I have a algorithm that solves for 'affected people' in given input. I have to solve the list of people who are affected. People are denoted by numbers, and two people interact with each other at given time N. If either of the person is affected, the other becomes affected too.
First, N(number of people) and M(total interactions) are given. and then (P1 P2 time) are given across M lines.
For example, 5 5
2 3 1
1 2 2
3 4 2
1 3 3
2 5 4
is given.
This means that there are 5 people, who have 5 interactions, which followed by 5 lines denoting person 2 and 3 meeting at time 1, 1 and 2 meeting at time 2, 3 and 4 meeting at time 2, and so on.(times may not be ordered).
At the start, person 1 is always infected.
So at time 2, person 1 and 2 meets, making person 2 infected, person 1 and 3 meets at time 3, making person 3 infected, and finally, person 2 and 5 meets at time 4, making person 5 infected.
This makes person 1, 2, 3, 5 infected at the end.
Interactions happen by time, and multiple interactions can happen simultaneously, and if that is the case, most people have to be considered to be affected.
For Example, if person 1 and 3 is infected, and (4 6 3) (3 6 3) is given as inputs, (3 6 3) has to be calculated first to get person 6 infected and person 4 infected as well.
To solve this question, I created this algorithm, and it has terrible running time, and I need help optimizing this algorithm.
inputs = input()
peopleNum = int(inputs.split()[0])
times = int(inputs.split()[1])
peopleMeet = {}
affectedPeople = [1]
for i in range(times):
occur = input()
person1 = int(occur.split()[0])
person2 = int(occur.split()[1])
time = int(occur.split()[2])
if not time in peopleMeet:
peopleMeet[time] = [(person1, person2)]
else:
for occur in range(len(peopleMeet[time])):
if set(peopleMeet[time][occur]) & set((person1,person2)):
peopleMeet[time][occur] = peopleMeet[time][occur] + ((person1,person2,))
break
if occur == (len(peopleMeet[time]) - 1):
peopleMeet[time].append((person1,person2))
for time in sorted(peopleMeet):
for occur in peopleMeet[time]:
if set(affectedPeople) & set(occur):
affectedPeople.extend(list(occur))
print(' '.join([str(x) for x in set(affectedPeople)]))
I'm very new at stack overflow, and I'm not used to the formatting and the posting guidelines, so I'm sorry if I'm wrong. And thank you in advance.