落谷 P4833 萨塔尼亚的一生之敌(思维+图论+并查集)

21 篇文章 0 订阅
5 篇文章 0 订阅

传送门

题意:给你n个点,m条边,让你将n个点分成尽量多的集合,不在同一集合的点俩俩之间要有边存在,问你最多能分成多少个集合,每个集合有多少个节点

题解:最开始任选一个节点v,所有没有与v有边相连的点都应与v属于同一集合,记录数量,维护联通块,然后从不属于已经出现的联通块中任选一个节点,与最开始一样的操作,但是由于已经有联通块出现了,所以如果必须与当前点在同一集合中点已经属于其他联通块了,那么所属的联通块应该与当前联通块合并,更新数量,维护联通块

AC代码:

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<queue>
#include<vector>
#include<iostream>
#define ll long long
using namespace std;
const int maxn=1e5+5;
int p[maxn],cnt;
int ed[maxn*40],nex[maxn*40];
int read(){
    int x=0,w=1;char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
    if(ch=='-')w=0,ch=getchar();
    while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
    return w?x:-x;
}
void add_edge(int st,int e)
{
    ed[cnt]=e;
    nex[cnt]=p[st];
    p[st]=cnt++;
}
bool judge[maxn];
int num[maxn],father[maxn],num1[maxn];
int find1(int x){
    if(x==father[x])
        return x;
    return father[x]=find1(father[x]);
}
void init(int n){
    memset(p,-1,sizeof(p));
    cnt=0;
    for(int a=1;a<=n;a++)
        father[a]=a;
}
void bfs(int now){
    judge[now]=true;
    for(int a=p[now];a!=-1;a=nex[a])
        judge[ed[a]]=true;
}
int main( )
{
    int n=read(),m=read();
    init(n);
    int i,j;
    for(int a=1;a<=m;a++){
        i=read();
        j=read();
        add_edge(j,i);
        add_edge(i,j);
    }
    int ans=0,num2;
    for(int a=1;a<=n;a++){
        if(find1(a)==a){
            memset(judge,false,sizeof(judge));
            memset(num1,0,sizeof(num1));
            bfs(a);
            num2=1;
            for(int k=1;k<=n;k++){
                if(judge[k])
                    continue;
                int fa=find1(k);
                if(fa!=k){
                    num2+=num[fa];
                    ans-=(num[fa]!=0);
                    num[fa]=0;
                }
                else
                    num2++;
                father[fa]=a;
            }
            ans++;
            num[a]=num2;
        }
    }
    sort(num+1,num+n+1);
    printf("%d\n",ans);
    for(int i=n-ans+1;i<=n;i++){
        printf("%d",num[i]);
        if(i==n)
            printf("\n");
        else
            printf(" ");
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值