QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#770001#9570. Binary TreeeastcloudTL 0ms0kbC++172.4kb2024-11-21 20:13:492024-11-21 20:13:50

Judging History

你现在查看的是最新测评结果

  • [2024-11-21 20:13:50]
  • 评测
  • 测评结果:TL
  • 用时:0ms
  • 内存:0kb
  • [2024-11-21 20:13:49]
  • 提交

answer


#include<bits/stdc++.h>

#define ll long long
#define pi pair<int,int>
#define vi vector<int>
#define cpy(x,y,s) memcpy(x,y,sizeof(x[0])*(s))
#define mset(x,v,s) memset(x,v,sizeof(x[0])*(s))
#define all(x) begin(x),end(x)
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ary array
#define eb emplace_back
#define IL inline

using namespace std;

#define N 300005

int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0' || ch>'9')f=(ch=='-'?-1:f),ch=getchar();
    while(ch>='0' && ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
    return x*f;
}
void write(int x){
    if(x<0)x=-x,putchar('-');
    if(x/10)write(x/10);
    putchar(x%10+'0');
}

vi e[N];
int vis[N],siz[N],tot;
int rt,maxn;

void find_root(int x,int fa){
    int maxsiz=0;siz[x]=1;
    for(auto v:e[x]){
        if(v==fa || vis[v])continue;
        find_root(v,x);siz[x]+=siz[v];
        maxsiz=max(maxsiz,siz[v]);
    }
    maxsiz=max(maxsiz,tot-siz[x]);
    if(maxsiz<maxn)maxn=maxsiz,rt=x;
}

void solve(){
    int n=read();
    for(int i=1;i<=n;i++)e[i].clear(),vis[i]=0;
    for(int i=1;i<=n;i++){
        int ls=read(),rs=read();
        if(ls)e[i].pb(ls),e[ls].pb(i);
        if(rs)e[i].pb(rs),e[rs].pb(i);
    }
    int x=1;
    while(1){
        vi S;
        for(auto v:e[x])if(!vis[v])S.pb(v);
        if(!S.size()){cout<<"! "<<x<<endl;break;}
        find_root(x,0);rt=0;maxn=n+5;tot=siz[x];find_root(x,0);
        x=rt;S.clear();
        for(auto v:e[x])if(!vis[v])S.pb(v);
        if(S.size()==1){
            int v=e[x][0];
            cout<<"? "<<x<<' '<<v<<endl;int res;cin>>res;
            if(x==0)cout<<"! "<<x<<endl;
            else cout<<"! "<<v<<endl;break;
        }
        else if(S.size()==2){
            int u=S[0],v=S[1];
            cout<<"? "<<u<<' '<<v<<endl;int res;cin>>res;
            if(res==1){cout<<"! "<<x<<endl;break;}             
            else if(res==0)vis[x]=1,x=u;
            else vis[x]=1,x=v;
        }
        else{
            sort(all(S),[](int x,int y){return siz[x]>siz[y];});
            cout<<"? "<<S[0]<<' '<<S[1]<<endl;int res;cin>>res;
            if(res==1)vis[S[0]]=vis[S[1]]=1;
            else if(res==0)vis[x]=1,x=S[0];
            else vis[x]=1,x=S[1];
        }
    }
}

int main(){

    int T=read();while(T--)solve();
    return 0;
}

詳細信息

Test #1:

score: 0
Time Limit Exceeded

input:

2
5
0 0
1 5
2 4
0 0
0 0
2
0

output:

? 1 3
? 4 3
! 3

result: