POJ 1966 Cable TV Network

POJ_1966

    由于枚举的点有可能恰好是割点,所以要分别枚举源点和汇点,而且源点和汇点不能相邻,然后做最大流。所有最大流中的最小值即为最后结果,当然如果所有点都相邻的话结果自然就是N了。

#include<stdio.h>
#include<string.h>
#include<algorithm>
#define MAXD 110
#define MAXM 10110
#define INF 0x3f3f3f3f
char b[110];
int N, M, first[MAXD], e, next[MAXM], v[MAXM], flow[MAXM], g[MAXD][MAXD];
int S, T, d[MAXD], q[MAXD], work[MAXD], ANS;
struct Edge
{
    int x, y;    
}edge[MAXM];
void init()
{
    int i;
    memset(g, 0, sizeof(g));
    for(i = 0; i < M; i ++)
    {
        scanf("%s", b), sscanf(b, "(%d,%d)", &edge[i].x, &edge[i].y);
        g[edge[i].x][edge[i].y] = g[edge[i].y][edge[i].x] = 1;
    }
}
void add(int x, int y, int z)
{
    v[e] = y, flow[e] = z;
    next[e] = first[x], first[x] = e ++;    
}
void build(int s, int t)
{
    int i, j;
    S = s + N, T = t;
    memset(first, -1, sizeof(first[0]) * (N * 2 + 2)), e = 0;
    for(i = 0; i < N; i ++)
        add(i, i + N, 1), add(i + N, i, 0);
    for(i = 0; i < M; i ++)
    {
        add(edge[i].x + N, edge[i].y, INF), add(edge[i].y, edge[i].x + N, 0);
        add(edge[i].y + N, edge[i].x, INF), add(edge[i].x, edge[i].y + N, 0);
    }
}
int bfs()
{
    int i, j, rear = 0;
    memset(d, -1, sizeof(d[0]) * (N * 2 + 2));
    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;
}
int dinic()
{
    int ans = 0, t;
    while(bfs())
    {
        memcpy(work, first, sizeof(first[0]) * (N * 2 + 2));
        while(t = dfs(S, INF))
            ans += t;
    }
    return ans;
}
void solve()
{
    int i, j, ans = N;
    for(i = 0; i < N; i ++)
        for(j = i + 1; j < N; j ++)
            if(!g[i][j])
            {
                build(i, j);
                ans = std::min(ans, dinic());    
            }
    printf("%d\n", ans);
}
int main()
{
    while(scanf("%d%d", &N, &M) == 2)
    {
        init();
        solve();    
    }
    return 0;
}

你可能感兴趣的:(NetWork)