For the exchange program to be successfully implemented, every student who wants to move from to must have another student who wants to move from to . In other words, each pair must have a corresponding reverse pair . Identical pairs may appear multiple times.
We'll use a multiset to store the pairs. The algorithm works as follows:
For each input pair , check whether the pair is present in the multiset.
If such a pair is found, remove it from the multiset, thereby forming a valid exchange pair.
If the reverse pair does not exist, add the current pair to the multiset.
After processing all the students, there are two possible cases:
The multiset is empty — this means that for every pair , a corresponding reverse pair was found, and the exchange program can be successfully carried out.
The multiset is not empty — this means that some students do not have a suitable partner, and the exchange program cannot be completed.
Based on this, the output is either "YES" or "NO".
Example
In the first test, every pair has a corresponding reverse pair . In the second test, none of the students' requests can be fulfilled.
Algorithm implementation
Declare a multiset of pairs . During execution, it will store only those pairs for which a corresponding reverse pair has not yet been found.
multiset<pair<int,int> > s;Read the number of test cases .
scanf("%d",&t);Process the test cases sequentially.
while (t--)
{Read the number of students .
scanf("%d", &n); Before processing each test case, clear the multiset.
s.clear();Process the students' requests sequentially.
for (i = 0; i < n; i++)
{Read the pair and look for a student with the opposite exchange direction.
scanf("%d %d", &a, &b);
auto it = s.find({ b, a });If the reverse pair is not found, the current pair is added to the multiset .
If the reverse pair is found, it is removed from , since a partner for this exchange has been found.
Thus, always contains only those pairs for which a match has not yet been found.
if (it == s.end()) s.insert({ a, b });
else s.erase(it);
}If, after processing all students, the multiset is empty, it means that a reverse pair was found for every pair, and the exchange program can be successfully carried out. Otherwise, print "NO".
if (s.empty()) printf("YES\n");
else printf("NO\n");
}