线性规划与网络流24题 02太空飞行计划问题

这个题的shut5.in的数据会是多解,所以评测可能出错。。。。。。很好的一个题。。。重点在向最小割的转化。。。。。建议看一下胡泊涛的论文《最小割模型在信息学竞赛中的应用》 里面很详细。。也很好。。。。


#include
#include
#include
using namespace std;
#define inf 1<<30
#define M 100000
#define N 10000
#define cc(m,v) memset(m,v,sizeof(m))

struct node {
    int u, v, f, next;
} edge[M];
int head[N], p, lev[N], cur[N];
int que[M];

void ainit() {
    p = 0, cc(head, -1);
}

bool bfs(int s, int t) {
    int i, u, v, qin = 0, qout = 0;
    cc(lev, -1), lev[s] = 0, que[qin++] = s;
    while (qout != qin) {
        u = que[qout++];
        for (i = head[u]; i != -1; i = edge[i].next)
            if (edge[i].f > 0 && lev[v = edge[i].v] == -1) {
                lev[v] = lev[u] + 1, que[qin++] = v;
                if (v == t) return 1;
            }
    }
    return 0;
}

int dinic(int s, int t) {
    int i, f, k, u, qin;
    int flow = 0;
    while (bfs(s, t)) {
        memcpy(cur, head, sizeof (head));
        u = s, qin = 0;
        while (1) {
            if (u == t) {
                for (k = 0, f = inf; k < qin; k++)
                    if (edge[que[k]].f < f) f = edge[que[i = k]].f;
                for (k = 0; k < qin; k++)
                    edge[que[k]].f -= f, edge[que[k]^1].f += f;
                flow += f, u = edge[que[qin = i]].u;
            }
            for (i = cur[u]; cur[u] != -1; i = cur[u] = edge[cur[u]].next)
                if (edge[i].f > 0 && lev[u] + 1 == lev[edge[i].v]) break;
            if (cur[u] != -1)
                que[qin++] = cur[u], u = edge[cur[u]].v;
            else {
                if (qin == 0) break;
                lev[u] = -1, u = edge[que[--qin]].u;
            }
        }
    }
    return flow;
}

void addedge(int u, int v, int f) {
    edge[p].u = u, edge[p].v = v, edge[p].f = f, edge[p].next = head[u], head[u] = p++;
    edge[p].u = v, edge[p].v = u, edge[p].f = 0, edge[p].next = head[v], head[v] = p++;
}

int main() {
    int n, m, i, cost, u, ans, sum;
    while (scanf("%d%d", &m, &n) != -1) {
        ainit();
        for (i = 1, sum = 0; i <= m; i++) {
            scanf("%d", &cost);
            sum += cost, addedge(0, i, cost);
            while (getchar() != '\n') {
                scanf("%d", &u);
                addedge(i, u + m, inf);
            }
        }
        for (i = 1; i <= n; i++) {
            scanf("%d", &u);
            addedge(i + m, n + m + 1, u);
        }
        ans = dinic(0, n + m + 1);
        for (i = 1; i <= m; i++) if (lev[i] != -1)
                printf("%d ", i);
        printf("\n");
        for (i = m + 1; i <= n + m; i++) if (lev[i] != -1)
                printf("%d ", i - m);
        printf("\n%d\n",sum - ans);
    }
    return 0;
}


你可能感兴趣的:(网络流)