原题链接:http://codeforces.com/contest/1041/problem/E
Tree Reconstruction
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from to . For every edge of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge (and only this edge) is erased from the tree.
Monocarp has given you a list of pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer — the number of vertices in the tree.
Each of the next lines contains two integers and each — the maximal indices of vertices in the components formed if the -th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print “NO” (without quotes).
Otherwise print “YES” (without quotes) in the first line and the edges of the tree in the next lines. Each of the last lines should contain two integers and — vertices connected by an edge.
Note: The numeration of edges doesn’t matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
input
4
3 4
1 4
3 4
output
YES
1 3
3 2
2 4
input
3
1 3
1 3
output
NO
input
3
1 2
2 3
output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
题解
每条边一定有一端的最大值为 ,所以我们就围着 建菊花图就好了,左右两端最大值相同的边就串成一条链接在 上,样例一构造如下:
样例中两个 作为一条链, 作为单独的一条链,然后中间的点直接贪心从大到小找没有作为端点的点作为中间的点,最后构图如下:
代码
#include<bits/stdc++.h>
using namespace std;
const int M=1005;
struct sd{int a,b;}ed[M];
int n,flag;
vector<int>cot[M];
vector<int>ans[M];
bool vis[M];
void in(){scanf("%d",&n);}
void ac()
{
int a,b;
for(int i=1;i<n;++i)
{
scanf("%d%d",&a,&b);
if(i==1&&a==38)flag=1;
if(a!=n&&b!=n)puts("NO"),exit(0);
cot[a].push_back(i);cot[b].push_back(i);vis[a]=vis[b]=1;
}
for(int i=1;i<n;++i)
{
if(!cot[i].size())continue;
ans[i].push_back(n);
for(int j=i-1;j>=1;--j)
{
if(ans[i].size()==cot[i].size())break;
if(!vis[j])ans[i].push_back(j),vis[j]=1;
}
if(ans[i].size()!=cot[i].size())puts("NO"),exit(0);
ans[i].push_back(i);
}
puts("YES");
for(int i=1;i<n;++i)if(ans[i].size())for(int j=0;j<cot[i].size();++j)ed[cot[i][j]]=(sd){ans[i][j],ans[i][j+1]};
for(int i=1;i<n;++i)printf("%d %d\n",ed[i].a,ed[i].b);
}
int main(){in();ac();}