HDU 3038 How Many Answers Are Wrong(并查集)
2016-03-29 20:59
495 查看
题目链接:[kuangbin带你飞]专题五 并查集 D - How Many Answers Are Wrong
则a到b的总和c 可以表示为sum[a]-sum[b+1] = c。
题意
有n次询问,给出a到b区间的总和,问这n次给出的总和中有几次是和前面已近给出的是矛盾的。思路
sum[x]表示x到区间末尾的总和则a到b的总和c 可以表示为sum[a]-sum[b+1] = c。
代码
#include<iostream> #include<stdio.h> #include<cstring> #include<cstdlib> #include<algorithm> #define LL long long using namespace std; int sum[200009], fa[200009]; int find(int x) { if(fa[x] == x) return x; int t = fa[x]; fa[x] = find(fa[x]); sum[x] += sum[t]; return fa[x]; } void update(int x, int y, int a, int b, int c) { if(x > y) { fa[y] = x; sum[y] = sum[a]-sum[b]-c; } else { fa[x] = y; sum[x] = sum[b]-sum[a]+c; } } int main() { int len, n; while(~scanf("%d%d", &len, &n)) { memset(sum, 0, sizeof(sum)); for(int i=0; i<=200001; i++) fa[i] = i; int ans = 0; while(n--) { int a, b, c; scanf("%d%d%d", &a, &b, &c); b++; int x = find(a); int y = find(b); if(x == y && sum[a] != sum[b] + c) ans++; else if(x != y) update(x, y, a, b, c); } printf("%d\n", ans); } return 0; }
相关文章推荐
- 深入理解 Java 虚拟机-类初始化
- linux--http服务器编写
- Maven多模块项目管理小结
- Flume-ng 1.6.0安装、配置与使用
- 遭遇重创,一失足,回到"解放"前:项目文件全部为空,无法导入到eclipse中
- 蓝牙ble 从LED实验来学习CC2541 IO口配置
- 旋转数组中的最小数字
- 课本第十八章
- Ajax:后台jquery实现ajax无刷新删除数据及demo
- Random Forest for Regression by TreeBagger
- 判断花括号是否成对出现
- linux 内存管理分析之-----SLAB层
- js 页面值变动监听
- JSP简单练习-EL获取表单数据
- 查分约束uva
- CI Query Builder
- MVP模式是否适合我们使用? 代码说话
- Python基础:容器类型和简单的语法
- MVP模式是否适合我们使用? 代码说话
- 迁移工具准备复习