POJ 3204 Ikki's Story I - Road Reconstruction

POJ_3204

    这个题目和ZOJ_2532是一样的题目,具体的思路可以参考我的ZOJ_2532的解题报告:http://www.cnblogs.com/staginner/archive/2012/08/11/2633751.html

#include<stdio.h>
#include<string.h>
#include<algorithm>
#define MAXD 510
#define MAXM 10010
#define INF 0x3f3f3f3f
int N, M, first[MAXD], e, next[MAXM], v[MAXM], flow[MAXM];
int S, T, d[MAXD], q[MAXD], work[MAXD], visx[MAXD], visy[MAXD];
void add(int x, int y, int z)
{
    v[e] = y, flow[e] = z;
    next[e] = first[x], first[x] = e ++;
}
void init()
{
    int i, x, y, z;
    S = 0, T = N - 1;
    memset(first, -1, sizeof(first[0]) * N), e = 0;
    for(i = 0; i < M; i ++)
    {
        scanf("%d%d%d", &x, &y, &z);
        add(x, y, z), add(y, x, 0);
    }
}
int bfs()
{
    int i, j, rear = 0;
    memset(d, -1, sizeof(d[0]) * N);
    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;
    for(int &i = work[cur]; i != -1; i = next[i])
        if(flow[i] && d[v[i]] == d[cur] + 1)
            if(int t = dfs(v[i], std::min(a, flow[i])))
            {
                flow[i] -= t, flow[i ^ 1] += t;
                return t;
            }
    return 0;
}
void dinic()
{
    while(bfs())
    {
        memcpy(work, first, sizeof(first[0]) * N);
        while(dfs(S, INF));
    }
}
void DFS(int cur, int *vis, int k)
{
    int i;
    vis[cur] = 1;
    for(i = first[cur]; i != -1; i = next[i])
        if(!vis[v[i]] && flow[i ^ k] != 0)
            DFS(v[i], vis, k);
}
void solve()
{
    int i, cnt = 0;
    dinic();
    memset(visx, 0, sizeof(visx[0]) * N), memset(visy, 0, sizeof(visy[0]) * N);
    DFS(S, visx, 0), DFS(T, visy, 1);
    for(i = 0; i < e; i += 2)
        if(flow[i] == 0 && visx[v[i ^ 1]] && visy[v[i]])
            ++ cnt;
    printf("%d\n", cnt);
}
int main()
{
    while(scanf("%d%d", &N, &M) == 2)
    {
        init();
        solve();
    }
    return 0;
}

你可能感兴趣的:(struct)