比赛 2024暑期C班集训4 评测结果 AAAAATTTTT
题目名称 飘雪圣域 最终得分 50
用户昵称 darkMoon 运行时间 5.009 s
代码语言 C++ 内存使用 15.06 MiB
提交时间 2024-07-04 09:31:40
显示代码纯文本
#include<bits/stdc++.h>
#define int long long
using namespace std;
ifstream fin("icekingdom.in");
ofstream fout("icekingdom.out");
auto mread = [](){int x;fin >> x;return x;};
const int N = 2e5 + 5;
int n = mread(), q = mread(), e[N], fa[N], ans = 0, sum[N], res[N];
vector<int> v[N];
void dfs(int x, int fa2){
    for(int y : v[x]){
        if(fa2 == y)
        continue;
        fa[y] = x;
        dfs(y, x);
    }
}
struct node{
    int l, r, id;
}s[N];
void add(int x){
    int tmp = sum[x];
    tmp += e[fa[x]];
    if(tmp == 0){
        ans ++;
    }
    else{
        ans -= tmp - 1;
    }
    e[x] = 1;
    sum[fa[x]] ++;
    // printf("*** %lld %lld %lld\n", x, tmp, ans);
    return;
}
void del(int x){
    int tmp = sum[x];
    tmp += e[fa[x]];
    if(tmp == 0){
        ans --;
    }
    else{
        ans += tmp - 1;
    }
    e[x] = 0;
    sum[fa[x]] --;
    // printf("--- %lld %lld %lld\n", x, tmp, ans);
    return;
}
signed main(){
    for(int i = 1, x, y; i < n; i ++){
        x = mread(), y = mread();
        v[x].push_back(y);
        v[y].push_back(x);
    }
    dfs(1, 0);
    for(int i = 1; i <= q; i ++){
        s[i].l = mread(), s[i].r = mread();
        s[i].id = i;
    }
    {
        int q = sqrt(n);
        sort(s + 1, s + 1 + q, [q](node a, node b){
            if(a.l / q == b.l / q)
            return a.r < b.r;
            return a.l < b.l;
        });
    }
    int l = 1, r = 0;
    for(int i = 1; i <= q; i ++){
        while(l > s[i].l){
            l --;
            add(l);
        }
        while(r < s[i].r){
            r ++;
            add(r);
        }
        while(l < s[i].l){
            del(l);
            l ++;
        }
        while(r > s[i].r){
            del(r);
            r --;
        }
        res[s[i].id] = ans;
    }
    for(int i = 1; i <= q; i ++)
    fout << res[i] << "\n";
    return 0;
}