C. Mail Stamps
Time Limit: 20 Sec
Memory Limit: 256 MB
题目连接
http://codeforces.com/problemset/problem/29/C
Description
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Sample Input
2
1 100
100 2
Sample Output
2 100 1
HINT
题意
给你一条链,让你从头输出到尾
题解:
离散化一下,然后在跑一发拓扑排序就好了
代码
//qscqesze #include <cstdio> #include <cmath> #include <cstring> #include <ctime> #include <iostream> #include <algorithm> #include <set> #include <vector> #include <sstream> #include <queue> #include <typeinfo> #include <fstream> #include <map> #include <stack> typedef long long ll; using namespace std; //freopen("D.in","r",stdin); //freopen("D.out","w",stdout); #define sspeed ios_base::sync_with_stdio(0);cin.tie(0) #define maxn 2000001 #define mod 1000000007 #define eps 1e-9 int Num; char CH[20]; const int inf=0x3f3f3f3f; inline ll read() { int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } //************************************************************************************** int n; vector<int> q; map<int,int> H; map<int,int> h; int a[maxn]; int b[maxn]; vector<int> e[maxn]; int d[maxn]; int vis[maxn]; int main() { n=read(); for(int i=0;i<n;i++) { a[i]=read(); b[i]=read(); q.push_back(a[i]); q.push_back(b[i]); } sort(q.begin(),q.end()); q.erase(unique(q.begin(),q.end()),q.end()); for(int i=0;i<q.size();i++) H[q[i]]=i,h[i]=q[i]; for(int i=0;i<n;i++) { e[H[a[i]]].push_back(H[b[i]]); e[H[b[i]]].push_back(H[a[i]]); d[H[a[i]]]++; d[H[b[i]]]++; } int flag=1; queue<int> qq; for(int i=0;i<q.size();i++) { if(d[H[q[i]]]==1) { qq.push(H[q[i]]); vis[H[q[i]]]=1; break; } } while(!qq.empty()) { int v=qq.front(); printf("%d ",h[v]); vis[v]=1; qq.pop(); for(int i=0;i<e[v].size();i++) { if(vis[e[v][i]]) continue; d[e[v][i]]--; if(d[e[v][i]]<=1) qq.push(e[v][i]); } } }