HDU 1213 how many tables (suitable for newcomer entry stickers)

Source: Internet
Author: User


Today is and check set of special, oh, test instructions not much explanation, can not understand to fill English bar sunglass (▔,▔) Deny, bare and check set, the first initialization let each point of the root node for himself, if the input a, B to know then put a A, a and a group of the same set (that is, let a, b root node, And the collection in the set with a point as the root node to represent this set, also known as the representative of the yuan, and finally as long as the detection of a few representatives of the yuan can know at least a few tables, there is a bit of the path compression, we find a bit of the root node from his parent node, Grandpa node What the past more annoying AH If this path is a long one, it's much more annoying to find it, so it's convenient to have each point on his path connected directly to the root node when we first look it up. Here's the code.

#include <bits/stdc++.h>

using namespace std;
int per[1005];

int sf (int x) {
	int r=x;
   while (R!=per[r]) {	
   r=per[r];
   }
   while (r!=x) {
   	int t=per[x];
   	Per[x]=r;
   	x=t;
   }
   return r;
}

void Union (int a,int b) {
	if (SF (a)!=sf (b))
     PER[SF (a)]=sf (b);
}


int main () {
	int t,n,m,i,sum,a,b;
	cin>>t;
	while (t--) {
		cin>>n>>m;
		sum=0;
		for (i=1;i<=n;i++)
		per[i]=i;
		for (i=1;i<=m;i++) {
			cin>>a>>b;
			Union (A, b);
		}
		for (i=1;i<=n;i++)
		if (per[i]==i)
		sum++;
		cout<<sum<<endl;
	}
	return 0;
}
Ladies and gentlemen, are you crossing for getting started?

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.