题目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
扫描二维码关注公众号,回复:
4788813 查看本文章
找出起点 和终点
根据图论知识我们知道对于起点有出度-入度=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);
}
}