이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define int ll
int n,ans;
vector<vector<int>> roads[200005];
int jump[200005][21],dep[200005],one[200005],mul[200005];
int cnt[200005];
void dfs(int x, int p){
for(vector<int> i:roads[x]){
if(i[0]!=p){
jump[i[0]][0] = x;
dep[i[0]] = dep[x]+1;
one[i[0]] = i[1];
mul[i[0]] = i[2];
dfs(i[0],x);
}
}
}
int lca(int a, int b){
if(dep[a]>dep[b]){
swap(a,b);
}
for(int j=20;j>=0;j--){
if(dep[b]-(1<<j)>=dep[a]){
b = jump[b][j];
}
}
if(a==b){
return a;
}
for(int j=20;j>=0;j--){
if(jump[a][j]!=jump[b][j]){
a = jump[a][j];
b = jump[b][j];
}
}
return jump[a][0];
}
void dfs2(int x, int p){
for(vector<int> i:roads[x]){
if(i[0]!=p){
dfs2(i[0],x);
cnt[x] += cnt[i[0]];
}
}
ans += min(one[x]*cnt[x],mul[x]);
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for(int i=1;i<=n-1;i++){
int a,b,c1,c2;
cin >> a >> b >> c1 >> c2;
roads[a].push_back({b,c1,c2});
roads[b].push_back({a,c1,c2});
}
dep[1] = 1;
dfs(1,-1);
for(int j=1;j<=20;j++){
for(int i=1;i<=n;i++){
jump[i][j] = jump[jump[i][j-1]][j-1];
}
}
for(int i=1;i<=n-1;i++){
int x = lca(i,i+1);
cnt[i]++;
cnt[i+1]++;
cnt[x] -= 2;
}
dfs2(1,-1);
cout << ans << "\n";
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |