PAT Advanced 1013
来源:互联网 发布:手机麻将辅助软件 编辑:程序博客网 时间:2024/05/17 07:45
Battle Over Cities
简单的并查集应用:
思路
先假设这个点不在图里面,然后构建并查集,算有几个连通分量,算完之后,连通分量数-1就能得到需要修建多少条路。
源码
#include<iostream>#include<fstream>#include<cstring>using namespace std;int tree[1010];//ifstream fin("fin.txt");//streambuf *old = cin.rdbuf(fin.rdbuf());int N, M, K;int ans[1010];struct node{ int f, r;};node edge[1010*1010];void init(){ for (int i = 1; i <= N; i++) { tree[i] = i; ans[i] = 0; }}int findroot(int x){ int r = x; while (tree[r] != r) r = tree[r]; int i = x, j; while (i != r) { j = tree[i]; tree[i] = r; i = j; } return r;}void merge(int a, int b){ int fx = findroot(a), fy = findroot(b); if (fx != fy) { tree[fy] = fx; }}void solve(){ int city; int highway=0; for (int i = 1; i <= K; i++) { cin >> city; init(); for (int j = 1; j <= M; j++) { if (edge[j].f != city &&edge[j].r != city) { merge(edge[j].f, edge[j].r); } } for (int j = 1; j <= N; j++) { if (j != city) findroot(j); } for (int j = 1; j <= N; j++) { if (tree[j]==j&&j!=city) { highway++; } } if (!highway) cout << 0 << endl; else cout << highway - 1 << endl; highway = 0; }}void input(){ cin >> N >> M >> K; int c1, c2; init(); for (int i = 1; i <= M; i++) { cin >> c1 >> c2; edge[i].f = c1; edge[i].r = c2; } if (N) solve(); else cout << 0 << endl;}int main(){ input(); return 0;}
目录
- Battle Over Cities
- 思路
- 源码
- 目录
- 思路
0 0
- pat advanced 1013
- PAT Advanced 1013
- PAT Advanced 1065
- PAT Advanced 1001
- PAT Advanced 1043
- PAT Advanced 1042
- PAT Advanced 1067
- PAT Advanced 1066
- PAT Advanced 1005
- pat advanced 1044
- pat advanced 1042
- pat advanced 1043
- pat advanced 1032
- pat:1002(Advanced)
- pat advanced 1050
- pat advanced 1051
- pat advanced 1046
- pat advanced 1054
- 黑马程序员之多线程
- 【面向对象】多态公有继承、抽象基类
- android studio在模拟器上显示中文乱码的解决方案
- 关于一个查找数组中是否存在某一个元素的问题
- HDU 1010 Tempter of the Bone 深搜+奇偶剪枝
- PAT Advanced 1013
- 2015.9.2组队赛 1006题(dp:前缀和优化,空间压缩)
- UVAlive6935
- mybatis-SQL语句映射文件(1)resultMap
- 英方法语学习
- 动态输出html一些效果失效的处理
- Windows Server 2008 R2开关机取消登录时要按Ctrl+Alt+Delete组合键登录的方法
- CentOS6.5 x64 Hadoop学习过程
- 程序设计与我的5年