萌新初学虚树,求调(wa on11)
查看原帖
萌新初学虚树,求调(wa on11)
342487
BreakPlus楼主2022/7/2 10:21

提示信息:wrong answer 9th numbers differ - expected: '2', found: '3'

看到讨论区里有人发的 wa on 11 的问题可能,但我都没有错啊

建虚树参考了第二篇题解

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,u,v; vector<ll>Edge[200005],E[200005],now;
ll f[25][200005],dep[200005],mk[200005],have[200005],dfn[200005],tim;
void dfs(ll x,ll fa,ll d){
    f[0][x]=fa; dep[x]=d; dfn[x]=++tim;
    for(auto y: Edge[x]){
        if(y==fa) continue;
        dfs(y,x,d+1);
    }
}
void startLCA(){
    for(ll i=1;i<=20;i++)
        for(ll j=1;j<=n;j++) f[i][j]=f[i-1][f[i-1][j]];
}
ll LCA(ll x,ll y){
    if(x==y){ return x;}
    if(dep[x]<dep[y]) swap(x,y);
    for(ll i=20;i>=0;i--)
        if(dep[f[i][x]]>=dep[y]) x=f[i][x];
    if(x==y){ return x;}
    for(ll i=20;i>=0;i--)
        if(f[i][x]!=f[i][y]) x=f[i][x], y=f[i][y];
    return f[0][x];
}
bool cmp(ll a,ll b){
    return dfn[a]<dfn[b];
}
ll tmp[200005],cnt;
void doit(){
    cnt=0;
    for(auto x: now) tmp[++cnt]=x;
    sort(tmp+1,tmp+cnt+1,cmp); ll ncnt=cnt;
    for(ll i=2;i<=ncnt;i++){
        tmp[++cnt]=(LCA(tmp[i],tmp[i-1]));
    }
    sort(tmp+1,tmp+cnt+1); cnt=unique(tmp+1,tmp+cnt+1)-(tmp+1);
    sort(tmp+1,tmp+cnt+1,cmp);
    for(ll i=2;i<=cnt;i++){
        ll fa=LCA(tmp[i],tmp[i-1]);
        E[fa].push_back(tmp[i]);
    }
}
ll dp(ll x){
    // cout<<"node: "<<x<<" fa: "<<fa<<endl;
    ll res=0;
    for(auto y: E[x]){
        res+=dp(y);
    }
    if(mk[x]){
        for(auto y: E[x]){
            res+=have[y];
        }
        have[x]=1;
    }else{
        ll cnt=0;
        for(auto y: E[x]){
            cnt+=have[y];
        }
        if(cnt>1) res++;
        else have[x]=1;
    }
    return res;
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    #ifndef ONLINE_JUDGE
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);
    #endif
    /*----------------------------*/
    cin>>n;
    for(ll i=1;i<n;i++) cin>>u>>v, Edge[u].push_back(v), Edge[v].push_back(u);
    dfs(1,0,1);
    startLCA();
    ll t; cin>>t;
    while(t--){
        ll cnts; cin>>cnts; now.clear();
        while(cnts--) {
            ll r; cin>>r; now.push_back(r); mk[r]=1;
        }
        bool flag=0;
        for(auto x: now){
            if(mk[f[0][x]]){
                flag=1;
                cout<<"-1"<<endl;
                break;
            }
        }
        if(flag){
            for(auto x: now) mk[x]=0;
            continue;
        }
        doit();
        cout<<dp(tmp[1])<<endl;
        for(ll i=1;i<=cnt;i++) mk[tmp[i]]=have[tmp[i]]=0, E[tmp[i]].clear();
    }
    /*----------------------------*/
    return 0;
}
2022/7/2 10:21
加载中...