【树上点分治3】 Ciel the Commander CodeForces 321C

原题链接
在这里插入图片描述
题意:给定N个守卫,按照A-Z的等级从高到低排布,要求每两个相同等级的守卫的最短路径上都有比他等级高的守卫,问构造的方法。

如果对点分治理解很透彻的话,应该可以看出,每次取的根结点无非就是高等级的守卫,因为所有的点对都会经过这个根。

再则就是判断impossible的情形,如果点分了26次以上,那么就无解了。

#include <bits/stdc++.h>
using namespace std;
//#define ACM_LOCAL
typedef long long ll;
const int MOD = 1e9 + 7;
const int N = 1e5 + 5, M = 2e5 + 5, INF = 0x3f3f3f3f;

struct Edge {
    
    
    int to, next, vi;
} e[N << 1];

int h[N], cnt, m, p[N], idx;

void add(int u, int v, int w) {
    
    
    e[cnt].to = v;
    e[cnt].vi = w;
    e[cnt].next = h[u];
    h[u] = cnt++;
}

ll ans = 0;
int root, sum, n;
int sz[N], mx[N], vis[N];

void getroot(int x, int fa) {
    
    
    sz[x] = 1, mx[x] = 0;
    for (int i = h[x]; ~i; i = e[i].next) {
    
    
        int y = e[i].to;
        if (vis[y] || y == fa) continue;
        getroot(y, x);
        sz[x] += sz[y];
        mx[x] = max(mx[x], sz[y]);
    }
    mx[x] = max(mx[x], sum - sz[x]);
    if (mx[x] < mx[root]) root = x;
}

int d[N], dep[N];

int K;
void work(int x, int idx) {
    
    
    if (!p[x]) p[x] = idx;
    vis[x] = 1;
    for (int i = h[x]; ~i; i = e[i].next) {
    
    
        int y = e[i].to;
        if (vis[y]) continue;
        sum = sz[y], root = 0;
        getroot(y, -1);
        work(root, idx+1);
    }
}
void solve() {
    
    
    scanf("%d", &n);
    memset(h, -1, sizeof h);
    for (int i = 1; i <= n-1; i++) {
    
    
        int x, y;
        scanf("%d %d", &x, &y);
        add(x, y, 1);
        add(y, x, 1);
    }
    root = 0, mx[0] = INF, sum = n;
    getroot(1, -1);
    work(root, 1);
    if (idx > 26) {
    
    
        printf("Impossible!\n");
        return;
    }
    for (int i = 1; i <= n; i++) printf("%c ", p[i]+'A'-1);
}

signed main() {
    
    
    cin.tie(0);
    cout.tie(0);
#ifdef ACM_LOCAL
    freopen("input", "r", stdin);
    freopen("output", "w", stdout);
#endif
    solve();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/kaka03200/article/details/109406716