ZOJ_1760

    只要保留S-T所有可能的最短路上的边,然后做最大流即可,题目数据存在f[i][i]!=0的情况,因此如果用floyd预处理的话要注意初始化f[i][i]=0。

#include<stdio.h>
#include<string.h>
#include<algorithm>
#define MAXD 110
#define MAXM 20010
#define INF 0x3f3f3f3f
int N, f[MAXD][MAXD], g[MAXD][MAXD], first[MAXD], e, next[MAXM], v[MAXM], flow[MAXM];
int d[MAXD], q[MAXD], work[MAXD], S, T;
void init()
{
    int i, j, k;
    for(i = 1; i <= N; i ++)
        for(j = 1; j <= N; j ++)
            scanf("%d", &g[i][j]), f[i][j] = g[i][j] == -1 ? INF : g[i][j];
    for(i = 1; i <= N; i ++)
        f[i][i] = 0;
    for(k = 1; k <= N; k ++)
        for(i = 1; i <= N; i ++)
            for(j = 1; j <= N; j ++)
                f[i][j] = std::min(f[i][j], f[i][k] + f[k][j]);
}
void add(int x, int y, int z)
{
    flow[e] = z, v[e] = y;
    next[e] = first[x], first[x] = e ++;
}
int bfs()
{
    int i, j, rear = 0;
    memset(d, -1, sizeof(d));
    d[S] = 0, q[rear ++] = S;
    for(i = 0; i < rear; i ++)
        for(j = first[q[i]]; j != -1; j = next[j])
            if(flow[j] && d[v[j]] == -1)
            {
                d[v[j]] = d[q[i]] + 1, q[rear ++] = v[j];
                if(v[j] == T)
                    return 1;
            }
    return 0;
}
int dfs(int cur, int a)
{
    if(cur == T)
        return a;
    int t;
    for(int &i = work[cur]; i != -1; i = next[i])
        if(flow[i] && d[v[i]] == d[cur] + 1)
            if(t = dfs(v[i], a < flow[i] ? a : flow[i]))
            {
                flow[i] -= t, flow[i ^ 1] += t;
                return t;
            }
    return 0;
}
int dinic()
{
    int ans = 0, t;
    while(bfs())
    {
        memcpy(work, first, sizeof(first));
        while(t = dfs(S, INF))
            ans += t;
    }
    return ans;
}
void solve()
{
    int i, j, k;
    scanf("%d%d", &S, &T);
    ++ S, ++ T;
    if(S == T)
    {
        printf("inf\n");
        return ;
    }
    if(f[S][T] == INF)
    {
        printf("0\n");
        return ;
    }
    memset(first, -1, sizeof(first));
    e = 0;
    for(i = 1; i <= N; i ++)
        for(j = 1; j <= N; j ++)
            if(i != j && g[i][j] != -1)
            {
                if(f[S][i] + g[i][j] + f[j][T] == f[S][T])
                    add(i, j, 1), add(j, i, 0);
            }
    printf("%d\n", dinic());
}
int main()
{
    while(scanf("%d", &N) == 1)
    {
        init();
        solve();
    }
    return 0;
}
posted on 2012-08-06 23:24  Staginner  阅读(329)  评论(0编辑  收藏  举报