poj 1273 Drainage Ditches 最大流

解题思路: 源点为1,汇点为N, 直接求最大流就好

View Code
#include<stdio.h>
#include<string.h>
#include<string.h>
#define MIN(a,b) (a)<(b)?(a):(b)
const int inf = ~0u>>1;
const int MAXN = 210;
int n, m, S, T, N;
int    head[MAXN], idx, h[MAXN], vh[MAXN];
struct Edge{
    int v, f, nxt;    
}edge[MAXN<<4];

void AddEdge(int u,int v,int f)
{
    edge[idx].v = v; edge[idx].f = f;
    edge[idx].nxt = head[u]; head[u] = idx++;
    edge[idx].v = u; edge[idx].f = 0;
    edge[idx].nxt = head[v]; head[v] = idx++;
}
void build()
{
    int u, v, f;
    S = 1; T = n; N = n;    
    memset( head, 0xff, sizeof(head));
    idx = 0;
    for(int i = 0; i < m; i++)
    {
        scanf("%d%d%d", &u,&v,&f);
        AddEdge( u, v, f );
    }
}
int DFS( int u, int flow )
{
    if( u == T ) return flow;
    int tmp = h[u]+1, remain = flow;
    for(int i = head[u]; ~i; i = edge[i].nxt)
    {
        int v = edge[i].v;
        if( edge[i].f && h[u] == h[v]+1 )
        {
            int p = DFS( v, MIN(remain,edge[i].f) );
            edge[i].f -= p; edge[i^1].f += p; remain -= p;
            if( remain == 0 || h[S] == N ) return flow-remain;
        }
    }
    for(int i = head[u]; ~i; i = edge[i].nxt )
        if( edge[i].f )    tmp = MIN( tmp, h[ edge[i].v ] );
    if( !( --vh[ h[u] ] )  )    h[S] = N;
    else    ++vh[ h[u] = tmp+1 ];
    return flow - remain;
}
void sap()
{
    int maxflow = 0;
    memset( vh, 0, sizeof(vh));
    memset( h, 0, sizeof(h));
    vh[0] = N;
    while( h[S] < N ) maxflow += DFS( S, inf );
    printf("%d\n", maxflow );
}
int main()
{
    while( scanf("%d%d", &m,&n) != EOF)
    {
        build();
        sap();
    }
    return 0; 
}

 

posted @ 2012-12-10 19:39  yefeng1627  阅读(146)  评论(0编辑  收藏  举报

Launch CodeCogs Equation Editor