Poj 1611 the suspects and query Union find

Source: Internet
Author: User

This question is also a standard question and can be found.

After the operation is completed and the set is queried, the number of elements in the same set as the 0 node is queried.

Note that in this operation, you need to first find the parent node 0, and then find the number of parent nodes and the parent node 0 are the same.

At this time, you need to use the find parent operation for each node, because the node's parent is not necessarily the root node of this set at the final state.


#include <stdio.h>const int MAX_N = 30001;struct SubSet{int p, rank;}sub[MAX_N];int N, M;void initSub(){for (int i = 0; i < N; i++){sub[i].p = i;sub[i].rank = 0;}}int find(int x){if (x != sub[x].p) sub[x].p = find(sub[x].p);return sub[x].p;}void unionTwo(int x, int y){int xroot = find(x);int yroot = find(y);if (sub[xroot].rank < sub[yroot].rank) sub[xroot].p = yroot;else{if (sub[xroot].rank == sub[yroot].rank) sub[xroot].rank++;sub[yroot].p = xroot;}}int main(){int a, b, k;while (scanf("%d %d", &N, &M) && (N || M)){initSub();for (int i = 0; i < M; i++){scanf("%d", &k);if (k > 0) scanf("%d", &a);for (int j = 1; j < k; j++){scanf("%d", &b);unionTwo(a, b);}}int sus = 1, p = find(0);for (int i = 1; i < N; i++){if (find(i) == p) sus++;}printf("%d\n", sus);}return 0;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.