hdu-2480-Steal the Treasure-贪心+缩点

本文介绍了一道经典的图论与贪心算法结合的问题——HDU 2480,通过边排序及特殊处理双向边的方法来解决。详细解释了如何在遇到单向边和双向边时进行选择,并通过缩点等技巧优化解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.hdu.edu.cn/showproblem.php?pid=2480


边排序,贪心选择大的,遇到单向边直接选并标记起点x,

遇到双向边,且起点可以任选,则缩点,若起点唯一,则按照单向边处理,标记起点


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <iostream>
using namespace std;

const double pi=acos(-1.0);
double eps=0.000001;

 int fa[1005];
 int find(int x)
 {
     if (x==fa[x]) return x;
     else
        return fa[x]=find(fa[x]);
 }
 struct node
 {
     int x,y,d,w;
     node(){}
 };
 int vis[1005];
node ee[1005*1005/2];
bool cmp(node  x,node y)
{
    return x.w>y.w;
}
int main()
{

    int n,m,k;

    while(cin>>n>>m)
    {
        int x,y,d,w;
        memset(vis,0,sizeof vis);
        for (int i=1; i<=n; i++) fa[i]=i;
        for (int i=1;i<=m;i++)
        {
            scanf("%d%d%d%d",&x,&y,&d,&w);
            ee[i].x=x;
            ee[i].y=y;
            ee[i].d=d;
            ee[i].w=w;
        }
        sort(ee+1,ee+1+m,cmp);
        int ans=0;
        for (int i=1;i<=m;i++)
        {
            int x=ee[i].x;
            int y=ee[i].y;
            int fx=find(x);
            int fy=find(y);
            if (vis[fx]&vis[fy] )continue;      //端点都被使用过
            else if (ee[i].d==1 &&vis[fx]) continue;    //单向边起点被用过

            ans+=ee[i].w;

            if (ee[i].d==1) vis[fx]=1;  //起点唯一
            else
            {
                if (fx==fy) vis[fx]=1;  //形成回环,则两端点都被覆盖了
                if (vis[fx]==0&&vis[fy]==0) fa[fx]=fy;  //起点任选,缩点
                else if (vis[fx]==1 )  vis[fy]=1;       //起点唯一
                else    if (vis[fy]==1) vis[fx]=1;      //起点唯一
            }
        }
        printf("%d\n",ans);


    }
    return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值