CodeForces 566 D.Restructuring Company(并查集)
来源:互联网 发布:空难 尼尔森 知乎 编辑:程序博客网 时间:2024/06/05 05:09
题意:有n个人,一开始每个人都属于自己部门。
现在q次询问,询问有三种:
1 x y : 将x所在的部门和y所在的部门合并
2 x y : 将x, x+1, ....y-1, y的所有人所在部门合并
3 x y : 问x和y是否在同一个部门
(1 ≤ n ≤ 200 000, 1 ≤ q ≤ 500 000)
思路:1 3操作好做,关键是2操作,需要将一串的都合并。暴力的话n*q肯定不行,因为要将一个区间合并成一个,一共才n个人,没合并几次,很多都已经是同一个部门了,所以没必要再从x遍历到y,我们可以利用一个数组维护记录每个人他后面的第一个不属于他部门的人的id。每次2操作时将这个区间的下一个都改成y的下一个。
代码:
#include<bits/stdc++.h>using namespace std;const int maxn = 2e5+5;int n, q, pre[maxn], nex[maxn];int Find(int x){ int r = x; while(pre[r] != r) r = pre[r]; int i = x, j; while(pre[i] != r) { j = pre[i]; pre[i] = r; i = j; } return r;}void join(int x, int y){ int a = Find(x); int b = Find(y); if(a != b) pre[b] = a;}int main(void){ while(cin >> n >> q) { for(int i = 1; i <= n; i++) pre[i] = i, nex[i] = i+1; while(q--) { int cmd, x, y, to; scanf("%d%d%d", &cmd, &x, &y); if(cmd == 1) join(x, y); else if(cmd == 2) { for(int i = x+1; i <= y; i = to) { join(i-1, i); to = nex[i]; nex[i] = nex[y]; //他要和y成为一个部门,所以他下一个不是自己部门的就是y的下一个 } } else puts(Find(x)==Find(y) ? "YES" : "NO"); } } return 0;}
阅读全文
1 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【并查集】
- win+linux 搭建Java环境JDK
- python -- scrapy 问题小结
- 【SSH进阶之路】深入源码,详解Struts基本实现流程(七)
- Educational Codeforces Round 5 D
- intent浏览器
- CodeForces 566 D.Restructuring Company(并查集)
- 论建树的方法
- 图背景模糊
- 自定义CString类
- 第四场个人训练赛(未完成)
- Ajax
- 牛客《剑指Offer》 跳台阶
- 文章标题
- JS实现UTF8编解码及Base64编解码