codeforces 546E 分类: codeforces 2015-05-27 20:33 36人阅读 评论(0) 收藏


网络流,主要看思维,CF有官方题解。


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

const int MAXN = 105, MAXM = 205, INF = 1<<30;

int n, m;
int ss, tt, ind;

int a[MAXN], b[MAXN];
int an[MAXN], bn[MAXN];
int maxflow, sa, sb;

int cap[MAXN<<1][MAXN<<1];

int dep[MAXN<<1];

std::queue<int> line;

void BuildEdge(int u,int v,int w)
{
    cap[u][v] = w, cap[v][u] = 0;
}

int BFS()
{
    memset(dep,0,sizeof(dep));
    dep[ss] = 1, line.push(ss);

    while(!line.empty())
    {
        int t = line.front(); line.pop();
        for(int i = 1; i <= ind; i++)
            if(cap[t][i] > 0 && !dep[i]) 
                dep[i] = dep[t] + 1, line.push(i);      
    }

    return dep[tt];
}

int DFS(int a,int flow)
{
    if(a == tt || flow == 0) return flow;

    int ret = 0;

    for(int i = 1; i <= ind && flow; i++)
        if(cap[a][i] > 0 && dep[i] == dep[a] + 1)
        {
            int ff = DFS(i,std::min(flow,cap[a][i]));

            flow -= ff;

            cap[a][i] -= ff;
            cap[i][a] += ff;

            ret += ff;
        }
    return ret; 
}
int Dinic()
{
    int ret = 0;
    while(1)
    {
        if(!BFS()) break;
        ret += DFS(ss,INF);
    }
    return ret;
}

int main()
{
#ifndef ONLINE_JUDGE    
    freopen("546E.in","r",stdin);
    freopen("546E.out","w",stdout);
#endif

    std::cin >> n >> m;

    for(int i = 1; i <= n; i++)
        std::cin >> a[i];
    for(int i = 1; i <= n; i++)
        std::cin >> b[i];

    ss = ++ind, tt = ++ind;

    for(int i = 1; i <= n; i++)
    {
        an[i] = ++ind, bn[i] = ++ind;

        BuildEdge(ss,an[i],a[i]);
        BuildEdge(bn[i],tt,b[i]);
        BuildEdge(an[i],bn[i],INF);

        sa += a[i], sb += b[i];
    }
    for(int i = 1,u,v; i <= m; i++)
    {
        std::cin >> u >> v;
        BuildEdge(an[u],bn[v],INF);
        BuildEdge(an[v],bn[u],INF);
    }

    maxflow = Dinic();

    if(maxflow == sa && maxflow == sb)
    {
        puts("YES");
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= n; j++)
                std::cout << cap[bn[j]][an[i]] << ' ';
            std::cout << std::endl; 
        }   
    }
    else
        puts("NO");

#ifndef ONLINE_JUDGE    
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-05-27 20:33  <Dash>  阅读(109)  评论(0编辑  收藏  举报