每日一题之hiho213周 Boarding Passes

描述
Long long ago you took a crazy trip around the world. You can not remember which cities did you start and finish the trip. Luckily you have all the boarding passes. Can you find out the starting city and ending city?

输入
The first line contains a number N denoting the number of boarding passes. (1 <= N <= 100)

The following N lines each contain a pair of cities (the city name consists of no more than 10 capital letters)

It is guaranteed that there is always a valid solution.

输出
The starting and ending cities separated by a space.

样例输入
4
SFO HKG
PVG BOS
HKG ABC
ABC PVG
样例输出
SFO BOS

题意:

给n个城市对,找出起点城市和终点城市,保证有合法的解。

思路:

这题需要注意的是有可能某个城市会经过多次,所以不能简单的认为起点的入度为0而终点的出度为0。这样判断只能得60分。正解是 对于起点其出度-入度 = 1,对于终点则是 入度-出度 = 1

#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>

using namespace std;

int in[205];
int out[205];


int main()
{
    map<string,int>str2id;
    map<int,string>id2str;
    map<string,int>::iterator it;
    int n;
    string s1,s2;
    cin >> n;
    int id = 0;
    for (int i = 0; i < n; ++i) {
        cin >> s1 >> s2;
        it = str2id.find(s1);
        if (it == str2id.end()) {
            str2id[s1] = id;
            id2str[id] = s1;
            ++id;
        }

        ++out[str2id[s1]];

        it = str2id.find(s2);
        if (it == str2id.end()) {
            str2id[s2] = id;
            id2str[id] = s2;
            ++id;
        }

        ++in[str2id[s2]];

    }
    int flag = 0;
    for (int i = 0; i < id; ++i) {
        if (flag > 2) break;
        if (out[i] - in[i] == 1) s1 = id2str[i],++flag;
        if (in[i]- out[i] == 1) s2 = id2str[i],++flag;
    }

    cout << s1 << " " << s2 << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/u014046022/article/details/81269426
今日推荐