Tree Restoration Gym - 101755F (并查集)

There is a tree of n vertices. For each vertex a list of all its successors is known (not only direct ones). It is required to restore the tree or to say there is no such tree.

Input

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of vertices in the tree.

Each of the next n lines contains an integer ci (0 ≤ ci ≤ n) — the number of successors of vertex i, and then ci distinct integers aij (1 ≤ aij ≤ n) — the indices of successors of vertex i.

Output

If the answer does not exist, output «NO».

Otherwise, in the first line output «YES», and then output n - 1 lines containing two integers each — indices of parent and child. Pairs (parent, child) can be output in any order.

Examples

Input
5
4 2 3 4 5
3 3 4 5
2 4 5
1 5
0
Output
YES
1 2
2 3
3 4
4 5
Input
5
4 2 3 4 5
3 3 4 5
0
1 5
0
Output
YES
1 2
2 3
2 4
4 5
Input
3
3 2 3 1
3 3 1 2
3 1 2 3
Output
NO

细节太多,大致先按子孙的数量排序。。。
还是请看我的代码吧,写这篇博客,主要是提醒一下坑点。
1.有环
2.建出来好几课树
3.自己不能当自己的儿子。
4.每个儿子都不能漏
数据一组:

7
5 2 3 4 5 6
2 4 5
2 6 7
0
0
0
0

还要注意并查集不能压缩路径

#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#define fuck(x) cout<<#x<<" = "<<x<<endl;
#define ls (t<<1)
#define rs ((t<<1)+1)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = ;
const int inf = 2.1e9;
const ll Inf = ;
const int mod = ;
const double eps = 1e-;
const double pi = acos(-);
bool vis[maxn];
int num[maxn];
int f[maxn];
struct node
{
int id,sz;
}a[maxn];
vector<int>v[maxn];
int n,m; bool cmp(node a,node b){
return a.sz<b.sz;
} int mx=;
int getf(int x,int t){
if(t==mx){return -;}
if(x==f[x])return x;
return getf(f[x],t+);
} int get_num(int x,int t){
if(t==mx){return -;}
num[x]++;
if(x==f[x]){return x;}
return get_num(f[x],t+);
} vector<int>tt;
int main()
{
scanf("%d",&n);
for(int i=;i<=n;i++){
scanf("%d",&m);f[i]=i;
for(int j=;j<=m;j++){
int x;
scanf("%d",&x);
v[i].push_back(x);
a[i].sz++;
}
a[i].id=i;
} sort(a+,a++n,cmp);
bool flag=true;
for(int i=;i<=n;i++){
int siz = a[i].sz;
int id=a[i].id;
for(int j=;j<siz;j++){
vis[v[id][j]]=true;
}
vis[id]=true;
for(int j=;j<siz;j++){
int t1=getf(v[id][j],);
if(id==v[id][j]||t1==-||!vis[t1]){flag=false;break;}
if(t1==v[id][j]){tt.push_back(t1);}
}
int sz=tt.size();
for(int j=;j<sz;j++){
f[tt[j]]=id;
}
tt.clear();
if(!flag){break;}
memset(vis,,sizeof(vis));
} int rec=;
for(int i=;i<=n;i++){
if(f[i]==i){rec++;}
get_num(i,);
}
for(int i=;i<=n;i++){
if(num[i]!=v[i].size()+){flag=false;}
}
if(rec!=){flag=false;} if(flag){
printf("YES\n");
for(int i=;i<=n;i++){
if(f[i]!=i){printf("%d %d\n",f[i],i);}
}
}
else {
printf("NO\n");
} return ;
}
上一篇:#1490 : Tree Restoration


下一篇:hihocoder 1490 Tree Restoration