QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#759178 | #9570. Binary Tree | Stelor | RE | 0ms | 6236kb | C++17 | 2.8kb | 2024-11-17 22:43:01 | 2024-11-17 22:43:01 |
Judging History
answer
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int mx,tar,root=1;
vector<int> v[N];
int dep[N],pre[N];
bool vis[N];
void dfs(int u,int fa){
pre[u]=fa;
for(auto j:v[u]){
if(j==fa||vis[j]) continue;
dep[j]=dep[u]+1;
if(dep[j]>mx){
mx=dep[j];
tar=j;
}
dfs(j,u);
}
}
bool get_diameter(){
bool ok=false;
for(auto j:v[root]){
if(!vis[j]){
ok=true;
break;
}
}
if(!ok){
cout<<"! "<<root<<endl;
return true;
}
mx=0;
dep[root]=0;
dfs(root,0);
int L=tar;
mx=0;
dep[L]=0;
dfs(L,0);
int R=tar;
if(L==R){
cout<<L<<endl;
return true;
}
cout<<"? "<<L<<" "<<R<<endl;
int op;
cin >> op;
if(op==0){
if(mx<=2){
cout<<"! "<<L<<endl;
return true;
}
int cnt=0;
int tmp=-1;
if(mx&1){
tmp=(mx+1)/2;
}else{
tmp=(mx+2)/2;
}
//assert(tmp!=-1);
for(int i=R;;i=pre[i]){
cnt++;
if(cnt>tmp){
break;
}else{
vis[i]=true;
}
if(i==L){
break;
}
}
root=L;
}else if(op==1){
int cnt=0;
assert(mx%2==0);
for(int i=R;;i=pre[i]){
cnt++;
if(cnt!=mx/2+1){
vis[i]=true;
}else{
root=i;
}
if(i==L) break;
}
}else if(op==2){
if(mx<=2){
cout<<"! "<<R<<endl;
return true;
}
int cnt=0;
int tmp=-1;
if(mx&1){
tmp=(mx+1)/2;
}else{
tmp=mx/2;
}
assert(tmp!=-1);
for(int i=R;;i=pre[i]){
cnt++;
if(cnt>tmp){
vis[i]=true;
}
if(i==L) break;
}
root=R;
}
return false;
}
void solve(){
int n;
cin >> n;
for(int i=1;i<=n;++i){
vis[i]=false;
dep[i]=0;
pre[i]=0;
v[i].clear();
mx=0;
tar=0;
root=1;
}
for(int i=1;i<=n;++i){
int l,r;
cin >> l >> r;
if(l) {
v[i].push_back(l);
v[l].push_back(i);
}
if(r){
v[i].push_back(r);
v[r].push_back(i);
}
}
while(true){
if(get_diameter()) break;
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while(t--){
solve();
}
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 0ms
memory: 6236kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 2 1 2 0 2 0 0 2
output:
? 4 1 ? 5 1 ! 2 ? 2 1 ! 1
result:
ok OK (2 test cases)
Test #2:
score: -100
Runtime Error
input:
5555 8 2 0 8 6 0 0 3 0 0 0 7 0 0 0 5 4 2 0 2 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 2 1 0 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0 2 0 0 5 4 5 3 1 0 0 0 0 0 0 2 0 8 0 0 0 0 5 6 0 0 1 4 2 0 3 8 0 0 2 0 5 3 0 5 1 0 0 0 0 4 0 2 2 5 5 0 0 0 0 0 3 0 2 4 2 2 3 3 0 1 0 0 0 2 2 2 0 0 0 2 3 2 3 0 0 0 0 0 10 2 8 9 7 0 0 ...
output:
? 3 7 ? 1 7 ? 2 1 ! 1 ? 6 1 ? 4 1 ? 3 2 ! 3 ? 4 7 ? 5 7 ? 1 5 ! 1 ? 3 4 ? 5 4 ! 5 ? 2 1 ? 4 1 ! 4 ? 4 3 ? 1 3 ! 3 ? 3 1 ? 2 1 ! 1 ? 3 2 ! 2 ? 2 1 ! 1 ? 2 3 ! 2 ? 4 8 ? 5 4 ? 3 4 ! 6 ? 2 1 ! 2 ? 4 6 ? 1 6 ? 2 6 ! 6 ? 6 9 ? 1 9 ? 5 1 ! 1 ? 6 1 ? 4 6 ? 5 6 ! 5 ? 2 1 ! 2 ? 2 1 ? 7 1 ! 4 ? 3 1 ? 7 1 ? 9 ...