ZOJ-1789
2014-04-15 00:25
169 查看
并查集,其实kruskal算法里用过,不过不熟练,感觉代码还可以改进,懒的优化了,明天还要上班。。好困,睡觉去鸟
#include<stdio.h> #include<stdlib.h> struct StudentStruct { int id; struct StudentStruct *parent; int rank; }; typedef struct StudentStruct *Student; Student make_set(int id) { Student stu = malloc(sizeof(struct StudentStruct)); stu->parent = stu; stu->id = id; stu->rank = 1; return stu; } Student find_set(Student stu) { if (stu->parent != stu) stu->parent = find_set(stu->parent); return stu->parent; } static void link(Student s1, Student s2) { if (s1->rank > s2->rank) { s2->parent = s1; s1->rank += s2->rank; } else { s1->parent = s2; s2->rank += s1->rank; } } static void union_set(Student s1, Student s2) { link(find_set(s1), find_set(s2)); } int main() { int n, m; Student *array = malloc(30000 * sizeof(Student)); while (scanf("%d %d", &n, &m), n || m) { int i, j, k, id; for (i = 0; i < n; i++) array[i] = NULL; for (i = 0; i < m; i++) { scanf("%d", &k); Student head; if (k) { scanf("%d", &id); if (array[id] == NULL) array[id] = make_set(id); head = find_set(array[id]); } for (j = 1; j < k; j++) { scanf("%d", &id); if (array[id] == NULL) array[id] = make_set(id); if (find_set(head) != find_set(array[id])) union_set(head, array[id]); } } if (array[0] == NULL) puts("1"); else printf("%d\n", find_set(array[0])->rank); } free(array); return 0; }
相关文章推荐
- zoj - 1789 - The Suspects
- ZOJ 2158/POJ 1789 - Truck History
- zoj 2158 poj 1789 Truck History (Prim)
- zoj - 1789 - The Suspects
- ZOJ1789(The Suspects)j简单并查集
- zoj 1789 The Suspects
- ZOJ 2158 && POJ 1789 Truck History (经典MST)
- zoj 1789 The Suspects
- zoj1789(并查集)
- zoj 1789 The Suspects
- zoj 1789 The Suspects
- zoj 1789
- zoj 1789 The Suspects
- Truck History POJ 1789 ZOJ 2158 Prim算法
- ZOJ 1789
- ZOJ 1789 水水的并查集,刚开始学会并查集,做了此题。经过一次失败后终于AC了哈哈~ AC感觉就是好啊!与大家共分享啊
- ACM zoj 1789(并查集实现)
- zoj 1789||poj 1611 The Suspects(并查集,简单)
- ZOJ 1789 The Suspects
- zoj-1789