Submission #781865

#TimeUsernameProblemLanguageResultExecution timeMemory
781865AndreyCat Exercise (JOI23_ho_t4)C++14
100 / 100
294 ms65136 KiB
#include <bits/stdc++.h> using namespace std; vector<long long> h(200001); vector<long long> haha[200001]; vector<long long> dsu(200001); vector<long long> dep(200001); long long bruh[200001][19]; void dfs(long long a, long long t, long long d) { bruh[a][0] = t; dep[a] = d; for(long long v: haha[a]) { if(v != t) { dfs(v,a,d+1); } } } long long check(long long a) { long long c = a,d,e; while(dsu[c] != c) { c = dsu[c]; } d = a; while(d != dsu[d]) { e = dsu[d]; dsu[d] = c; d = e; } return c; } long long dist(long long a, long long b) { if(dep[a] < dep[b]) { swap(a,b); } long long c = dep[a]-dep[b],e = a,d = b; for(long long i = 0; i < 19; i++) { if((1 << i)&c) { e = bruh[e][i]; } } if(b != e) { for(long long i = 18; i >= 0; i--) { if(bruh[e][i] != -1 && bruh[e][i] != bruh[b][i]) { e = bruh[e][i]; b = bruh[b][i]; } } e = bruh[e][0]; } return dep[a]-dep[e]+dep[d]-dep[e]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); for(long long i = 1; i <= 200000; i++) { dsu[i] = i; } long long n,a,b,y = 0; cin >> n; for(long long i = 1; i <= n; i++) { cin >> h[i]; } vector<pair<long long,pair<long long,long long>>> edge(0); for(long long i = 0; i < n-1; i++) { cin >> a >> b; haha[a].push_back(b); haha[b].push_back(a); edge.push_back({max(h[a],h[b]),{a,b}}); } sort(edge.begin(),edge.end()); dfs(1,-1,0); for(long long i = 1; i < 19; i++) { for(long long j = 1; j <= n; j++) { if(bruh[j][i-1] != -1) { bruh[j][i] = bruh[bruh[j][i-1]][i-1]; } else { bruh[j][i] = -1; } } } vector<long long> ans(n+1); for(long long i = 1; i <= n; i++) { while(y < n-1 && edge[y].first == i) { a = edge[y].second.first; b = edge[y].second.second; if(h[a] < h[b]) { swap(a,b); } b = check(b); dsu[b] = a; ans[a] = max(ans[a],dist(a,b)+ans[b]); y++; } } for(long long i = 1; i <= n; i++) { if(h[i] == n) { cout << ans[i]; } } return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...