codeforces 并查集_CodeForces - 731C Socks (并查集+贪心)

Note

In the first sample, Arseniy can repaint the first and the third socks to the second color.

In the second sample, there is no need to change any colors.

题目大意是说,妈妈为孩子准备的袜子(都有自己的序号,不同序号代表不同颜色)。然后给出袜子的数量,需要穿几天,和颜色的数量。

然后又给出了m天之中,他穿的左右两只脚的袜子所在的位置。由于顺序被打乱,要求出改变最少的袜子颜色,让所选袜子都是同色(才不被别人笑话)。

//贪心+并查集,论stl的神奇

#include#include#include#include#includeusing namespace std;

const int mn=200010,mm=200010,mk=200010;

int n,m,k;

int c[mn],f[mn];

int find(int x)

{

int t=x;

while(x!=f[x]) x=f[x];

return f[t]=x;

}

void Union(int x,int y)

{

int fx=find(x),fy=find(y);

if(fx!=fy) f[fx]=fy;

}

vectorp[mn];

int main(){

scanf("%d%d%d",&n,&m,&k);

for(int i=1;i<=n;++i)

{

scanf("%d",c+i);

f[i]=i;

}

while(m--)

{

int l,r;

scanf("%d%d",&l,&r);

Union(l,r);

}

for(int i=1;i<=n;++i)

p[find(i)].push_back(c[i]);

int ans=0;

//k++;

for(int i=1;i<=n;++i)

if(p[i].size()>1)

{

mapcnt;

int mx=0;

for(int j=0;j

//贪心+并查集

#include#include#include#includeusing namespace std;

const int mn=200010,mm=200010,mk=200010;

int n,m,k;

int c[mn],f[mn];

int find(int x)

{

int t=x;

while(x!=f[x]) x=f[x];

return f[t]=x;

}

void Union(int x,int y)

{

int fx=find(x),fy=find(y);

if(fx!=fy) f[fx]=fy;

}

vectorp[mn];

int cnt[mk];

int main(){

scanf("%d%d%d",&n,&m,&k);

for(int i=1;i<=n;++i)

{

scanf("%d",c+i);

f[i]=i;

}

while(m--)

{

int l,r;

scanf("%d%d",&l,&r);

Union(l,r);

}

for(int i=1;i<=n;++i)

p[find(i)].push_back(c[i]);

int ans=0;

//k++;

for(int i=1;i<=n;++i)

if(p[i].size()>1)

{

//int cnt[k+2]={0};用这个也超时

int mx=0;

for(int j=0;j

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值