CodeForces 566 D.Restructuring Company(并查集)
来源:互联网 发布:java程序员薪资 编辑:程序博客网 时间:2024/06/13 03:05
Description
n个单点集,两种操作:
1 x y:合并x和y所在集合
2 x y:合并x,x+1,…,y-1,y所在集合
3 x y:查询x和y是否在同一集合
Input
第一行两个整数n和q表示初始集合数和操作数,之后q行每行一个操作(1<=n<=2e5,1<=q<=5e5)
Output
对于每次查询操作,如果x和y属于同一集合则输出YES,否则输出NO
Sample Input
8 6
3 2 5
1 2 5
3 2 5
2 4 7
2 1 2
3 1 7
Sample Output
NO
YES
YES
Solution
并查集,暴力合并显然不行,需要加个优化,令a[i]表示i集合的下一个集合编号,初始化是a[i]=i+1,那么每次点合并正常,区间合并的时候把区间[x,y]中所有点的a[i]值全部更新为a[y]的值,那么下次再合并到该区间就可以直接跳过已经合并过的这段而不是一个个合并了
Code
#include<cstdio>#include<iostream>#include<cstring>#include<algorithm>#include<cmath>#include<vector>#include<queue>#include<map>#include<set>#include<ctime>using namespace std;typedef long long ll;#define INF 0x3f3f3f3f#define maxn 222222int n,q,fa[maxn],a[maxn];void init(int n){ for(int i=1;i<=n;i++)fa[i]=i,a[i]=i+1;}int find(int x){ if(fa[x]==x)return x; return fa[x]=find(fa[x]);}void unite(int x,int y){ x=find(x),y=find(y); if(x==y)return ; fa[x]=y;}int main(){ while(~scanf("%d%d",&n,&q)) { init(n); while(q--) { int op,x,y; scanf("%d%d%d",&op,&x,&y); if(op==1)unite(x,y); else if(op==2) { if(x>y)swap(x,y); int temp; for(int i=x+1;i<=y;i=temp) { unite(i-1,i); temp=a[i]; a[i]=a[y]; } } else printf("%s\n",find(x)==find(y)?"YES":"NO"); } } return 0;}
0 0
- CodeForces 566 D.Restructuring Company(并查集)
- CodeForces 566 D.Restructuring Company(并查集)
- 【并查集】Codeforces 566D Restructuring Company
- Codeforces 566D Restructuring Company
- CodeForces 566D Restructuring Company
- VK Cup 2015 - Finals, online mirror D. Restructuring Company 并查集 stl应用
- VK Cup 2015 - Finals, online mirror D. Restructuring Company 并查集 set 二分
- codeforces Restructuring Company
- Restructuring Company CodeForces
- Restructuring Company
- Restructuring Company
- CodeForces 25D(并查集)
- CodeForces 151D Quantity of Strings(并查集)
- Codeforces Round #334 D. Moodular Arithmetic(并查集)
- CodeForces 292D Connected Components (并查集+YY)
- codeforces 827D(kruskal+倍增+并查集)
- Codeforces 366D 贪心+并查集
- Codeforces 371D. Vessels【并查集】
- Spring的七个核心模块
- 使用优先级队列求一个大数组中的前k个最大的数(或前k个最小的数)
- uv纹理坐标设定与贴图规则
- 今日头条面试手写代码-找出所有非递增减的子数组
- BZOJ 4010 [HNOI2015] 菜肴制作
- CodeForces 566 D.Restructuring Company(并查集)
- 我的java学习之路-tomcat与jsp
- (转载)2017第八届蓝桥杯C/C++ B组省赛题解
- 01_链表的翻转(C语言)
- 多线程
- 插件与主题
- [HDU 1796]How many integers can you find:容斥原理
- oralce监听配置允许访问本地数据库
- 拉格朗日插值方法示例