QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#744557 | #9570. Binary Tree | awayyy | ML | 1ms | 3620kb | C++20 | 2.5kb | 2024-11-13 22:25:15 | 2024-11-13 22:25:20 |
Judging History
answer
#include<bits/stdc++.h>
#define int long long
using namespace std;
using ll = long long;
using ld = double;
const ll mod = 1e9 + 7;
const ll inf = 1e18 + 5;
const int N = 1e6 + 5;
vector<vector<int> >ed; //存边
vector<int>siz,mxsiz,qans,vis; //siz存每个以x为根的子树大小,mxsiz存每个x的儿子的最大子树
void init(int n){ //qans存重心
siz=mxsiz=vector<int>(n+5);
qans.clear();
}
void dfs(int x,int fa,int n){
siz[x]=1;
mxsiz[x]=0;
for(auto son:ed[x]){
if(son==fa||vis[son])continue;
dfs(son,x,n);
siz[x]+=siz[son];
mxsiz[x]=max(mxsiz[x],siz[son]);
}
mxsiz[x]=max(mxsiz[x],n-siz[x]);
if(mxsiz[x]<=n/2){
qans.push_back(x);
}
}
void solve(){
int n;
cin>>n;
ed=vector<vector<int> >(n+5);
vis=vector<int>(n+5);
for(int i=1;i<=n;i++){
int a,b;
cin>>a>>b;
if(a){
ed[i].push_back(a);
ed[a].push_back(i);
}
if(b){
ed[i].push_back(b);
ed[b].push_back(i);
}
}
int n1=n,now=1;
while(n1>2){
init(n);
dfs(now,0,n1);
int mx=0,pos=0,pos1=0;
now=qans[0];
init(n);
dfs(now,0,n1);
for(auto son:ed[now]){
if(mx<siz[son]){
mx=siz[son];
pos=son;
}
}
for(auto son:ed[now]){
if(pos!=son){
pos1=son;
break;
}
}
cout<<"? "<<pos<<' '<<pos1<<endl;
int op;
cin>>op;
if(op==0){
vis[now]=1;
now=pos;
n1=siz[pos];
}else if(op==1){
vis[pos]=vis[pos1]=1;
n1=n1-siz[pos]-siz[pos1];
}else{
vis[now]=1;
now=pos1;
n1=siz[pos1];
}
}
if(n1==2){
int pos=0;
for(auto son:ed[now]){
if(!vis[son]){
pos=son;
break;
}
}
cout<<"? "<<pos<<' '<<now<<endl;
int op;
cin>>op;
if(op==0){
cout<<"! "<<pos<<endl;
}else{
cout<<"! "<<now<<endl;
}
}else{
cout<<"! "<<now<<endl;
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
// cout<<fixed<<setprecision(6);
// srand(time(0));
int T = 1;
cin >> T;
while (T--)solve();
return 0;
}
詳細信息
Test #1:
score: 100
Accepted
time: 1ms
memory: 3620kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 0 2 0 2 0 0 2
output:
? 3 1 ? 5 2 ! 5 ? 2 1 ! 1
result:
ok OK (2 test cases)
Test #2:
score: -100
Memory Limit Exceeded
input:
5555 8 2 0 8 6 0 0 3 0 0 0 7 0 0 0 5 4 0 0 2 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 0 1 0 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0 0 0 2 5 4 5 3 1 0 0 0 0 0 0 0 2 8 0 0 0 0 5 6 0 0 1 4 2 0 3 8 0 0 0 1 0 5 3 0 5 1 0 0 0 0 4 0 0 0 5 5 0 0 0 0 0 3 0 2 4 1 0 3 3 0 1 0 0 0 2 2 2 0 0 0 2 3 2 3 0 0 0 0 2 10 2 8 9 7 0 ...
output:
? 2 5 ? 2 7 ? 1 2 ! 2 ? 3 5 ? 1 4 ? 3 2 ! 3 ? 1 6 ? 1 7 ? 5 1 ! 1 ? 2 4 ? 3 2 ! 2 ? 5 6 ? 1 3 ? 4 5 ! 4 ? 5 1 ? 4 5 ! 4 ? 4 1 ? 2 5 ! 2 ? 3 2 ! 2 ? 2 1 ! 1 ? 2 3 ! 3 ? 2 6 ? 1 9 ? 10 9 ! 9 ? 2 1 ! 1 ? 5 9 ? 4 8 ? 5 3 ! 5 ? 5 8 ? 7 1 ? 9 7 ! 7 ? 9 3 ? 1 7 ? 9 2 ! 9 ? 2 1 ! 2 ? 4 3 ? 1 5 ? 7 4