zoukankan      html  css  js  c++  java
  • 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;
    }
    
    
    
  • 相关阅读:
    一行代码更改博客园皮肤
    fatal: refusing to merge unrelated histories
    使用 netcat 传输大文件
    linux 命令后台运行
    .net core 使用 Nlog 配置文件
    .net core 使用 Nlog 集成 exceptionless 配置文件
    Mysql不同字符串格式的连表查询
    Mongodb between 时间范围
    VS Code 使用 Debugger for Chrome 调试vue
    css权重说明
  • 原文地址:https://www.cnblogs.com/OvOq/p/14853075.html
Copyright © 2011-2022 走看看