[hrbust 2026] 势力较量

来源:互联网 发布:stm32官方烧录软件 编辑:程序博客网 时间:2024/04/30 00:22
题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=2026
一道赤裸裸的并查集。。。
代码如下:

#include<stdio.h>
#include<string.h>
#include<algorithm>

using namespace std;

const int MAXN = 105;
int father[MAXN];
int rank[MAXN];
int s[MAXN];

void Make_Set(int i)//集合初始化
{
father[i] = i;
rank[i] = 0;
}
int Find_Father(int i)
{
if(i!=father[i])
{
father[i] = Find_Father(father[i]);//带上路径压缩
}
return father[i];
}
void Union(int x, int y)//合并
{
x = Find_Father(x);
y = Find_Father(y);
if (x == y) return;
if (rank[x] > rank[y])
{
father[y] = x;
}
else
{
if (rank[x] == rank[y])
{
rank[y]++;
}
father[x] = y;
}
}

int main()
{
int n, m;
int Case = 1;
while(~scanf("%d %d", &n, &m))
{
for(int i = 1; i <= n; i++)
Make_Set(i);
for(int i = 1; i <= m; i++)
{
int u,v;
scanf("%d %d", &u, &v);
Union(u,v);
}
int q;
scanf("%d", &q);
for(int i = 1;i <= q; i++)
{
scanf("%d", &s[i]);
s[i] = Find_Father(s[i]);
for(int j = 1; j <= n; j++)
Find_Father(j);
}
printf("Case %d:\n", Case++);
for(int i = 1; i <= q; i++)
{
int count = 0;
for(int j = 1; j <= n; j++)
{
if(father[j] == s[i])
{
count++;
}
}
printf("%d %d\n", father[s[i]], count);
}
}
return 0;
}

黑赵晓,我们特专业!
0 0