CF1923E 一个无需 DSU On Tree 的解法

在地铁上口胡了一下。不知道对不对。

考虑记录每一个点 i 离他最远的一个祖先使得祖先到 i 的路径上没有 ai。设他为 lsti。然后如果两个 u,vlst 相等,那么这条路径就是好的。每种颜色枚举即可。

八成假了(?),欢迎 Hack。

PS:全对了,确实能过。

/*******************************
| Author:  DE_aemmprty
| Problem: E. Count Paths
| Contest: Codeforces - Educational Codeforces Round 162 (Rated for Div. 2)
| URL:     https://codeforces.com/contest/1923/problem/E
| When:    2024-02-23 23:29:35
| 
| Memory:  512 MB
| Time:    2000 ms
*******************************/
#include <bits/stdc++.h>
using namespace std;

long long read() {
    char c = getchar();
    long long x = 0, p = 1;
    while ((c < '0' || c > '9') && c != '-') c = getchar();
    if (c == '-') p = -1, c = getchar();
    while (c >= '0' && c <= '9')
        x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
    return x * p;
}

const int N = 2e5 + 7;

int n;
int c[N], lst[N], f[N];
vector <int> to[N], pos[N];
vector <int> p[N];
vector <int> col;
int cnt[N];

void dfs(int u, int fa) {
    f[u] = fa;
    if (fa) p[c[fa]].push_back(u);
    lst[u] = 0;
    if (p[c[u]].size()) lst[u] = p[c[u]].back();
    for (int v : to[u])
        if (v != fa)
            dfs(v, u);
    if (fa) p[c[fa]].pop_back();
}

void solve() {
    n = read();
    for (int i = 1; i <= n; i ++) {
        c[i] = read();
        pos[i].clear();
        to[i].clear();
        p[i].clear();
    }
    for (int i = 1; i <= n; i ++)
        pos[c[i]].push_back(i);
    for (int i = 1, u, v; i < n; i ++) {
        u = read(), v = read();
        to[u].push_back(v);
        to[v].push_back(u);
    }
    dfs(1, 0); long long ans = 0;
    for (int i = 1; i <= n; i ++) {
        for (int x : pos[i]) {
            cnt[lst[x]] ++;
            col.push_back(lst[x]);
        }
        for (int x : col) {
            ans += 1ll * cnt[x] * (cnt[x] - 1) / 2;
            cnt[x] = 0;
        }
        col.clear();
    }
    for (int i = 1; i <= n; i ++)
        ans += (f[lst[i]] > 0);
    cout << ans << '\n';
}

signed main() {
    int t = 1;
    t = read();
    while (t --) solve();
    return 0;
}

作者:DE_aemmprty

出处:https://www.cnblogs.com/aemmprty/p/18090517

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   DE_aemmprty  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示