QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#575327 | #9110. Zayin and Tree | leafmaple# | AC ✓ | 447ms | 20416kb | C++20 | 2.4kb | 2024-09-19 12:18:25 | 2024-09-19 12:18:26 |
Judging History
answer
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
using ll = long long;
#define int long long
const int N=1e6+5;
int a[N];
vector<int>g[N];
bool del[N];
int sz[N], mxs[N];
int ans = 1e18;
void solve(int u, int siz){
int root = -1, ms = siz+1;
function<void(int,int)> dfs1 = [&](int u,int fa){//找到重心
sz[u] = 1; mxs[u] = 0;
for(auto v:g[u]) if(v!=fa && !del[v]){
dfs1(v, u);
sz[u] += sz[v];
mxs[u] = max(mxs[u], sz[v]);
}
mxs[u] = max(mxs[u], siz-sz[u]);
if(mxs[u] < ms) ms = mxs[u], root = u;
};
dfs1(u, -1);
int lstmi = 1e16, lstmx = 1e16;
int lstmi2 = 1e16, lstmx2 = 1e16;
for(auto v: g[root]) if(!del[v]){
int nowmi = 1e16, nowmx = 1e16;
int nowmi2 = 1e16, nowmx2 = 1e16;
function<void(int,int,int,int,int)> dfs2 = [&](int u, int fa, int dep, int mi, int mx){
sz[u] = 1;
nowmi = min(nowmi, dep + mi);
nowmi2 = min(nowmi2, dep + 1 + min(mi, a[root]));
nowmx = min(nowmx, dep - mx);
nowmx2 = min(nowmx2, dep + 1 - max(mx, a[root]));
ans = min(ans, dep + 1 - max(mx, a[root]) + min(mi, a[root]));
// ans = min(ans, lstmi + dep + 1 - max(mx, a[root]));
// ans = min(ans, lstmx + dep + 1 + min(mi, a[root]));
for(auto v: g[u]) if(v!=fa && !del[v]){
dfs2(v, u, dep+1, min(mi, a[v]), max(mx, a[v]));
sz[u]+=sz[v];
}
};
dfs2(v, root, 1, a[v], a[v]);
ans = min({ans, lstmi + nowmx2, lstmi2 + nowmx,
lstmx + nowmi2, lstmx2 + nowmi});
lstmi = min(lstmi, nowmi);
lstmi2 = min(lstmi2, nowmi2);
lstmx = min(lstmx, nowmx);
lstmx2 = min(lstmx2, nowmx2);
}
del[root] = 1;
for(auto v: g[root]) if(!del[v]){
solve(v, sz[v]);
}
}
void solve(){
ans = 1e18;
int n; cin >> n;
for(int i=1; i<=n; i++) {
cin >> a[i];
g[i].clear();
del[i] = 0;
}
for(int i=1; i<n; i++){
int u, v; cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
solve(1, n);
ans = min(ans, 1ll);
cout << ans << endl;
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
int T; T=1;
cin >> T;
while(T--) solve();
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 447ms
memory: 20416kb
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