BZOJ 1497 最大获利(最大权闭合子图)

将第i个用户群和第ia和第ib个中转站连边,这是一个显然的二分图。

那么题目的最大获利就是要求求出这个二分图的最大权闭合子图。

对于最大权闭合子图的算法有网络流,将s和正权点连权值的边,负权点和t连权值的绝对值的边。原图中的边容量设为无穷大。

则这个最大权闭合子图的权为 正权点之和-最小割。

 

# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi 3.1415926535
# define eps 1e-9
# define MOD 100000007
# define INF 1000000000
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<1,l,mid
# define rch p<<1|1,mid+1,r
# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
    int res=0, flag=0;
    char ch;
    if((ch=getchar())=='-') flag=1;
    else if(ch>='0'&&ch<='9') res=ch-'0';
    while((ch=getchar())>='0'&&ch<='9')  res=res*10+(ch-'0');
    return flag?-res:res;
}
void Out(int a) {
    if(a<0) {putchar('-'); a=-a;}
    if(a>=10) Out(a/10);
    putchar(a%10+'0');
}
const int N=60005;
//Code begin...

struct Edge{int p, next, w;}edge[8*N];
int head[N], cnt=2, s, t, vis[N];
queue<int>Q;

void add_edge(int u, int v, int w){
    edge[cnt].p=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt++;
    edge[cnt].p=u; edge[cnt].w=0; edge[cnt].next=head[v]; head[v]=cnt++;
}
int bfs(){
    int i, v;
    mem(vis,-1);
    vis[s]=0; Q.push(s);
    while (!Q.empty()) {
        v=Q.front(); Q.pop();
        for (i=head[v]; i; i=edge[i].next) {
            if (edge[i].w>0 && vis[edge[i].p]==-1) {
                vis[edge[i].p]=vis[v] + 1;
                Q.push(edge[i].p);
            }
        }
    }
    return vis[t]!=-1;
}
int dfs(int x, int low){
    int i, a, temp=low;
    if (x==t) return low;
    for (i=head[x]; i; i=edge[i].next) {
        if (edge[i].w>0 && vis[edge[i].p]==vis[x]+1){
            a=dfs(edge[i].p,min(edge[i].w,temp));
            temp-=a; edge[i].w-=a; edge[i^1].w += a;
            if (temp==0) break;
        }
    }
    if (temp==low) vis[x]=-1;
    return low-temp;
}
int main ()
{
    int n, m, tmp, x, y, sum=0;
    n=Scan(); m=Scan();
    s=0; t=n+m+1;
    FOR(i,1,n) tmp=Scan(), add_edge(m+i,t,tmp);
    FOR(i,1,m) x=Scan(), y=Scan(), tmp=Scan(), add_edge(i,m+x,INF), add_edge(i,m+y,INF), add_edge(s,i,tmp), sum+=tmp;
    int res=0;
    while (bfs()) while (tmp=dfs(s,INF)) res+=tmp;
    printf("%d\n",sum-res);
    return 0;
}
View Code

 

posted @ 2017-03-18 16:32  free-loop  阅读(218)  评论(0编辑  收藏  举报