线性规划与网络流24题 01飞行员配对方案问题

答案不唯一。。。所以可能直接测会是错误的。。。。


/*飞行员配对方案问题*/
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
#define inf 1<<30
#define maxn 10000

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

bool bfs(int s, int t) {
    int i, u, v, qin = 0, qout = 0;
    memset(lev, 0, sizeof (lev));
    lev[s] = 1, 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] == 0) {
                lev[v] = lev[u] + 1, que[qin++] = v;
                if (v == t) return 1;
            }
    }
    return lev[t];
}
int dinic(int s, int t) {
    int i, k, f, u;
    int flow = 0, qin = 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++;
}

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

int main() {
    int n, m, i, j, u, v;
    while (scanf("%d%d", &m, &n) != -1) {
        ainit();
        for(i=1;i<=m;i++) addedge(0,i,1);
        for(i=m+1;i<=n;i++) addedge(i,n+1,1);
        while (scanf("%d%d", &u, &v) && (u != -1 || v != -1))  addedge(u, v, 1);
        int ans = dinic(0, n + 1);
        if (ans <= 0) printf("No Solution!\n");
        else {
            printf("%d\n", ans);
            for (i = 0; i < p; i +=2)
                   if (edge[i].f == 0 &&edge[i].v!=n+1 && edge[i].u!=0){
                        printf("%d %d\n", edge[i].u, edge[i].v);
                   }
        }
    }
    return 0;
}


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