【ノートコード] [互いに素なセット]

hdu1213

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define ms(s) memset(s, 0, sizeof(s))
const int inf = 0x3f3f3f3f;
#define LOCAL
const int maxn=1e3+10;
int f[maxn];
int n,m;
int search(int x)
{
    if(f[x]!=x)
        f[x]=search(f[x]);
    return f[x];
}
void unit(int x,int y)
{
    int fx=search(x);
    int fy=search(y);
    if(fx!=fy)
        f[fx]=fy;
    return ;
}
int main() 
{
    //freopen("in.txt", "r", stdin);
    int t;
    scanf("%d",&t);
    while(t--)
    {
        //memset(rank,0,sizeof(rank));
        scanf("%d%d",&n,&m);
        //memset(f,-1,sizeof(f));
        int u,v;
        for(int i=1;i<=n;++i)
            f[i]=i;
        for(int i=0;i<m;++i)
        {
            scanf("%d%d",&u,&v);
            unit(u,v);
        }
        int ans=0;
        for(int i=1;i<=n;++i)
        {
            int fi=search(i);
            //cout<<i<<" "<<fi<<endl;
            if(fi==i)
                ans++;
        }
        printf("%d\n",ans );
    }
    return 0;
}

hdu1856

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define ms(s) memset(s, 0, sizeof(s))
const int inf = 0x3f3f3f3f;
#define LOCAL
const int maxn=1e7+10;
int f[maxn];
int n,a,b;
int rk[maxn];
void make_set()
{
    for(int i=0;i<maxn;++i)
    {
        f[i]=i;
        rk[i]=1;
    }
}
int  search(int x)
{
    if(x!=f[x])
        f[x]=search(f[x]);
    return f[x];
}
void unit(int a,int b)
{
    int x=search(a);
    int y=search(b);
    if(x!=y)
    {
        f[x]=y;
        rk[y]+=rk[x];
    }
}
int main() 
{
    //freopen("in.txt", "r", stdin);
    while(scanf("%d",&n)!=EOF)
    {
    make_set();
    for(int i=0;i<n;++i)
    {
        scanf("%d%d",&a,&b);
        unit(a,b);
    }
    // for(int i=0;i<10;++i)
    //     cout<<f[i]<<" ";
    int ans=0;
    for(int i=0;i<maxn;++i)
    {
        ans=max(ans,rk[i]);
    }
    cout<<ans<<endl;
}
    return 0;
}
公開された22元の記事 ウォンの賞賛3 ビュー1828

おすすめ

転載: blog.csdn.net/qq_42825058/article/details/100607402