http://acm.timus.ru/problem.aspx?space=1&num=1069
建树呀 水题
代码:
#include<iostream> #include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> #include<vector> #include<set> #include<map> #include<string> #include<queue> #include<stack> #include <iomanip> using namespace std; #define LL long long const int INF=0x3f3f3f3f; priority_queue<int,vector<int>,greater<int> >qt; const int N=10005; int a[N]; int num[N]; vector<int>tree[N]; int main() { //freopen("data.in","r",stdin); int n=1; memset(num,0,sizeof(num)); while(cin>>a[n]) { ++num[a[n]]; ++n; } for(int i=1;i<=n;++i) tree[i].clear(); for(int i=1;i<=n;++i) if(num[i]==0) qt.push(i); for(int i=1;i<n;++i) { int k=qt.top();qt.pop(); tree[a[i]].push_back(k); tree[k].push_back(a[i]); --num[a[i]]; if(num[a[i]]==0) qt.push(a[i]); } for(int i=1;i<=n;++i) { cout<<i<<":"; sort(tree[i].begin(),tree[i].end()); for(unsigned int j=0;j<tree[i].size();++j) { cout<<" "<<tree[i][j]; } cout<<endl; } return 0; }