luogu P2754 [CTSC1999]家园

本题是分层图最大流问题,相当于按时间拆点,每个当前点向下一点的下一时间层连点,每一层有n+1个点

#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) ((x)&(-x))
typedef long long LL;

const int maxm = 5e4+5;
const int INF = 0x3f3f3f3f;

struct edge{
    int u, v, cap, flow, nex;
} edges[maxm];

int head[maxm], cur[maxm], cnt, level[6005];

void init() {
    memset(head, -1, sizeof(head));
}

void add(int u, int v, int cap) {
    edges[cnt] = edge{u, v, cap, 0, head[u]};
    head[u] = cnt++;
}

void addedge(int u, int v, int cap) {
    add(u, v, cap), add(v, u, 0);
}

void bfs(int s) {
    memset(level, -1, sizeof(level));
    queue<int> q;
    level[s] = 0;
    q.push(s);
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        for(int i = head[u]; i != -1; i = edges[i].nex) {
            edge& now = edges[i];
            if(now.cap > now.flow && level[now.v] < 0) {
                level[now.v] = level[u] + 1;
                q.push(now.v);
            }
        }
    }
}

int dfs(int u, int t, int f) {
    if(u == t) return f;
    for(int& i = cur[u]; i != -1; i = edges[i].nex) {
        edge& now = edges[i];
        if(now.cap > now.flow && level[u] < level[now.v]) {
            int d = dfs(now.v, t, min(f, now.cap - now.flow));
            if(d > 0) {
                now.flow += d;
                edges[i^1].flow -= d;
                return d;
            }

        }
    }
    return 0;
}

int dinic(int s, int t) {
    int maxflow = 0;
    for(;;) {
        bfs(s);
        if(level[t] < 0) break;
        memcpy(cur, head, sizeof(head));
        int f;
        while((f = dfs(s, t, INF)) > 0)
            maxflow += f;
    }
    return maxflow;
}

int H[25], r[25], station[25][25];

void run_case() {
    init();
    int n, m, k;
    cin >> n >> m >> k;
    for(int i = 1; i <= m; ++i) {
        cin >> H[i] >> r[i];
        for(int j = 0; j < r[i]; ++j) {
            cin >> station[i][j];
            if(station[i][j] == -1) station[i][j] = n+1;
        }
    }
    int s = 0, t = n+1, maxflow = 0;
    for(int times = 1; times <= 500; ++times) {
        for(int i = 0; i <= n; ++i) addedge(i+(times-1)*(n+2), i+(times)*(n+2), INF);
        addedge(t+times*(n+2), t+(times-1)*(n+2), INF);
        for(int i = 1; i <= m; ++i) 
            addedge((times-1)*(n+2)+station[i][(times-1)%r[i]], times*(n+2)+station[i][times%r[i]], H[i]);
        maxflow += dinic(s, t);
        if(maxflow >= k) {
            cout << times;
            return;
        }
    }
    cout << 0;
}

int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    run_case();
    cout.flush();
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/GRedComeT/p/12305321.html