codeforces731——C. Socks(并查集)

原题链接
题意:
有n只袜子,k种颜色,在m天中,问最少修改几只袜子的颜色,可以使每天穿的袜子左右两只都同颜色。
思路:
将在一天里穿的放到一个连通块里,染成当前连通块最多的一种颜色。并查集或dfs维护。
代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll>PLL;
typedef pair<int,int>PII;
typedef pair<double,double>PDD;
#define I_int ll
inline ll read()
{
    ll x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-')f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x=x*10+ch-'0';
        ch=getchar();
    }
    return x*f;
}
char F[200];
inline void out(I_int x)
{
    if (x == 0) return (void) (putchar('0'));
    I_int tmp = x > 0 ? x : -x;
    if (x < 0) putchar('-');
    int cnt = 0;
    while (tmp > 0)
    {
        F[cnt++] = tmp % 10 + '0';
        tmp /= 10;
    }
    while (cnt > 0) putchar(F[--cnt]);
    //cout<<" ";
}
ll ksm(ll a,ll b,ll p)
{
    ll res=1;
    while(b)
    {
        if(b&1)res=res*a%p;
        a=a*a%p;
        b>>=1;
    }
    return res;
}
const ll inf = 0x3f3f3f3f3f3f3f3f;
const int maxn=2e5+100,mod=1e8;
const double PI = atan(1.0)*4;
const double eps=1e-6;
int root[maxn];
int n,m,k,c[maxn];
vector<int>v[maxn];
int Find(int x){
    if(x!=root[x]) root[x]=Find(root[x]);
    return root[x];
}
void Union(int u,int v){
    u=Find(u),v=Find(v);
    if(u!=v)
        root[v]=u;
}
int main(){
    n=read(),m=read(),k=read();
    for(int i=1;i<=n;i++) c[i]=read(),root[i]=i;
    while(m--){
        int l=read(),r=read();
        Union(l,r);
    }
    for(int i=1;i<=n;i++)
        v[Find(i)].push_back(i);
    int cnt=0;
    for(int i=1;i<=n;i++)
        if(i==Find(i)){
            int pos=0,maxx=0;
            map<int,int>mp;
            for(auto t:v[i]){
                mp[c[t]]++;
                maxx=max(maxx,mp[c[t]]);
            }
            cnt+=v[i].size()-maxx;
        }
    out(cnt);
    return 0;
}


原文地址:https://www.cnblogs.com/OvOq/p/14853075.html