QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#480806#9110. Zayin and Treebad_solver#AC ✓456ms24040kbC++231.9kb2024-07-16 18:59:162024-07-16 18:59:17

Judging History

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

  • [2024-07-16 18:59:17]
  • 评测
  • 测评结果:AC
  • 用时:456ms
  • 内存:24040kb
  • [2024-07-16 18:59:16]
  • 提交

answer

#include <bits/stdc++.h>
#define pb push_back
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define f first
#define s second
using namespace std;
using ll = long long;
using pii = pair <int, int>;
const int N = 1e6 + 5, inf = 1e9;
int n, a[N], sz[N], ans;
bool used[N];
vector <int> g[N];
void calc(int v, int p = 0) {
    sz[v] = 1;
    for (auto to : g[v]) {
        if (!used[to] && to != p)
            calc(to, v), sz[v] += sz[to];
    }
}
int center(int v, int nsz, int p = 0) {
    for (auto to : g[v]) {
        if (!used[to] && to != p && sz[to] > nsz / 2)
            return center(to, nsz, v);
    }
    return v;
}
int dist[N], mx[N], mn[N];
vector <int> nodes;
void go(int v, int p = 0) {
    nodes.pb(v);
    ans = min(ans, dist[v] + 1 - mx[v] + mn[v]);
    for (auto to : g[v]) {
        if (!used[to] && to != p) {
            dist[to] = dist[v] + 1;
            mx[to] = max(mx[v], a[to]);
            mn[to] = min(mn[v], a[to]);
            go(to, v);
        }
    }
}
void dfs(int v) {
    calc(v);
    v = center(v, sz[v]);
    used[v] = 1;
    dist[v] = 0;
    mx[v] = mn[v] = a[v];
    go(v);
    sort(all(nodes), [&] (int x, int y) {
        return mx[x] < mx[y];
    });
    int mnn = inf;
    for (auto u : nodes) {
        ans = min(ans, mnn + dist[u] - mx[u]);
        mnn = min(mnn, dist[u] + mn[u] + 1);
    }
    nodes.clear();
    for (auto to : g[v]) {
        if (!used[to]) 
            dfs(to);
    }
}
void solve() {
    cin >> n;
    ans = inf;
    for (int i = 1; i <= n; ++i) {
        g[i].clear();
        used[i] = 0;
        cin >> a[i];
    }
    for (int i = 1, u, v; i < n; ++i) {
        cin >> u >> v;
        g[u].pb(v);
        g[v].pb(u);
    }
    dfs(1);
    cout << ans << '\n';
}
int main() {
    ios :: sync_with_stdio(false);
    cin.tie(nullptr);
    int T;
    cin >> T;
    while (T--)
        solve();
    return 0;
}

详细

Test #1:

score: 100
Accepted
time: 456ms
memory: 24040kb

input:

3009
5
4 5 3 4 2
1 2
2 3
3 4
3 5
5
4 4 1 1 2
1 2
2 3
3 4
3 5
10
5 8 1 0 8 7 5 2 0 4
2 4
3 8
3 9
1 2
1 3
3 6
4 5
5 7
6 10
10
6 8 8 4 8 0 6 6 0 2
7 10
1 7
2 9
2 3
3 4
1 5
1 6
6 8
1 2
10
9 0 4 0 4 6 0 2 0 0
1 5
1 3
1 7
2 6
1 2
1 9
1 4
5 8
7 10
10
8 8 1 2 7 4 8 6 0 8
1 6
1 7
1 5
7 9
1 3
1 2
2 10
3 4
1 8...

output:

0
-1
-6
-6
-7
-6
-7
-4
-3
-7
-5
-6
-5
-4
-6
-3
-4
-7
-4
-4
-6
-6
-6
-5
-4
-5
-6
-6
-7
-7
-5
-7
-6
-6
-7
-6
-5
-5
-4
-6
-6
-5
-6
-6
-6
-6
-3
-6
-3
-6
-4
-6
-7
-6
-7
-6
-6
-5
-7
-6
-4
-7
-3
-5
-5
-6
-4
-5
-7
-6
-5
-5
-4
-3
-5
-3
-4
-2
-6
-5
-7
-4
-5
-5
-7
-7
-4
-6
-5
-4
-6
-5
-5
-6
-3
-6
-7
-7
-7
-6
-...

result:

ok 3009 lines