Hiho 119 网络流五·最大权闭合子图

这个题目之前建图写搓了 改了好久
这种建图要自己给点编号的题目 总是会写出一些奇奇怪怪的bug

题目思路

看题目标题就能知道这是一道最大权闭合子图的题
至于啥是最大权闭合子图
https://blog.csdn.net/can919/article/details/77603353
这是我学的时候看的博客
求最大权闭合子图的答案 就是求图中正权值之和减去最小割
而最小割刚好有等于最大流
这样我们先统计正权和 在跑最大流就能出结果了
建图的时候要细心一点 以免出现bug 浪费时间

ac代码

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <utility>
#define pi 3.1415926535898
#define ll long long
#define lson rt<<1
#define rson rt<<1|1
#define eps 1e-6
#define ms(a,b) memset(a,b,sizeof(a))
#define legal(a,b) a&b
#define print1 printf("111\n")
using namespace std;
const int maxn = 1e5+10;
const int inf = 0x3f3f3f3f;
const ll llinf =0x3f3f3f3f3f3f3f3f;
const int mod = 1e9+7;
int n,m,len;
int a[maxn],b[maxn],first[maxn],d[maxn];
struct node
{
    int to,next,v;
}e[maxn*10];
vector<int>vec[maxn];

void add(int u,int v,int w)
{
    e[len].to=v;
    e[len].v=w;
    e[len].next=first[u];
    first[u]=len++;
    swap(u,v);
    e[len].to=v;
    e[len].v=0;
    e[len].next=first[u];
    first[u]=len++;
}

bool makelevel(int s,int t)
{
    //print1;
    ms(d,0);
    queue<int>q;
    d[s]=1;
    q.push(s);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        if(x==t)return true;
        for(int i=first[x];i!=-1;i=e[i].next)
        {
            if(d[e[i].to]==0&&e[i].v!=0)
            {
                q.push(e[i].to);
                d[e[i].to]=d[x]+1;
            }
        }
    }
    return false;
}

int dfs(int x,int flow,int t)
{
    if(x==t)return flow;
    int sum=0;
    for(int i=first[x];i!=-1;i=e[i].next)
    {
        if(e[i].v!=0&&d[e[i].to]==d[x]+1)
        {
            int tem=dfs(e[i].to,min(flow-sum,e[i].v),t);
            e[i].v-=tem;
            e[i^1].v+=tem;
            sum+=tem;
            if(sum==flow)return sum;
        }
    }
    return sum;
}
int main()
{
    scanf("%d%d",&n,&m);
    int tem=0,sum=m+n;
    len=0;
    ms(first,-1);
    for(int i=1;i<=m;i++)
    {
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=n;i++)
    {
        int x,y;
        scanf("%d%d",&b[i],&x);
        tem+=b[i];
        for(int j=1;j<=x;j++)
        {
            scanf("%d",&y);
            vec[i].push_back(y);
        }
    }
    for(int i=1;i<=n;i++)
        add(0,i+m,b[i]);
    for(int i=1;i<=m;i++)
        add(i,n+m+1,a[i]);
    for(int i=1;i<=n;i++)
    {
        for(int j=0;j<vec[i].size();j++)
        {
            add(i+m,vec[i][j],inf);
        }
    }
    int ans=0;
    while(makelevel(0,n+m+1))
    {

        ans+=dfs(0,inf,n+m+1);
    }
    printf("%d\n",tem-ans);
}

猜你喜欢

转载自blog.csdn.net/daydreamer23333/article/details/107589249
119
今日推荐