QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#779363#9570. Binary TreewindStriderML 0ms0kbC++202.3kb2024-11-24 18:39:582024-11-24 18:39:58

Judging History

你现在查看的是最新测评结果

  • [2024-11-24 18:39:58]
  • 评测
  • 测评结果:ML
  • 用时:0ms
  • 内存:0kb
  • [2024-11-24 18:39:58]
  • 提交

answer

#include <bits/stdc++.h>

constexpr int inf = 0x3f3f3f3f;

struct nd
{
    int v, l, r, f, sz;
    nd() : v(0), l(0), r(0), f(0), sz(0) { }
};

void bfs(std::vector<nd>& v, int& rt)
{
    int size = v[rt].sz;
    std::queue<int> q;
    q.emplace(rt);

    std::function<void(int, int)>update = [&](int x, int val) -> void
    {
        v[x].sz -= val;
        while (v[x].f) x = v[x].f, v[x].sz -= val;
    };

    int obj = 0, mn = inf;

    while (q.size())
    {
        int tar = q.front();
        q.pop();

        int mx = std::max({ v[v[tar].l].sz, v[v[tar].r].sz, size - v[v[tar].l].sz - v[v[tar].r].sz });
        if (mx < mn) mn = mx, obj = tar;
        
        if (v[tar].l) q.emplace(v[tar].l);
        if (v[tar].r) q.emplace(v[tar].r);
    }

    if (v[obj].l && v[obj].r)
    {
        std::cout << "? " << v[obj].l << " " << v[obj].r << std::endl;
        int bk;
        std::cin >> bk;
        if (bk == 0) v[obj].l = 0, v[obj].r = 0, update(obj, v[obj].sz);
        else if (bk == -1) rt = v[obj].l, v[rt].f = 0;
        else rt = v[obj].r, v[rt].f = 0;
    }
    else if (v[obj].l)
    {
        std::cout << "? " << obj << " " << v[obj].l << std::endl;
        int bk;
        std::cin >> bk;
        if (bk == -1) v[obj].l = 0, update(obj, v[obj].sz);
        else rt = v[obj].l, v[rt].f = 0;
    }
    else if (v[obj].r)
    {
        std::cout << "? " << obj << " " << v[obj].r << std::endl;
        int bk;
        std::cin >> bk;
        if (bk == -1) v[obj].r = 0, update(obj, v[obj].sz);
        else rt = v[obj].r, v[rt].f = 0;
    }    
}

void solve()
{
    int n;
    std::cin >> n;
    std::vector<nd> v(n + 1);
    for (int i = 1; i <= n; ++i)
    {
        int l, r;
        std::cin >> l >> r;
        v[i].v = i, v[i].l = l, v[i].r = r;
        v[l].f = i, v[r].f = i;
    }
    int rt = 1;
    while (v[rt].f != 0) rt = v[rt].f;

    std::function<int(int)>dfs = [&](int t) -> int
    {
        int v1 = 0, v2 = 0;
        if (v[t].l) v1 = dfs(v[t].l);
        if (v[t].r) v2 = dfs(v[t].r);
        v[t].sz += v1 + v2;
        return v[t].sz + 1;
    };
    dfs(rt);

    while (v[rt].sz) bfs(v, rt);

    std::cout << "! " << rt << std::endl;
}

int main()
{
    int t;
    std::cin >> t;
    while (t--)
    {
        solve();
    }
}

詳細信息

Test #1:

score: 0
Memory Limit Exceeded

input:

2
5
0 0
1 5
2 4
0 0
0 0
0

output:

? 2 4
! 3

result: