每日一题之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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值