ZOJ-2740
来源:互联网 发布:知乎三角铁十级什么梗 编辑:程序博客网 时间:2024/06/01 10:42
题目的意思就是给出一些边,问这些边组成的图是否是一棵树,就是无环并且全连通,如果是树的话,那边肯定为顶点数减一,然后用并查集加边,如果加入边形成了环,就不是树,否则一直加直到每条边都加上,刚好为一棵树
#include<stdio.h>#include<stdlib.h>struct Computer{struct Computer *parent;int rank;};static struct Computer *make_set(){struct Computer *v = malloc(sizeof(struct Computer));v->parent = v;v->rank = 0;return v;}static struct Computer *find_set(struct Computer *v){if (v->parent != v)v->parent = find_set(v->parent);return v->parent;}static void link(struct Computer *u, struct Computer *v){if (u->rank > v->rank)v->parent = u;else{u->parent = v;if (u->rank == v->rank)v->rank++;}}static void union_set(struct Computer *u, struct Computer *v){link(find_set(u), find_set(v));}int main(){int n, m, i;struct Computer **array = malloc(1000 * sizeof(struct Computer*));for (i = 0; i < 1000; i++)array[i] = make_set();while (scanf("%d %d", &n, &m), n){for (i = 0; i < n; i++){array[i]->parent = array[i];array[i]->rank = 0;}int a, b, flag = 1;if (n - 1 != m)flag = 0;for (i = 0; i < m; i++){scanf("%d %d", &a, &b);if (flag){struct Computer *c1 = find_set(array[a - 1]);struct Computer *c2 = find_set(array[b - 1]);if (c1 != c2)union_set(c1, c2);elseflag = 0;}}puts(flag ? "Yes" : "No");}for (i = 0; i < 1000; i++)free(array[i]);free(array);return 0;}
0 0
- ZOJ-2740
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- 作品展导师
- POJ 2271 HTML
- CSU 1411: Longest Consecutive Ones
- C#之委托与事件
- 12个有趣的c语言面试题
- ZOJ-2740
- poj 2947 Widget Factory(模7环上的高斯消元)
- myeclipse10配置svn
- CodeForces 412D - Giving Awards (dfs)
- c++ 字符类型总结区别wchar_t,char,WCHAR
- SpringMVC中文乱码问题
- 软件文档中部分图的解释
- C/C++的堆栈,内存分配
- win8,win8.1的日记本应用(包含页面跳转)以及如何调用语音来朗读文本