27 lines of code AC_How Many Tables HDU-1213 (and check the collection to explain)

Inspirational use less code for efficient expression


Analysis and thinking

When n people eat, they can only sit with acquaintances and acquaintances, otherwise they will sit at the table alone. Given m relationships (m to acquaintances), ask how many tables are required at least.

For the question of the union check template for pure examination, given m relations represent m sets, there will be sets and unions of the same elements, and finally the number of sets can be calculated.

Video explanation -> Portal


Here is how I learned the new algorithm:

  1. Understand the basic principles by watching videos or documents (videos are best)
  2. Try to understand the code
  3. Handwritten code, while recalling the principle, while writing silently. Generally, you should remember it once or twice silently ( don't just use the computer to type, forget it super fast . It's not as good as bad writing).
  4. Constantly brushing the types of questions, generally after completing 8-10 questions, you can use this type of algorithm more proficiently.

#include<bits/stdc++.h>
using namespace std;
int per[1010];

int find(int x) {
    
    
	if(x==per[x]) return x;
	per[x] = find(per[x]);
	
	return per[x];
}

void Union(int a, int b) {
    
    				//建立并集 
	int t1 = find(a);
	int t2 = find(b);
	if(t1 != t2) per[t1] = t2;
}

int main() {
    
    
	ios::sync_with_stdio(false);
	int T; cin>>T; while(T--) {
    
    
		int n, m; cin>>n>>m;
		
		for(int i = 1; i <= n; i++) per[i] = i;  
		
		while(m--) {
    
    
			int a, b; cin>>a>>b;
			Union(a, b);			//对所有序对建立并 
		} 
		
		int ans = n;
		
		for(int i = 1; i <= n; i++) if(per[i] != i) ans--;
		
		cout << ans << endl;
	}
return 0; } 

If this article has helped you, please give the blogger a like! Let more people see it.

Guess you like

Origin blog.csdn.net/weixin_43899069/article/details/108669922