|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码如下,是一道合根的试题
#include <iostream>
#include <cstring>
using namespace std;
const int MAX = 0x3f3f3f;
int pre[MAX];
int m,n;
int s;
int left1,right1;
void init(int n){
for(int i=1;i<=n;i++){
pre[i]=i;
}
}
int find_pre(int key)
{
int temp=key;
while(temp!=pre[temp]){
temp=pre[temp];
}
int t=0;
while(key!=temp){//压缩
t=pre[key];
pre[key]=temp;
key=t;
}
return temp;
}
void unite(int x,int y)
{
int rootx=find_pre(x);
int rooty=find_pre(y);
if(rootx!=rooty) pre[rootx]=rooty;
}
int main()
{
cin >> m >> n;
int all=m*n;
cin >> s;
init(all);
for(int i=1;i<=s;i++){
cin >> left1 >> right1;
unite(left1,right1);
}
int att[MAX];
int num=0;
memset(att,0,sizeof(att));//内存空间初始化
for(int i=1;i<=all;i++){
att[find_pre(i)]=1;
}
for(int i=1;i<=all;i++){
if(att[i]==1) num++;
}
cout << num;
return 0;
}
推荐用debug,我出现这样情况时一般是出现了死循环
|
|