题解:AT_arc142_c [ARC142C] Tree Queries

· · 题解

分析

看到 2n 次查询容易想到分别查询 1, 2 号点到其他点的距离,我们记 a[u], b[u] 分别代表点 u 到 1, 2 的距离。

然后开始分类讨论:

这题核心就是这样上述两种情况,但其实有一个巨坑的细节:

当点数 n 为 4 时,即使对任意点 u \geq 3,|a[u]-b[u]| 为 1,也并不一定意味着答案为 1,请注意特判处理这种情况。

AC 代码:

// Problem: C - Tree Queries
// Contest: AtCoder - AtCoder Regular Contest 142
// URL: https://atcoder.jp/contests/arc142/tasks/arc142_c
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;

#define debug(x) cerr << #x << ": " << (x) << endl
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define dwn(i,a,b) for(int i=(a);i>=(b);i--)
#define pb push_back
#define all(x) (x).begin(), (x).end()

#define x first
#define y second
using pii = pair<int, int>;
using ll = long long;

inline void read(int &x){
    int s=0; x=1;
    char ch=getchar();
    while(ch<'0' || ch>'9') {if(ch=='-')x=-1;ch=getchar();}
    while(ch>='0' && ch<='9') s=(s<<3)+(s<<1)+ch-'0',ch=getchar();
    x*=s;
}

const int N=110;

int a[N], b[N];

int q(int fir, int sec){
    cout<<"? "<<fir<<" "<<sec<<endl;
    int x; cin>>x;
    return x;
}

void o(int x){
    cout<<"! "<<x<<endl;
}

void solve(){
    int n; cin>>n;
    rep(i, 3, n) a[i]=q(1, i);
    rep(i, 3, n) b[i]=q(2, i);
    bool fl=true;
    rep(i, 3, n) if(abs(a[i]-b[i])!=1) fl=false;
    if(fl){
        int res=1;
        if(n==4){
            if(q(3, 4)==1 && a[3]+b[3]==3 && a[4]+b[4]==3) res=3;
        }
        o(res);
    }
    else{
        int res=1e9;
        rep(i, 3, n) res=min(res, a[i]+b[i]);
        o(res);
    }
}

signed main(){
    solve();    
    return 0;
}