跳到正文

题解

题解:P17283 「IXOI R2」Retribution ~ Cycle of Redemption ~

hzw234约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年8月21日
收录
2026年8月21日
更新
2026年11月18日
篇幅
约 2 分钟
获赞
1
题目
P17283

版本

  1. v2当前
  2. v1

直接从小到大枚举每个数能否成为答案

这个数要想成为答案,当且仅当不选它自身或不选两个数,这两个数在它的不同子树上

换言之,就是所选所有的数都在它的同一子树或非子树上

因此,我只要预先搜出它的最大子树d[u]d[u]大小与子树大小sz[u]sz[u]则要想成为答案,就满足n−sz[u]+d[u]>=xn-sz[u]+d[u]>=x即可

AC代码

C++
#include<bits/stdc++.h>
using namespace std;
int d[1000005],sz[1000005],ver[2000005],nex[2000005],edge[2000005],head[2000005];
int n,r,qu,tot,t;
queue<int>q;
void add(int x,int y){
	ver[++tot]=y;
	nex[tot]=head[x];
	head[x]=tot;
}
void dfs(int u,int fa){
    for(int i=head[u];i;i=nex[i]){
        int v=ver[i];
        if(v==fa)
            continue;
        dfs(v,u);
        sz[u]+=sz[v];
        d[u]=max(d[u],sz[v]);
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin>>n>>qu>>r;
    for(int i=1;i<=n-1;i++){
        int a,b;
        cin>>a>>b;
        add(a,b);
        add(b,a);
    }
    for(int i=0;i<n;i++)
        sz[i]=1;
    dfs(r,-1);
    while(qu--){
        int x,ans;
        cin>>x;
        if(x==n)
            cout<<n<<'\n';
        else{
            for(int i=0;i<n;i++){
                if(n-sz[i]+d[i]>=x){
                    cout<<i<<'\n';
                    break;
                }
            }
        }  
    }
}
原文