[USACO15DEC] 最大流 Max Flow

Luogu P3128 [USACO15DEC] Max Flow

Code:

#include<cstdio>
#include<vector>
#include<iostream>
using namespace std;
const int MAXN = 1e5 + 5;

vector<int> grp[MAXN];
int n, k, ans;
int dep[MAXN], f[MAXN][22], power[MAXN];

int lca(int x, int y) {
    if (dep[x] > dep[y]) swap(x, y);
    for (int i = 20; i >= 0; --i) {
        if (dep[x] <= dep[y] - (1 << i)) y = f[y][i];
    }
        if (x == y) return x;
        for (int i = 20; i >= 0; --i) {
            if (f[x][i] != f[y][i])
                x = f[x][i], y = f[y][i];
    }
    return f[x][0];
}

void inisharu(int pos, int fa) {
    dep[pos] = dep[fa] + 1;
    f[pos][0] = fa;
    for(int i = 0; f[pos][i]; ++i) f[pos][i + 1] = f[f[pos][i]][i];
    for(int i = 0; i < grp[pos].size(); ++i) {
        if(grp[pos][i] == fa) continue;
        inisharu(grp[pos][i], pos);
    }
}

void getans(int pos, int fa) {
    for(int i = 0;i < grp[pos].size(); ++i) {
        if(grp[pos][i] == fa) continue;
        getans(grp[pos][i], pos);
        power[pos] += power[grp[pos][i]];
    }
    ans = max(ans, power[pos]);
}
int main() {
    scanf("%d %d", &n, &k);
    for(int i = 0; i < n - 1; ++i) {
        int arg1, arg2;
        scanf("%d %d", &arg1, &arg2);
        grp[arg1].push_back(arg2);
        grp[arg2].push_back(arg1);
    }
    inisharu(1, 0);
    for(int i = 0; i < k; ++i) {
        int arg1, arg2;
        scanf("%d %d", &arg1, &arg2);
        int lca1 = lca(arg1, arg2);
        ++power[arg1];
        ++power[arg2];
        --power[lca1];
        --power[f[lca1][0]];
    }
    getans(1, 0);
    printf("%d", ans);
    return 0;
}
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注