「已注销」 2023-03-31 23:56 采纳率: 90.2%
浏览 21
已结题

蓝桥杯合根植物并查集

原题洛谷:https://www.luogu.com.cn/problem/P8654
考点:并查集
套了并查集模板,在join函数中用cnt--记录总集合数量变化最后输出cnt,不知道为什么样例过了最后全WA

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;

int m,n,k;
int pre[1000005],rankk[1000005]={0},cnt;

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

void join(int x,int y)             
{
    x=find(x),y=find(y);          
    if(x!=y)pre[x]=y;               
    cnt--;
}


int main(){
    cin>>m>>n;
    cnt=m*n;
    for(int i=1;i<=n*m;i++)pre[i]=i;
    int x,y;
    cin>>k;
    for(int i=0;i<k;i++){
        cin>>x>>y;
        join(x,y);
    }
    cout<<cnt+1;
    return 0;
}

  • 写回答

2条回答 默认 最新

  • ksgpjhqf 2023-04-01 00:53
    关注

    第10行判断相等写成赋值了;
    join函数中,当x==y时,cnt不能减,应该把cnt--写进if里;
    最后cnt不要加1。
    这是修改后的代码,试过可以通过。

    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    
    int m, n, k;
    int pre[1000005], rankk[1000005] = {0}, cnt;
    
    int find(int x) {
        if (pre[x] == x)return x;
        return pre[x] = find(pre[x]);
    }
    
    void join(int x, int y) {
        x = find(x), y = find(y);
        if (x != y) {
            pre[x] = y;
            cnt--;
        }
    }
    
    int main() {
        cin >> m >> n;
        cnt = m * n;
        for (int i = 1; i <= n * m; i++)pre[i] = i;
        int x, y;
        cin >> k;
        for (int i = 0; i < k; i++) {
            cin >> x >> y;
            join(x, y);
        }
        cout << cnt;
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月9日
  • 已采纳回答 4月1日
  • 创建了问题 3月31日