Luogu 3629 [APIO2010]巡逻

先考虑$k = 1$的情况,很明显每一条边都要被走两遍,而连成一个环之后,环上的每一条边都只要走一遍即可,所以我们使这个环的长度尽可能大,那么一棵树中最长的路径就是树的直径。

设直径的长度为$L$,答案就是$2(n - 1) - L + 1 = 2n - L - 1$。

考虑$k = 2$的情况,发现第一条边一定还是要把直径练成一个环,而第二条边是要再求一个类似于直径的东西,具体来说,可以把原来直径(记为$L_{1}$)上的每一条边的边权取为$-1$,然后再求一遍直径(记为$L_{2}$),这样子的话答案就是$2(n - 1) - (L_{1} - 1) - (L_{2} - 1) = 2n - L_{1} - L_{2}$。发现这样做之后如果第二条直径上包含着第一条直径上的部分,那么重叠的部分就被重新加了回来,所以这样子求出来的答案就是最后的答案。

由于可以在同一个点连边,那么$L_{2}$至少要为$0$。

注意第二次求直径的时候要使用树形$dp$,两次$bfs$的方法会挂,因为边带负权之后会相当于把之前带正权的边的贡献减掉,所以第一次求出来的一端并不一定是直径的一个端点。

时间复杂度$O(n)$。

Code:

#include <cstdio>
#include <cstring>
using namespace std;

const int N = 1e5 + 5;
const int inf = 1 << 30;

int n, m, tot = 1, head[N];
int root, eid[N], dis[N], ans = 0;
int f[N], d[N];

struct Edge {
    int to, nxt, val;
} e[N << 1];

inline void add(int from, int to) {
    e[++tot].to = to;
    e[tot].val = 1;
    e[tot].nxt = head[from];
    head[from] = tot;
}  

inline void read(int &X) {
    X = 0; char ch = 0; int op = 1;
    for(; ch > '9'|| ch < '0'; ch = getchar())
        if(ch == '-') op = -1;
    for(; ch >= '0' && ch <= '9'; ch = getchar())
        X = (X << 3) + (X << 1) + ch - 48;
    X *= op;
}

inline void chkMax(int &x, int y) {
    if(y > x) x = y;
}

void dfs(int x, int fat) {
    dis[x] = dis[fat] + 1;
    for(int i = head[x]; i; i = e[i].nxt) {
        int y = e[i].to;
        if(y == fat) continue;
        eid[y] = i ^ 1;
        dfs(y, x);
    }
}

void dfs2(int x, int fat) {
    bool flag = 0;
    for(int i = head[x]; i; i = e[i].nxt) {
        int y = e[i].to;
        if(y == fat) continue;
        flag = 1;
        dfs2(y, x);
        chkMax(ans, d[y] + e[i].val + d[x]);
        chkMax(d[x], d[y] + e[i].val);
    }
    if(!flag) d[x] = 0;
}

int main() {
    read(n), read(m);
    for(int x, y, i = 1; i < n; i++) {
        read(x), read(y);
        add(x, y), add(y, x);
    }
    
    dis[0] = -1;
    dfs(1, 0);
    dis[root = n + 1] = -inf;
    for(int i = 1; i <= n; i++)
        if(dis[i] > dis[root]) root = i;
    
    dfs(root, 0);    
    
/*    for(int i = 1; i <= n; i++)
        printf("%d ", dis[i]);
    printf("
");    */
    
    if(m == 1) {
        for(int i = 1; i <= n; i++)
            chkMax(ans, dis[i]);
        printf("%d
", 2 * n - 1 - ans);
        return 0;
    }
    
    int pnt = n + 1;
    for(int i = 1; i <= n; i++) 
        if(dis[pnt] < dis[i]) pnt = i;

    for(int x = pnt; x != root; x = e[eid[x]].to)
        e[eid[x]].val = e[eid[x] ^ 1].val = -1;
        
    memset(f, 128, sizeof(f));
    memset(d, 128, sizeof(d));
    ans = 0;
    dfs2(root, 0);
    
    printf("%d
", 2 * n - dis[pnt] - ans);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/CzxingcHen/p/9553604.html