https://vjudge.net/problem/UVA-10608(uva0608 点击打开链接)
思路:并查集,维护一个连通分量。
分析:“靠左”原则,不断地合并区间,维护一颗树的元素个数这个权值(完全是自己写的第一个并查集程序,虽然是简单的套模板,但好在没有看题解了,因为实在是太水了)。
代码:
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <string.h>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cstdio>
#include <iterator>
using namespace std;
const int maxn = 30000 + 10;
int father[maxn];
int cnt[maxn];
int n,m;
void init(int n)
{
for(int i = 0; i <= n; i++)
{
father[i] = i;
cnt[i] = 1;
}
}
int find(int x)
{
if(x == father[x])
return x;
int y = find(father[x]);
return father[x] = y;
}
void unin(int a,int b)
{
int fa = find(a);
int fb = find(b);
father[fb] = fa;
cnt[fa] += cnt[fb];
}
int main()
{
int t,a,b;
scanf("%d",&t);
//int father[maxn];
//int cnt[maxn];
//int n,m;
while(t--)
{
scanf("%d%d",&n,&m);
init(n);
while(m--)
{
scanf("%d%d",&a,&b);
//“靠左”原则
if(find(a) != find(b))
{
unin(a,b);
}
}
int maxn = 0;
for(int i = 0; i < n; i++)
{
if(maxn < cnt[i])
maxn = cnt[i];
}
printf("%d\n",maxn);
}
}
/*
2
3 2
1 2
2 3
10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 1
1 2
9 10
8 9
*/
- 真正自己思考了才会有收获,不着急,慢慢来,一步一个脚印,加油!