QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#883735 | #9570. Binary Tree | xueman | RE | 0ms | 0kb | C++26 | 2.9kb | 2025-02-05 18:33:08 | 2025-02-05 18:33:16 |
Judging History
answer
#include <bits/stdc++.h>
using namespace std;
// #define endl '\n'
#define ll long long
const int N = 5e5 + 10;
const int maxn = 1e5 + 10;
const int inf = 0x3f3f3f3f;
struct edge
{
int to, ne;
} e[N];
int head[maxn], ecnt = 1;
void add(int x, int y)
{
e[++ecnt].to = y;
e[ecnt].ne = head[x];
head[x] = ecnt;
}
int n, sum;
int sz[maxn];
int ans, pos;
void dfs1(int x, int fa, int d)
{
sz[x] = 1;
int res = 0;
for (int i = head[x]; i; i = e[i].ne)
{
int y = e[i].to;
if (y == fa || y == d)
continue;
dfs1(y, x, d);
sz[y] += sz[x];
res = max(res, n - sz[x]);
// cout << res << ' ';
if (res < ans || (ans == res && x < pos))
ans = res, pos = x;
}
}
void dfs2(int x, int fa, int d)
{
sz[x] = 1;
for (int i = head[x]; i; i = e[i].ne)
{
int y = e[i].to;
if (y == fa || y == d)
continue;
dfs2(y, x, d);
sz[x] += sz[y];
}
}
int ask(int x, int y)
{
cout << "? " << x << ' ' << y << endl;
int tmp;
cin >> tmp;
return tmp;
}
void solve(int now, int d)
{
ans = inf, pos = 0;
dfs1(now, 0, d);
// cout << '(' << pos << ')' << endl;
dfs2(pos, 0, d);
vector<pair<int, int>> v;
for (int i = head[pos]; i; i = e[i].ne)
{
int y = e[i].to;
if (y == d)
continue;
v.push_back({sz[y], y});
}
sort(v.begin(), v.end());
if (v.size() == 3)
{
int op = ask(v[0].second, v[1].second);
if (op == 0)
solve(v[0].second, pos);
else if (op == 1)
solve(v[3].second, pos);
else
solve(v[2].second, pos);
}
else if (v.size() == 2)
{
int op = ask(v[0].second, v[1].second);
if (op == 0)
solve(v[0].second, pos);
else if (op == 1)
{
sum = pos;
return;
}
else
solve(v[1].second, pos);
}
else
{
int op = ask(pos, v[0].second);
if (op == 0)
{
sum = pos;
return;
}
else
{
sum = v[0].second;
return;
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--)
{
cin >> n;
for (int i = 0; i <= n; i++)
head[i] = 0;
ecnt = 1;
for (int i = 1; i <= n; i++)
{
int x, y;
cin >> x >> y;
if (x)
add(x, i), add(i, x);
if (y)
add(y, i), add(i, y);
}
if (n == 1)
{
cout << "! 1" << endl;
continue;
}
sum = 0;
solve(1, 0);
cout << "! " << sum << endl;
}
}
详细
Test #1:
score: 0
Runtime Error
input:
2 5 0 0 1 5 2 4 0 0 0 0 2
output:
? 1 2 ! 2