10763 - Foreign Exchange

来源:互联网 发布:强制竖屏软件 编辑:程序博客网 时间:2024/05/16 11:53

Your non-profitorganization (iCORE - international Confederationof Revolver Enthusiasts) coordinates a very successfulforeign student exchange program. Over the last few years, demand hassky-rocketed and now you need assistance with your task.

The program yourorganization runs works as follows: All candidates are asked for their originallocation and the location they would like to go to. The program works out onlyif every student has a suitable exchange partner. In other words, if a studentwants to go from A to B, there must be another student who wants to go from Bto A. This was an easy task when there were only about 50 candidates, howevernow there are up to 500000 candidates!

Input

The input filecontains multiple cases. Each test case will consist of a line containing n -the number of candidates(1≤n≤500000), followed by n linesrepresenting the exchange information for each candidate. Each of these lineswill contain 2 integers, separated by a single space,representing the candidate's original location and the candidate's targetlocation respectively. Locations will be represented by nonnegative integernumbers. You may assume that no candidate will have his or her originallocation being the same as his or her target location as this would fall intothe domestic exchange program. The input is terminated by a case where n = 0;this case should not be processed.

 

Output

For each testcase, print "YES" on a single line if there is a wayfor the exchange program to work out, otherwise print"NO".

 

SampleInput                               Outputfor Sample Input

10

1 2

2 1

3 4

4 3

100 200

200 100

57 2

2 57

1 2

2 1

10

1 2

3 4

5 6

7 8

9 10

11 12

13 14

15 16

17 18

19 20

0

 

YES

NO

代码:

#include<iostream>

#include<map>

using namespacestd;

 

multimap<int,int>exchange;

multimap<int,int>::iteratorit;

 

int main()

{

    int n;

 

    while(cin>>n && n)

    {

        exchange.clear();

        for(int i=0; i<n; ++i)

        {

            int from, to;

            cin>>from>>to;

            bool flag = true;

            for(it= exchange.find(to); it!=exchange.end() && it->first== to; ++it)

            {

                if(it->second == from)

                {

                    exchange.erase(it);

                    flag = false;

                    break;

                }

            }

            if(flag == true)

            {

                exchange.insert(make_pair(from, to));

            }

        }

 

        if(exchange.empty())

        {

           cout<<"YES"<<endl;

        }

        else

        {

           cout<<"NO"<<endl;

        }

    }

    return 0;

}

解析:

利用multimap存储,每次读入一组新的数据,先判断能否找到匹配的,找到则删除找到的数据,否则插入新数据,最后若multimap为空.则证明每一个学生都成功,输出YES.

0 0