poj 3228 二分+最大流

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>

using namespace std;

const int VM=220;
const int EM=50010;
const int INF=0x3f3f3f3f;

int n,m,src,des,map[VM][VM],dis[VM][VM];
int total,gold[VM],store[VM],dep[VM];

int min(int a,int b) {
	return a>b?b:a;
}
void buildgraph(int x){
	int i;
    memset(map,0,sizeof(map));
    for( i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            if(dis[i][j]<=x)
                map[i][j]=INF;
    for( i=1;i<=n;i++){
        map[src][i]=gold[i];
        map[i][des]=store[i];
    }
}

int BFS(){
    queue<int> q;
    while(!q.empty())
        q.pop();
    memset(dep,-1,sizeof(dep));
    dep[src]=0;
    q.push(src);
    while(!q.empty()){
        int u=q.front();
        q.pop();
        for(int v=src;v<=des;v++)
            if(map[u][v]>0 && dep[v]==-1){
                dep[v]=dep[u]+1;
                q.push(v);
            }
    }
    return dep[des]!=-1;
}

int DFS(int u,int minx){
    if(u==des)
        return minx;
    int tmp;
    for(int v=src;v<=des;v++)
        if(map[u][v]>0 && dep[v]==dep[u]+1 && (tmp=DFS(v,min(minx,map[u][v])))){
            map[u][v]-=tmp;
            map[v][u]+=tmp;
            return tmp;
        }
    dep[u]=-1;
    return 0;
}

int Dinic(){
    int ans=0,tmp;
    while(BFS()){
        while(1){
            tmp=DFS(src,INF);
            if(tmp==0)
                break;
            ans+=tmp;
        }
    }
    return ans;
}

int main(){

    //freopen("input.txt","r",stdin);
int i,j;
    while(~scanf("%d",&n) && n){
 for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
dis[i][j]=INF;
        total=0;
        src=0,  des=n+1;
        for( i=1;i<=n;i++){
            scanf("%d",&gold[i]);
            total+=gold[i];     //宝藏的总数
        }
        for( i=1;i<=n;i++)
            scanf("%d",&store[i]);
        scanf("%d",&m);
        int u,v,w;
        while(m--){
            scanf("%d%d%d",&u,&v,&w);
            dis[u][v]=dis[v][u]=w;
        }
        int l=0,r=100010;
        int ans=-1,tmp;
        while(l<=r){
            int mid=(l+r)>>1;
            buildgraph(mid);
            tmp=Dinic();
            if(tmp==total){
                ans=mid;
                r=mid-1;
            }else
                l=mid+1;
        }
        if(ans==-1)
            printf("No Solution\n");
        else
            printf("%d\n",ans);
    }
    return 0;
}

posted @ 2014-07-29 20:04  HYDhyd  阅读(168)  评论(0编辑  收藏  举报