We need to solve the problem: Given n messages in non-decreasing time order (could be equal times? Yes, "non-decreasing order of ti's" means ti <= t_{i+1}), each message from sender Ai to recipient Bi at time ti. For each unordered pair of users (A, B) (A != B), they are considered friends if: there exists a message from A to B at time t1 and a message from B to A at time t2 such that 0 < t2 - t1 ≤ d. Or equivalently, if at least one answered the other's message within d seconds (excluding simultaneous? condition says 0 < t2 - t1 ≤ d, so strictly positive difference, so they must be at different times, and t2 > t1 must hold because t2 - t1 > 0). Also, it says "A answered at least one B's message or B answered at least one A's message". Which covers both directions: A answering B (meaning B sent first, then A responded) and B answering A (A sent first, then B responded). So the condition reduces to existence of two messages: one from X to Y at time t1 and one from Y to X at time t2 with 0 < t2 - t1 ≤ d.
We need to output all unordered pairs of users that satisfy this condition.
Constraints: n, d ≤ 1000, names up to 20 lowercase letters, ti up to 10000. So we can brute force across messages O(n^2) perhaps: for each message, consider earlier messages? But n up to 1000 so O(n^2) is okay. However, we need to consider pairs of messages that are in opposite directions. Also we need to output each pair of users only once.
Simplify: We can maintain for each unordered pair of users a boolean flag if they are friends. We'll process messages sequentially. For each new message (A->B at time t), we need to check if there exists any previous message from B to A with time t' such that 0 < t - t' ≤ d. If yes, then mark (A,B) as friends. Also check the reverse? Actually condition also includes A answering B, i.e., if a later message from B to A answers this one: but that will be handled when processing that later message. So we just need for each message, look for previous messages that could be answered by this message (i.e., earlier messages from the opposite direction). Since all messages are processed in non-decreasing time order, we can maintain a list of messages, but we only need to look back at messages within a time window of d (since t - t' must be ≤ d). Since d <= 1000, we could also just scan all previous messages but that's still O(n^2) = 1e6, fine. Also ti non-decreasing, but they can be equal: for equal times, condition requires t2 - t1 > 0, so equal times do not count. So we must ensure t2 > t1 strictly.
Thus algorithm:
Initialize empty set of friend pairs (unordered). Use a dictionary/hash to map pair (user1, user2) with user1<user2 lexicographically or sorted to store if they are friends.
We'll keep a list of all messages: maybe as tuples (sender, receiver, time).
Then for i from 0 to n-1:
(A, B, t) = messages[i]
For j from 0 to i-1:
(A2, B2, t2) = messages[j]
If A2 == B and B2 == A and 0 < t - t2 <= d:
mark pair (A,B) as friends, add to set (maybe break loop if found)
// No need to check opposite direction? Because if A->B answered earlier B->A, then that earlier case is when we processed B->A we checked earlier messages? But when we processed B->A we might not have seen A->B yet because it's later. So only need to check the case where current message answers previous message. That covers both directions because for each pair of messages that satisfy condition, the later one will be processed and will detect the earlier one. So it's enough.
However, careful: If there are multiple messages in both directions, but some answers are from later message but the time difference > d. So only some qualify.
Edge: two messages with same time? not counted.
So O(n^2) with n=1000 -> max 1e6 iterations, each with simple string comparisons, fine.
But we must consider that the list might be large, but still fine.
Alternatively, we could use a map for each directed pair to store list of times or something. Since d and n small, it's okay.
But one nuance: The problem requires output each pair exactly once. So we can use a set of pairs (sorted order of names). Also note that we might mark friend pair multiple times, set ensures uniqueness.
Now we need to read input, parse strings and int. Then output number of pairs and each pair on its own line with names separated by space (any order). The order in pair: we can print the two names in any order? The example prints "petya vasya", but they appear as petya then vasya. However, problem says "You can print users in pairs and the pairs themselves in any order." That means for each unordered pair, you can output either order. So we can store in sorted order to avoid confusion.
Implementation:
Read n, d.
messages = []
for i in range(n):
line = input().split()
A, B, t = line[0], line[1], int(line[2])
messages.append((A, B, t))
friends = set() # store tuple (u,v) with u<v lexicographically
For i in range(n):
A, B, t = messages[i]
# check previous messages
for j in range(i):
A2, B2, t2 = messages[j]
if A2 == B and B2 == A: # opposite direction
diff = t - t2
if diff > 0 and diff <= d:
# add pair
if A < B:
friends.add((A, B))
else:
friends.add((B, A))
# we could break to avoid unnecessary checks? But we need to check all because maybe previous qualifies but we already added, but break is optional optimization.
# However, if we break, it's fine because we already know they are friends; more answers don't change anything.
# But careful: maybe there is also a later message that could cause another pair? But we only care about this pair.
break # optional.
Output
print(len(friends))
for u, v in friends:
print(u, v)
But is this enough? Let's test with given example.
Example 1:
n=4,d=1
Messages:
1: vasya petya 1
2: petya vasya 2
3: anya ivan 2
4: ivan anya 4
Processing:
i=0: no previous -> nothing.
i=1: A='petya', B='vasya', t=2. Check j=0: A2='vasya', B2='petya', t2=1. A2==B? vasya==vasya? Actually B is 'vasya', A2='vasya' so yes. B2=='petya' == A? yes. diff=2-1=1 <=1 and >0 -> add (petya, vasya) or (vasya, petya). In our code, we'll add sorted: ('petya','vasya')? Compare: 'petya' < 'vasya'? 'p' < 'v' yes, so add ('petya','vasya').
i=2: anya ivan 2. Check previous j=0: A2='vasya', B2='petya' no match. j=1: petya vasya no match. No add.
i=3: ivan anya 4. Check j=0,1,2. j=2: anya ivan 2: A2='anya', B2='ivan'; A2 == B? B='anya'? Actually B='anya'? In i=3: A='ivan', B='anya', t=4. Check j=2: A2='anya', B2='ivan'. A2==B? anya==anya yes; B2==A? ivan==ivan yes. diff=4-2=2 > d=1 => not added. j=0,1 also not. So only one pair.
Matches.
Second example: 1 message, no friend pairs, output 0.
Now consider some edge cases:
-
Messages with same users but multiple times: could be friend already added.
-
If there is a message from A to B at time 5, and later from B to A at time 5? diff=0 not counted, so not friends. If later at time 5.5? diff=0.5? but ti are integers, so all times are integers. So diff integer.
-
If d=0, condition says 0 < t2 - t1 ≤ d, so if d=0, no pair can satisfy because t2-t1 must be >0 and <=0 impossible. So output 0. But d≥1 according to constraints? Actually d can be 1 to 1000. But problem statement says 1 ≤ n, d ≤ 1000. So d>=1. So fine.
-
However, it says d can be up to 1000 but also note ti up to 10000.
-
If there are multiple messages that could qualify, we add only once.
Now complexity O(n^2) fine.
But we can also improve using maps for each directed pair. But not needed.
One nuance: The input is given in non-decreasing order of ti, but not strictly increasing. So we need to ensure we only consider t2 < t1 (strict). Since we check diff > 0, equal times are excluded.
Also note that when we process each message, we check all previous messages, but messages at same time: if current message time equals previous message time, then diff = 0, so condition fails. So we won't add. Good.
Thus algorithm is correct.
Now we have to output each pair exactly once. In our approach, we add sorted tuple to set, that ensures uniqueness.
Now let's think about potential pitfalls: names can be up to 20 chars; we can store as strings. Set of tuples is fine.
Edge case: Could there be a case where two messages in opposite direction exist but the later one is not within d, but there is an earlier message that qualifies with a later message? Actually the condition only requires existence of any pair (i, j) such that messages i and j are opposite direction and 0 < t_j - t_i ≤ d. In chronological order, we only detect when later message answers earlier. So if there are messages: A->B at t=5, B->A at t=10, d=6 -> diff=5, qualifies. When we process later message (t=10) we will check earlier message and detect. If there are multiple messages, we can detect at first qualifying pair. So fine.
But what if the qualifying pair is such that the earlier message is not from the opposite direction of the later, but rather the later message is from the same direction? That can't be because condition requires opposite direction. So no.
Thus algorithm correct.
Now let's verify with some other test:
Case: n=3, d=5
A B 1
C D 2
B A 3
Processing: i=2: A='B', B='A', t=3, check j=0: A2='A', B2='B', t2=1 -> opposite, diff=2 ≤5, qualifies. Good.
Case: multiple pairs: A B 1, B A 2, A B 3, B A 4, d=1. We add friend at i=1, i=3 also would try but friend already added. So output one pair.
Now think about scenario where A and B have messages in both directions but only some meet d. For example: A->B at t=1, B->A at t=5, d=3 => not qualify. But later A->B at t=6, B->A at t=7, d=3 => qualifies. When we process i=3 (B->A at 7) check previous messages, see A->B at 6? yes diff=1, qualifies. So add.
Alright.
Now consider memory: storing all messages in list of tuples: n up to 1000, fine.
One more nuance: The log lines are in non-decreasing order of ti's. But note that the senders and recipients are strings; we need to ensure that we don't treat "A" and "a" as same? All lowercase letters, so fine.
Now we can implement.
But the problem might be from Codeforces (Problem "Friends" maybe). Actually it's Codeforces Beta Round #93 (Div.2) Problem B? I'm not sure. However, some solutions used a map to store last message time from one user to another for efficiency, but n small.
Nevertheless, I'll implement O(n^2) solution as it's straightforward.
But I'll also add early break after finding a friend for a pair? However, if we break after first qualifying previous message, we might miss later checks? But once we have already added pair to set, we don't need to check further for that pair. However, the current iteration (i) only involves that same pair (since the condition only cares about A and B). So we could break out of j loop once we find a qualifying message, because we don't need to check others; we already know they are friends. But be careful: what if there are multiple users? The j loop might contain messages from other users; we can only break if we have found a match for (A,B). But we cannot break the entire j loop if we encounter a match from a different pair? That's irrelevant. However, we could maintain a flag and break when found for that specific pair. But O(n^2) is still fine. We can just break when we add the pair, because further checks won't change anything. But we must be careful: after adding pair, we might still want to continue checking other j for potential other pairs? But the current message is from A to B. Only possible friend pair from this message is (A,B). So if we confirm (A,B) are friends, we can break entirely from j loop; no need to check other j's because they all are other pairs and won't yield any other friendship from this message (since the only possible friendship involves the two participants of the current message). But could it be that this message also qualifies as an answer to a message from some other user? No, because condition requires opposite direction: for the current message from A to B, to be considered an answer, the earlier message must be from B to A. So it only involves A and B. So once we find that, we can break out of the inner loop. So we can add a break.
But we also could add an early check: if (A,B) already in friends set, then skip inner loop altogether, because we already know they are friends. That would reduce work.
So:
if (A<B) pair = (A,B) else (B,A)
if pair not in friends:
for j in range(i):
... if match and condition:
friends.add(pair)
break
Yes.
Now what about the scenario where we process a message and (A,B) already friends? Then skip inner loop.
That's efficient.
Now also note that if we skip inner loop when already friends, we might miss the case where the current message is from A to B and there is also a later message from B to A that could be answered? But that will be handled when processing that later message. So it's fine.
Now let's consider another nuance: Suppose we have messages: A->B at t=1, then later B->A at t=1000, d=1000. And before that, we also have A->B at t=500. When we process B->A at t=1000, we need to check previous messages: A->B at t=1 and t=500. Both have diff 999 and 500, both ≤ d, so qualifies. If we added friend pair at first match (t=1) and then break, that's fine. So algorithm works.
Thus we can implement as described.
Now we need to output k and then each pair. The pairs can be printed in any order; I'll just iterate over the set.
Now test with sample.
Now also test with custom:
Input:
2 10
alice bob 5
bob alice 15
-> diff=10, qualifies (0<10<=10) yes -> friend.
Our code: i=0 nothing, i=1: A='bob', B='alice', t=15. pair sorted = ('alice','bob'). Not yet friends. Loop j=0: A2='alice', B2='bob', t2=5. Condition: A2==B? 'alice'=='alice' yes, B2==A? 'bob'=='bob' yes, diff=10>0 and <=10 -> add, break. Output: 1 alice bob. Good.
Now with equal times: 2 10, a b 0, b a 0 -> diff=0, not added.
Now with multiple pairs: 4 100
a b 0
c d 1
b a 2
d c 3
-> Both pairs friends.
Our code: i=0: no. i=1: no. i=2: A='b',B='a', t=2, check j=0: A2='a',B2='b',t2=0 -> diff=2 <=100 -> add (a,b). i=3: A='d',B='c',t=3, check j=1: A2='c',B2='d',t2=1 -> diff=2 -> add (c,d). Good.
Now with overlapping names: We need to be careful about sorting the pair names to ensure consistent ordering. Using tuple of (min, max) is fine. Since all strings.
Implementation details:
We'll read input using sys.stdin.read().splitlines() or simple input().
We'll parse first line: n, d = map(int, input().split())
Then messages = [].
But note: The lines contain two strings and an integer. We'll read each line as tokens.
Now note that n up to 1000, reading line by line fine.
Now let's think about potential pitfalls: The input lines are in non-decreasing order of ti, but there could be multiple messages with same time. Already handled.
Now I think solution is correct.
However, I recall that in some Codeforces problem "Friends" the approach required careful handling of the fact that there might be messages where A sends to B, then later B sends to A, but there might also be earlier messages that could cause false detection due to time difference? But our condition checks strict diff > 0, so okay.
Now let's verify with an edge case: d is big, up to 1000, but times up to 10000, diff could be up to 10000. But we only check diff <= d. So if d=1000, diff could be >1000, we ignore.
Now is there any scenario where we might need to consider both directions of answering? Actually "A answered at least one B's message or B answered at least one A's message." So it's exactly as we have. So our detection covers both cases: either the current message answers a previous one (B answered A) or later message will answer this one (A answered B). So we only need to detect one case.
Now, think about scenario where there are three messages: A->B at t=1, B->A at t=3, A->B at t=5, d=2. The pairs: (t=1, t=3): diff=2 qualifies. (t=3, t=5): diff=2 qualifies. So they are friends. Our code: i=0: nothing; i=1: A='B',B='A', t=3. Check j=0: A2='A',B2='B', t2=1 diff=2 -> add. i=2: A='A',B='B', t=5. Pair already friends, so skip inner loop. So we correctly output 1 pair. Good.
Now scenario: A->B at t=1, B->C at t=2, C->A at t=3, d large. But pairs only considered between A and B if they exchange messages. So no cross.
Now correctness.
Now for output: Print number of pairs, then each pair on a separate line, with names separated by a space. We should not output trailing spaces.
Now let's implement.
But I'm a ChatGPT. So I need to write final answer as Python code.
Potential improvements: Use a dictionary to store for each directed pair the list of times, then for each message (A->B, t), we can check times of B->A and see if any t' such that 0 < t - t' ≤ d. That would be more efficient but not required.
Given constraints, O(n^2) fine.
Now let's consider memory: Set of friend pairs might be up to number of distinct pairs. n messages can involve up to O(n) users, but pairs up to O(m^2) where m is number of users. But m could be up to about 2n (each message involves two distinct users). So m <= 2000, pairs up to ~2e6, which is big, but actual friendships may be many. However, does the problem have such scenario? With n=1000, worst-case number of distinct users could be 2000? Actually each message involves two distinct users. If all messages are between distinct pairs, you could have up to 2000 distinct users (since each message introduces two new users? But there are only 1000 messages, so maximum distinct users is at most 2000). Number of unordered pairs among 2000 users is about 2 million. Could the answer be up to 2 million? Possibly, but each pair must have at least one answering interaction, which requires at least two messages between them (one in each direction) within time constraint d. With n=1000 messages, you cannot have more than 500 pairs that each have at least two messages (since each such pair uses at least 2 messages). Actually you can have overlapping: one message could be used for multiple pairs? No, each message is between a specific pair, so each pair that becomes friends must have at least one message in each direction. So at most floor(n/2) pairs? Wait, not exactly: if you have messages: A->B, B->A, C->D, D->C, E->F, F->E etc., each pair uses two messages. So maximum number of friend pairs is n/2 (if n even) and all messages form disjoint pairs of bidirectional exchanges. So maximum k <= 500. But is it possible for a pair to become friends with only one bidirectional exchange? Yes. And you could have many pairs that are friends but they share some messages? For a pair to be friends, we need at least one message in each direction. So each pair that is friends requires at least two messages that involve exactly those two users. However, a message could serve for multiple pairs if it involves more than two users? No, each message has exactly one sender and one recipient. So a message can only belong to a specific ordered pair (sender, receiver). Therefore, the total number of friend pairs is at most the number of unordered pairs (A,B) such that there is at least one message A->B and at least one B->A. This could be as high as the number of unordered pairs among users, but each such unordered pair would require at least two messages (one each direction). Since total messages n=1000, the maximum number of such unordered pairs is at most 500, because each such pair consumes at least 2 messages, and messages are distinct. However, it could be less if some messages are not part of any bidirectional pair? But if we have many messages that are all between a set of users in both directions, each pair could be supported by many messages. But each pair still needs at least two messages. So the maximum distinct unordered pairs with at least one message in each direction is at most floor(n/2) = 500. So k <= 500, which is small.
Thus set of friends is small.
So our solution is fine.
Now implement.
Pseudo-code:
def solve():
import sys
input_data = sys.stdin.read().strip().splitlines()
if not input_data:
return
first = input_data[0].split()
n, d = map(int, first)
messages = []
for i in range(1, n+1):
parts = input_data[i].split()
if len(parts) < 3: # should not happen
continue
A, B, t = parts[0], parts[1], int(parts[2])
messages.append((A, B, t))
friends = set()
for i in range(n):
A, B, t = messages[i]
# ensure sorted pair
if A < B:
pair = (A, B)
else:
pair = (B, A)
if pair in friends:
continue
# check previous messages
for j in range(i):
A2, B2, t2 = messages[j]
# check if opposite direction
if A2 == B and B2 == A:
diff = t - t2
if 0 < diff <= d:
friends.add(pair)
break
# output
out_lines = [str(len(friends))]
for u, v in sorted(friends): # sorted to have deterministic output, not required but helps
out_lines.append(f"{u} {v}")
sys.stdout.write("\n".join(out_lines))
But we might sort pairs to produce stable output for testing, but not required. In problem, you can print in any order.
Now test with sample:
Input:
4 1
vasya petya 1
petya vasya 2
anya ivan 2
ivan anya 4
Our code: messages as above. friends set adds ('petya','vasya') maybe? Actually pair sorted: vasya, petya? Since 'petya'<'vasya', pair = ('petya','vasya'). So output will be: 1 \n petya vasya. That matches sample except sample had "petya vasya". Good.
Now second sample: 0 output.
Now additional test:
Input:
2 10
a b 0
b a 10
-> diff=10 qualifies. pair = ('a','b'). Output 1 \n a b.
Now check for equal times: 2 10 a b 5 b a 5 -> diff=0 -> no friends. Output 0.
Now test for multiple pairs:
3 100
x y 1
y x 2
a b 3
-> friends set: after i=1 add (x,y). Output: 1 \n x y
Now test for case where a pair becomes friends later after earlier attempt failed:
3 2
a b 1
c d 2
b a 4
Processing: i=2: A='b',B='a', t=4. Check j=0: A2='a',B2='b',t2=1 diff=3 >2 -> no. No other j. So friends remains empty. So not friends. Indeed, diff=3 > d=2, so no friendship. Ok.
Now test with many messages to ensure early break works.
Now think about scenario: The message log may contain lines where sender and receiver are same? The problem says no user sent a message to himself, so no.
Now one more nuance: Could there be a scenario where a pair becomes friends not only by direct answering, but by transitive? No, definition only direct exchange.
Thus solution correct.
Now complexity O(n^2) time, O(n) space (plus set of pairs). n=1000, fine.
We could also use a dictionary mapping from (sender, receiver) to list of times, and then for each message (A->B, t), we check in map for (B, A) times that are in [t-d, t-1] using binary search (since times are sorted if we insert in order). But not necessary.
I think it's fine.
Now final step: Write answer.
But I'm ChatGPT, and I need to output final answer as Python code with solve() function and main guard.
Let's produce final answer.
Also note: The input reading method using sys.stdin.read() is okay, but we could also use input() in a loop. Using sys.stdin.read() ensures no issues with large input? Not large anyway. I'll use sys.stdin.readline.
Better:
import sys
def solve():
data = sys.stdin.read().strip().splitlines()
if not data:
return
n, d = map(int, data[0].split())
messages = []
for i in range(1, n+1):
parts = data[i].split()
if len(parts) < 3:
continue
A, B, t = parts[0], parts[1], int(parts[2])
messages.append((A, B, t))
friends = set()
for i in range(n):
A, B, t = messages[i]
if A < B:
pair = (A, B)
else:
pair = (B, A)
if pair in friends:
continue
for j in range(i):
A2, B2, t2 = messages[j]
if A2 == B and B2 == A:
diff = t - t2
if 0 < diff <= d:
friends.add(pair)
break
# Output
out = [str(len(friends))]
# To have consistent output, sort the pairs
for u, v in sorted(friends):
out.append(f"{u} {v}")
sys.stdout.write("\n".join(out))
if name == "main":
solve()
But ensure to import sys.
Now maybe we need to handle case where n lines may have extra spaces? But not.
Now consider test when n=0? n>=1.
Now I think this is fine.
But I want to double-check the condition: "If 0 < t2 - t1 ≤ d, then user B's message was an answer to user A's one." So answer occurs only if later message is from the recipient of earlier message. So it's exactly our check.
Now one more nuance: The definition of friends: "Users A and B are considered to be friends if A answered at least one B's message or B answered at least one A's message." So if A answered B, that means there exists a message from B to A (t1) and later a message from A to B (t2) such that 0 < t2 - t1 ≤ d. So in our processing, when we get a message A->B (t2), we look for earlier B->A (t1) with diff conditions. That covers A answered B. And when we get B->A (t2), we look for earlier A->B (t1) covering B answered A. So yes.
Thus correct.
Now we can output.
Now it's time to produce the final answer.
But we need to provide a full solution explanation as well? The instruction says "Write final answer as Python code", but as ChatGPT in "Final" channel, we should output the code. Typically, for Codeforces problems, they expect just code. So I'll output final code.
One more thing: The problem statement may be from Codeforces and they require to use fast I/O? Not necessary. However, reading with sys.stdin.read is fine.
But sometimes using input() in Python 3 may be slower if many lines but n <=1000 so fine.
Thus final.
Now potential corner: The log lines are in non-decreasing order of ti, but we need to treat them as given. Our algorithm does not rely on sorting beyond that.
Now let's test with custom case where there are messages with same time, but also an opposite-direction message later. That we did.
Now test scenario where two messages satisfy condition in both directions? Actually if there is A->B at 1, B->A at 2 (d=1), then also B->A at 3? Not relevant.
Now consider scenario where there are two messages from A->B and B->A but the earlier is B->A and later A->B, but diff = exactly d, qualifies.
Now we are good.
Now I'd like to check if we need to consider that the messages are sorted but not necessarily strictly, so j loop includes earlier messages with same time. For a message at same time as current, diff=0, condition fails. So correct.
Now, also consider scenario where there is a message at time t and another at time t but in opposite direction? Then neither is later, but diff=0, so not answer. They can't be friends based on those two messages. However, they could become friends if there is another pair with non-zero diff. So our algorithm would handle.
Now I think it's correct.
Now final answer.
But wait, there is another nuance: The problem says: "If 0 < t2 - t1 ≤ d, then user B's message was an answer to user A's one." And then "Users A and B are considered to be friends if A answered at least one B's message or B answered at least one A's message." So the condition is symmetric. So if there is any pair of messages (one from A to B, one from B to A) with time difference within d and later message from the recipient of the earlier, then they are friends.
Now what about the case where there is a sequence: A->B at t1, B->A at t2, A->B at t3. If t2-t1 ≤ d, then they are friends (B answered A). If t3-t2 ≤ d, then also they are friends (A answered B). So if either condition holds, they are friends. In our algorithm, we will detect at i=1 (B->A) check j=0: qualifies if t2-t1 ≤ d, add. If not, at i=2 (A->B) check previous messages: j=1 (B->A) if t3-t2 ≤ d then add. So both conditions captured.
Now confirm that we do not miss when t2-t1 > d but t3-t2 ≤ d. Works.
Now consider if there are more messages: A->B at t1=0, B->A at t2=1000, d=500, not friends. Then later B->A at t3=1500, A->B at t4=1600, d=500. Now t4 - t3 = 100 ≤ 500, qualifies, add. In our algorithm: when processing i for t4 (A->B, t=1600), check previous messages, including j for t3 (B->A, t=1500) diff=100 <=500 -> add. Good.
Now consider scenario where A->B at t=1, B->A at t=1000, d=1000, qualifies diff=999? Actually 1000-1=999 ≤1000 -> qualifies. So at i=1 we add. Good.
Thus final solution.
Now implement with proper reading.
But we may need to handle that the input may contain extra blank lines? Probably not.
Now code:
I'll provide final answer.
But before final, I want to ensure that we are not missing a scenario where there are multiple users and the friend pair could be determined by a message that is not the current one? As we have covered.
Now let's consider performance: For each i, we might loop over all j < i, but break early when we find a qualifying answer. In worst-case if no friendships, we will do O(n^2) comparisons. n=1000 => 500k iterations, not 1e6? Actually sum_{i=1}^{n} (i-1) = n(n-1)/2 = ~500k. That's fine.
Now final code.
I'll include a main guard.
Now answer.
Wait, some solutions on Codeforces used a different approach: store for each ordered pair the last message time and check if current message from opposite direction occurs within d. But that's a one-way detection: For each message from A to B, check if there was a previous message from B to A with time >= t-d and < t. This can be done using dictionary of last time? Actually it's more subtle: Because condition requires existence of any earlier message from B to A within the interval (t-d, t). But if we only store the most recent time, will it suffice? Suppose we have earlier messages from B to A at times 1 and 100, d=50, and current A->B at t=110. The most recent from B to A is 100, diff=10 <=50, qualifies. If most recent is 100, it qualifies. But what if most recent is 90, diff=20 qualifies. But if most recent is 40, diff=70 >50, but there could be an earlier message at 55? Actually if we only store the most recent time, if it's too old (outside window), but there could be a later but still earlier than current message that is within window? But the most recent is by definition the one with the largest time less than current t. If that most recent time is not within (t-d, t), then any earlier times are even smaller, so they are further away, so they also won't be within (t-d, t). Because t - earlier_time > t - most_recent_time > d. So storing only the latest time before current is sufficient. However, this only works if we check only one direction: For each message from A to B, we need to know if there exists any previous message from B to A with time t2 such that t - t2 <= d and t > t2. Since messages are processed in non-decreasing order, the most recent B->A message before current time is indeed the maximum t2 < t (or <= t, but we need <). If the most recent one does not satisfy the condition (i.e., t - t2 > d or t2 == t), then no earlier one will satisfy because earlier ones are even smaller, thus t - earlier > t - recent > d. So condition reduces to checking just the most recent B->A message. That's a more efficient O(n) solution. But we need to be careful about equal times: if the most recent B->A has t2 == t (equal time), then diff=0, not allowed. But if there is also an earlier one that might satisfy? But if t2 == t is the most recent, there is no B->A with t2 < t. So any earlier B->A would have t2 < t, and t - t2 > 0, but since the most recent (with t2 as large as possible) is t, any earlier B->A would have t2 <= t-1? Actually if there is a B->A at time t, that's the latest possible (since we have non-decreasing order, there could be multiple messages at same time, but order among them is arbitrary? Actually the log is given in non-decreasing order. It's possible to have a B->A message at time t that appears earlier in the list than the current A->B message at same time t. Since times are same, the B->A might appear before or after. In processing order, if a B->A at time t appears before the current A->B at time t, then when we process the A->B, we consider that B->A as a previous message with t2 = t. That would be the most recent B->A (since it's at same time t). But the condition requires t - t2 > 0, so not satisfied. If there is an earlier B->A at t' < t, it might satisfy if t - t' <= d. But our "most recent B->A" would be that B->A at time t? Actually if there is both a B->A at time t and also earlier B->A, the most recent B->A with time <= t is the one at time t (since it's the maximum time <= t). So if that doesn't satisfy (diff=0), then we might incorrectly conclude no answer, even though there is a B->A at t' < t that could satisfy if t - t' <= d. Wait, but t - t' > 0, and if t - t' <= d, that would satisfy. However, if there is a B->A at time t (same time as A->B), then that B->A is more recent, but because its time equals t, we cannot use it because diff=0. But an earlier B->A at t' might satisfy. In this scenario, the most recent B->A (with time <= t) is the one at t, but it's invalid. Yet an earlier one could be valid. So storing only the most recent time fails in this case because the most recent is invalid due to equality, but a less recent could still be within d. However, we can handle this by storing the most recent B->A with time < t (strictly less). That is, we need to know the latest time from B->A that is strictly less than t. If that exists and satisfies t - t_last < = d, then they are friends. If there is a B->A at time t, we must ignore it for the purpose of checking answer to an A->B at time t, because it cannot be used (diff>0 required). But could it be used if we process a later A->B at time t+? That's fine.
Thus, we could maintain for each ordered pair (X,Y) the most recent time a message from X to Y was seen. Then for each new message (A,B,t), we check if we have stored for (B,A) a time t' such that 0 < t - t' <= d. However, if we store only the latest time, it might be t' that is equal to t (if there was a B->A at same t earlier in order). Then t - t' = 0, not allowed, but maybe there is an older t'' that would satisfy? But if there was a B->A at same t, that B->A could be after the older one? Actually we process messages in order, so if we encounter a B->A at time t, we update its latest time to t. Later we encounter A->B at time t (since times are non-decreasing, it's possible that there are multiple messages with same time; the order among them is given, but they all have same time). When we process A->B at time t, we look at the latest (B,A) time. If there was a B->A at the same time t that appeared earlier, then latest (B,A) = t, but that yields diff=0. However, is it possible that there is also an older B->A at time t' < t that would satisfy? Yes, if there was B->A at time t' earlier. But the latest time we stored is t, overwriting t'? We might lose t' if we only store the most recent. So we would incorrectly think no valid answer. To avoid this, we could store for each ordered pair all times? That's like my O(n^2) but we could also store a list of times, but again, might be okay given constraints.
Alternatively, we can store only the most recent time that is strictly less than current t. But when we have a B->A at time t, we should not let it invalidate previous earlier times for the purpose of later A->B at the same t? Actually if we only store the latest time, and we process messages in order, then when we see a B->A at time t, we update its stored time to t. Then later when we see an A->B at time t (still same t), the stored time for (B,A) is t, diff=0. So we will not consider the earlier t' even if it existed. But could we have such a scenario where there is a B->A at time t earlier than A->B at time t, but also an earlier B->A at t' that would qualify? Example: n=3, d=10. Messages: (B->A at t=1), (B->A at t=5), (A->B at t=5). The two B->A messages at times 1 and 5. Actually if they are both B->A, the latest is 5. When we process A->B at t=5, the stored (B,A) time is 5 (from the second B->A). diff=0 not allowed. However, there is also B->A at t=1, diff=4 which is ≤10, so they should be friends. But our simplified method would miss that. However, note that the order is non-decreasing: We have two B->A messages: one at t=1, then one at t=5, then A->B at t=5. When we process the first B->A at t=1, we store (B,A)=1. Then process second B->A at t=5, we update (B,A) to 5. Then process A->B at t=5. The stored (B,A)=5, diff=0 -> not friends. But there was an earlier B->A at 1 that would have qualified. However, because we updated to 5, we lost it. Could we still determine friendship? Yes, we need to consider if there exists any B->A time t' such that 0 < t - t' ≤ d. Since we replaced the stored value, we would not know about t'=1. So storing only the latest fails.
One could argue that we could store not only the latest but also ensure to check if the latest is not valid and there might be older valid. But we could store the latest that is strictly less than t, but we don't know if the latest is t. If latest is t, we could also store the previous latest? That would be like storing a deque of times? But easier: Because n is small, O(n^2) is simpler and robust.
Thus I'll stick to O(n^2).
But we can also improve by storing for each directed pair a list of times (since each pair may have multiple messages). Then for each message (A,B,t), we can binary search in the list of times for (B,A) for a time in (t-d, t). Since times are added in non-decreasing order, we can maintain pointers. But O(n^2) is simpler.
Given the problem constraints, O(n^2) is fine.
Now let's produce final answer.
However, I've seen some Codeforces solutions that used map<pair<string,string>, int> last; and then for each message (a,b,t), they check if last.count({b,a}) and t - last[{b,a}] <= d and t > last[{b,a}], then mark friendship. But that only works if there is at most one previous message per directed pair? As argued, it fails in certain cases where there are multiple messages from B to A and the most recent is equal to current t or just outside window but an older one is within. However, maybe the problem's constraints guarantee that there is at most one message per directed pair? Let's read the problem statement again: It does not say there is at most one message per directed pair. It can be many. So that approach is flawed. But I recall that many Codeforces participants used that and got accepted. Why? Let's test with the counterexample: d=10, messages: 1: b a 1; 2: b a 5; 3: a b 5. According to those flawed solutions, last[(b,a)] would be updated to 5 after second message, then when processing third, check if last[(b,a)] exists (5) and t - last =0 <=10? They also check t > last? They might check if t - last > 0. Usually they check if last contains key and t - last > 0 and t - last <= d. So they would see t - last = 0, not > 0, so they would not add. So they would output 0, but correct answer is 1. So is that a valid test case? Let's see: are messages allowed to have same time? Yes, times can be equal. Are multiple messages allowed between same users in same direction? Yes, nothing forbids. So that test case should be valid. But maybe the problem input guarantees that times are strictly increasing? It says "non-decreasing". So yes, they could be equal. So that would break the simple last-time approach.
But is it possible that the condition 0 < t2 - t1 ensures that if there is a B->A at time t, it cannot be used to answer an A->B at time t, but could be used if there is an earlier B->A. So it's a valid scenario. Yet I suspect that many Codeforces solutions used the "last" approach and passed. Possibly because the test cases did not include such tricky case? But the problem constraints do not forbid it. So we should implement a correct solution.
I'll stick with O(n^2) which is definitely correct.
But note: O(n^2) is O(10^6) worst-case, which is fine.
Now, we should consider an optimization to avoid scanning all previous messages: we could maintain a dictionary mapping from (sender, receiver) to a list of times, but for each query we need to see if there's a time in (t-d, t). Since d <= 1000 and times are integers up to 10000, we could also use a sliding window technique: maintain a queue of messages within last d time units? But messages are not sorted by time only globally, but times are non-decreasing, so we can maintain two pointers? Actually if we want to consider all previous messages within d time difference, we could keep a list of messages and since times are increasing, we can move a pointer to discard messages older than current time - d. But we also need to check only opposite direction. But that's more complex. Simpler: O(n^2) works.
Now I'll produce final code with Python.
But also need to consider that the input may contain trailing spaces, but split handles.
Now final code:
I'll write a solve() function and call it.
One more detail: When we output pairs, the problem says "You can print users in pairs and the pairs themselves in any order." So we can sort for deterministic output.
Now final answer.
But wait, there is a nuance: The problem statement says "0 < t2 - t1 ≤ d" and "Users A and B are considered to be friends if A answered at least one B's message or B answered at least one A's message." The definition of "A answered at least one B's message" means that there is a message from B to A at time t1 and a message from A to B at time t2 such that 0 < t2 - t1 ≤ d. So it's exactly as we have.
Now we need to ensure that we interpret the direction correctly: In the message log, each line is "Ai Bi ti", which means user Ai sent a message to user Bi at time ti. So for an answer, the answering message must be from the recipient of the original message. So our check is correct.
Now final.
I will output code as final answer. ```python
import sys
def solve() -> None:
data = sys.stdin.read().strip().splitlines()
if not data:
return
n, d = map(int, data[0].split())
messages = []
for i in range(1, n + 1):
parts = data[i].split()
# Each line: sender, receiver, time
sender, receiver, t = parts[0], parts[1], int(parts[2])
messages.append((sender, receiver, t))
friends = set() # stores unordered pairs as (name1, name2) with name1 < name2
for i in range(n):
A, B, t = messages[i]
# create canonical unordered pair
if A < B:
pair = (A, B)
else:
pair = (B, A)
# If already known as friends, skip further checks
if pair in friends:
continue
# Look for an earlier message from B to A that qualifies as an answer
for j in range(i):
A2, B2, t2 = messages[j]
if A2 == B and B2 == A: # opposite direction
diff = t - t2
if 0 < diff <= d:
friends.add(pair)
break # no need to check other earlier messages
# Output
out_lines = [str(len(friends))]
# Sort pairs for deterministic output (not required by the problem)
for u, v in sorted(friends):
out_lines.append(f"{u} {v}")
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()