月赛T4求hack
  • 板块题目总版
  • 楼主朦胧_XY
  • 当前回复5
  • 已保存回复5
  • 发布时间2023/9/23 18:21
  • 上次更新2023/11/2 18:28:52
查看原帖
月赛T4求hack
358971
朦胧_XY楼主2023/9/23 18:21

用的树上启发式合并,25pts

#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
int n, f[N], ans, dep[N];
char c[N];
vector<int> E[N], lvs[N];
void dfs(int x, int y){
    dep[x] = dep[y] + 1;
    for(int ch : E[x]) if(ch ^ y){
        dfs(ch, x);
        if(c[x] ^ '(') continue;
        if(lvs[ch].size()){
            f[x] += f[ch];
            for(int p : lvs[ch]){ f[x]++;
                for(int to : E[p]) if(dep[to] > dep[p]){
                    f[x] += f[to];
                    if(lvs[x].size() < lvs[to].size()) swap(lvs[x], lvs[to]);
                    for(int t : lvs[to]) lvs[x].push_back(t);
                    lvs[to].clear();
                }
            }
        }
    }
    if(f[x]) f[x]++;
    else if(!lvs[x].size() && c[x] ^ '(') lvs[x].push_back(x);
    ans = max(ans, f[x]);
    return;
}
int main(){
    int x, y;
    scanf("%d", &n);
    c[1] = getchar();
    while(c[1]^'(' && c[1]^')') c[1] = getchar();
    for(int i = 2; i <= n; i++) c[i] = getchar();
    for(int i = 1; i < n; i++){
        scanf("%d%d", &x, &y);
        E[x].push_back(y), E[y].push_back(x);
    }
    dfs(1, 0);
    printf("%d", ans);
    return 0;
}
2023/9/23 18:21
加载中...