洛谷 P1525 关押罪犯

拿到这题看都没看直接写了个裸地贪心+并查集

写完就发现一点问题


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
int n,m,g[40010];
struct pi
{
    int p1,p2,ang;
}pe[100010];
bool cmp(pi aa,pi bb){return aa.ang>bb.ang;}int getf(int x){
    if (g[x]==x) return x;
    g[x]=getf(g[x]);
return g[x];
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    cin>>n>>m;
    for (int i=1;i<=20010;i++) g[i]=i;  
    for (int i=1;i<=m;i++) cin>>pe[i].p1>>pe[i].p2>>pe[i].ang;
    sort(pe+1,pe+m+1,cmp);
    int fa1=pe[1].p1,fa2=pe[1].p2,ans=0;
    for (int i=2;i<=m;i++)
    {
        if (getf(pe[i].p1)==getf(pe[i].p2))
            {printf("%d\n",pe[i].ang); return 0;}
         else
          {
            if (g[pe[i].p1]==fa1) g[pe[i].p2]=fa2;
             else if (g[pe[i].p1]==fa2) g[pe[i].p2]=fa1; else if (g[pe[i].p2]==fa1) g[pe[i].p1]=fa2; else if (g[pe[i].p2]==fa2) g[pe[i].p1]=fa1;
          }
    }   
    printf("%d\n",0);
return 0;
}

因为当 当前2个罪犯 都不在2个并查集中的时候 究竟是 p1加到fa1 还是 p2加到fa1 就不知道

如果随便加的话 可能后面的关系会对前面的关系产生影响 所以不能维护最优解

所以这个人品贪心也就过了3个点


最后想到正解

即建立并查集的补集 --> 将g数组扩大2倍 n+1~end 为补集

分别将p1  p2和p2 p1的补集合并

这样后面关系更新后前面的也会更新

所以这样做是正确的

然后按这个思路debug了一下就A了

下面是AC代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
int n,m,g[40010];
struct pi
{
    int p1,p2,ang;
}pe[100010];
bool cmp(pi aa,pi bb){return aa.ang>bb.ang;}int getf(int x){
    if (g[x]==x) return x;
    g[x]=getf(g[x]);
return g[x];
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    cin>>n>>m;
    for (int i=1;i<=2*n;i++) g[i]=i;  
    for (int i=1;i<=m;i++) cin>>pe[i].p1>>pe[i].p2>>pe[i].ang;
    sort(pe+1,pe+m+1,cmp);
    for (int i=1;i<=m;i++)
    {
        int x=getf(pe[i].p1),y=getf(pe[i].p2);
        if (x==y){printf("%d\n",pe[i].ang); return 0;}
        g[x]=getf(pe[i].p2+n); g[y]=getf(pe[i].p1+n);
    }   
    printf("%d\n",0);
return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值