【GoogleCodeJam-apactest-roundD-C】SortAScrambledItinerary

【GoogleCodeJam-apactest-roundD-C】SortAScrambledItinerary

玛丽准备从城市A飞到城市B,中间需要经过几次转机,为此她买了几张机票,每张机票可以从一个城市飞到另一个城市,但是很不幸的是她把飞机票的顺序给弄混了,现在需要你帮她把机票的顺序排好。值得注意的是每个城市不会重复飞两次

限制条件

T个测试样例,每个样例有N张机票

1<=T <=100

1<=N<=10000

 

输入

2

1

SFO

DFW

4

MIA

ORD

DFW

JFK

SFO

DFW

JFK

MIA

 

输出

Case #1: SFO-DFW

Case #2: SFO-DFW DFW-JFK JFK-MIA MIA-ORD

 

分析:

由于每个城市不会被重复飞到,因此每个城市至多会飞进一次,飞出一次。把飞进这个城市的起点记为该城市的父亲,这个城市飞出的终点记为该城市的儿子,则整个飞行的起点只有儿子没有父亲,整个飞行的终点只有父亲没有儿子。用数组存储机票信息,顺序扫描一遍,没有父亲的元素即为起点,再从起点开始向儿子节点遍历整个数组,这样既可按顺序输出飞行的路径。


代码

#include<string>
#include<vector>
#include<fstream>
#include<iostream>
#include<map>
#include<queue>
#include<algorithm>
#include<time.h>
#define MAXN 11000
#define PII pair<int,int>
#define VI vector<int>
#define MAT vector<vector<int>>
#define LL long long
using namespace std;

struct node{
	int father;
	int son;
	node(int a,int b):father(a),son(b){};
};

int main(){
	time_t start,stop;
	start=time(NULL);
	int T;
	ifstream fin;
	ofstream fout;
	fin.open("C-large-practice.in");
	fout.open("C-large-practice.out");
	fin>>T;
	for(int t=0;t<T;t++){
		int N,result,cityCount=0;
		string from,to;
		map<string,int> m;
		map<int,string> reverseM;
		vector<node> cities(MAXN,node(-1,-1));
		fin>>N;
		for(int i=0;i<N;i++){
			fin>>from>>to;
			if(m[from]==0){
				m[from]=++cityCount;	
				reverseM[cityCount]=from;
			}
			if(m[to]==0){
				m[to]=++cityCount;
				reverseM[cityCount]=to;
			}
			int fromIndex=m[from],toIndex=m[to];
			cities[fromIndex].son=toIndex;
			cities[toIndex].father=fromIndex;
		}
		//for(int i=1;i<=cityCount;i++){
		//	cout<<cities[i].father<<" "<<cities[i].son<<endl;
		//}
		//for(int i=1;i<=cityCount;i++){
		//	cout<<reverseM[i]<<endl;
		//}
		fout<<"Case #"<<t+1<<": ";
		for(int i=1;i<=cityCount;i++)
			if(cities[i].father==-1){
				int currentIndex=i,nextIndex=-1;
				while(cities[currentIndex].son!=-1){
					nextIndex=cities[currentIndex].son;
					fout<<reverseM[currentIndex]<<"-"<<reverseM[nextIndex]<<" ";
					currentIndex=nextIndex;
				}
			}
		fout<<endl;
		cout<<"solve case "<<t+1<<endl;
	}
	stop=time(NULL);
	cout<<"total time used: "<<stop-start<<"s"<<endl;
	system("pause");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值