巡逻

AcWing-350-巡逻open in new window

分析

见《进阶指南》第371页。

实现

#include <iostream>
#include <cstring>
#include <queue>
#define inf 0x3f3f3f3f
using namespace std;

const int N = 100010;
struct edge {
    int to, next, w;
};
edge e[2 * N];
int idx, head[N];
int n, k, L2 = -inf;
int dis[N], eid[N];

void add_edge (int u, int v, int w) {
    e[idx].w = w;
    e[idx].to = v;
    e[idx].next = head[u];
    head[u] = idx ++;
}
int bfs (int rt) {
    memset(dis, 0x3f, sizeof(dis));
    
    queue<int> q;
    dis[rt] = 0;
    q.push(rt);
    while (!q.empty()) {
        int cur = q.front();
        q.pop();
        for (int i = head[cur]; i != -1; i = e[i].next) {
            int to = e[i].to, w = e[i].w;
            if (dis[to] == inf) {
                dis[to] = dis[cur] + w;
                eid[to] = i;
                q.push(to);
            }
        }
    }
    int ver = 1;
    for (int i = 2; i <= n; ++ i)
        if (dis[i] > dis[ver])
            ver = i;
    return ver;
}
void dfs (int cur, int fa) {
    for (int i = head[cur]; i != -1; i = e[i].next) {
        int to = e[i].to, w = e[i].w;
        if (to == fa) continue;
        dfs(to, cur);
        L2 = max(L2, dis[cur] + dis[to] + w);
        dis[cur] = max(dis[cur], dis[to] + w);
    }
}
void modify (int x, int y) {
    while (y != x) {
        e[eid[y]].w = -1;
        e[eid[y] ^ 1].w = -1;
        y = e[eid[y] ^ 1].to;
    }
}

int main () {
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &k);
    for (int i = 1, u, v; i <= n - 1; ++ i) {
        scanf("%d%d", &u, &v);
        add_edge(u, v, 1);
        add_edge(v, u, 1);
    }

    int x = bfs(1);
    int y = bfs(x);
    int res = 2 * (n - 1) - dis[y] + 1;
    if (k == 1) {
        printf("%d", res);
    } else {
        modify(x, y);
        memset(dis, 0, sizeof(dis));
        dfs(1, -1);
        printf("%d", res - L2 + 1);
    }
    return 0;
}
最后修改于: