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

来源:互联网 发布:type3软件下载 编辑:程序博客网 时间:2024/06/08 06:05

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;}


0 0
原创粉丝点击