跳到正文

题解

题解:AT_arc142_c [ARC142C] Tree Queries

Tenshi约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年12月18日
收录
2026年10月12日
更新
2026年11月10日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

分析

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

然后开始分类讨论:

  • 当 1,21, 2 点相邻的时候:
    可以知道对任意点 u≥3u \geq 3, ∣a[u]−b[u]∣|a[u]-b[u]| 必然为 11。
  • 而当 1,21, 2 点不相邻的时候:
    一定存在至少一个点 u0u_0 在 1,21, 2 号点中间,那答案 resres 就是 a[u0]+b[u0]a[u_0]+b[u_0]。而这个 resres 可以通过求 min⁡ua[u]+b[u]\min_u a[u]+b[u] 简单地得到。

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

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

AC 代码:

C++
// 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;
}
原文