Boarding Passes

64 篇文章 0 订阅
22 篇文章 0 订阅

题目1 : Boarding Passes

时间限制:10000ms

单点时限:1000ms

内存限制:256MB

描述

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

 

找出起点 和终点

根据图论知识我们知道对于起点有出度-入度=1,而对于终点有入度-出度=1。

需要注意可能同一地点经过多次,所以并不能简单认为起点入度是0,终点出度是0。

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        int n=Integer.parseInt(in.nextLine());
        Map<String,Integer> outMap=new HashMap<>(n);
        Map<String,Integer> inMap=new HashMap<>(n);
        for(int i=0;i<n;i++){
            String[] arr=in.nextLine().split("\\s+"); // 至少出现一个空格
            int outNum=outMap.getOrDefault(arr[0],0);
            outMap.put(arr[0],outNum+1);
            int inNum=inMap.getOrDefault(arr[1],0);
            inMap.put(arr[1],inNum+1);
        }

        String start=null;
        String end=null;
        Set<String> keys=new HashSet<>(n);
        keys.addAll(outMap.keySet());
        keys.addAll(inMap.keySet());
        for(String s:keys){
            int outNum=outMap.getOrDefault(s,0);
            int inNum=inMap.getOrDefault(s,0);
            if(outNum-inNum==1) start=s;
            if(inNum-outNum==1) end=s;
        }

        System.out.println(start+" "+end);
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值