AtCoder Grand Contest 014 E - Blue and Red Tree 乱搞
2018-01-29 22:25
447 查看
题意
一棵n个节点的树可以按如下方式构造一棵新树:选择一条简单路(s,t),把原图中在该路径上的某条边删掉,然后在新图中加入s到t的边。给出两棵树,问第一棵树是否存在一种构造方案来得到第二棵树。n<=100000
分析
大概想到了做法,但是没有想到要怎么实现。这题可以倒着想,在原图中最后删掉的边,在新图中也一定是以同样的方式出现。
那么我们可以看成一开始原图中有n个点连通块,每次找一条在原图和新图中都出现的边,把这条边的两个端点缩成一个点,然后继续进行以上操作。
若原图最后只剩下一个点,则代表可行,反之则不可行。
考虑如何实现:
我们可以把原图和新图中的边扔到一起,用一个queue记录所有要合并的连通块,用map记录每对连通块之间的边数,用set记录每个连通块和哪些连通块相连,最后用并查集维护连通性就好了。
实现起来会有一些细节,但问题不大。
代码
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<map> #include<set> #include<queue> #define mp(x,y) make_pair(x,y) using namespace std; typedef pair<int,int> pi; const int N=100005; int n,f ; set<int> se ; map<pi,int> ma; queue<pi> que; int 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 find(int x) { if (f[x]==x) return x; else return f[x]=find(f[x]); } int main() { n=read(); for (int i=1;i<=n*2-2;i++) { int x=read(),y=read(); se[x].insert(y);se[y].insert(x); ma[mp(x,y)]++;ma[mp(y,x)]++; if (ma[mp(x,y)]==2) que.push(mp(x,y)); } for (int i=1;i<=n;i++) f[i]=i; set<int>::iterator it; while (!que.empty()) { int x=que.front().first,y=que.front().second;que.pop(); x=find(x);y=find(y); se[x].erase(y);se[y].erase(x); if (se[x].size()<se[y].size()) swap(x,y); for (it=se[y].begin();it!=se[y].end();it++) { int to=(*it); ma[mp(to,y)]=ma[mp(y,to)]=0; se[to].erase(y);se[to].insert(x); ma[mp(to,x)]++;ma[mp(x,to)]++; if (ma[mp(to,x)]==2) que.push(mp(to,x)); se[x].insert(to); } f[y]=x; se[y].clear(); } int s=0; for (int i=1;i<=n;i++) s+=f[i]==i; if (s==1) puts("YES"); else puts("NO"); return 0; }
相关文章推荐
- AtCoder Grand Contest 014 D - Black and White Tree 博弈论
- Atcoder Grand Contest 018 D Tree and Hamilton Path
- [AtCoder Grand Contest 018] D: Tree and Hamilton Path (agc018D)
- AtCoder Grand Contest 018 D - Tree and Hamilton Path 树的重心
- (树的重心/DFS/构造)AtCoder Grand Contest 018 D - Tree and Hamilton Path
- AtCoder Grand Contest 014C: Closed Rooms 题解
- AtCoder Grand Contest 017 D - Game on Tree
- AtCoder Grand Contest 019 B: Reverse and Compare
- AtCoder Grand Contest 014 C - Closed Rooms bfs
- (dp)AtCoder Grand Contest 019 D - Shift and Flip
- AtCoder Grand Contest 019 B - Reverse and Compare
- AtCoder Grand Contest 017 C - Snuke and Spells
- (NTT)AtCoder Grand Contest 019 E - Shuffle and Swap
- AtCoder Grand Contest 012 E - Camel and Oases 状压dp
- 【AtCoder Grand Contest 007E】Shik and Travel [Dfs][二分答案]
- AtCoder Grand Contest 014 题解
- AtCoder Grand Contest 019 E - Shuffle and Swap
- [杂题] AtCoder Grand Contest 007 E Shik and Travel
- AtCoder Grand Contest 018B: Sports Festival 题解
- AtCoder Grand Contest 018 --------- Getting Difference