이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef pair<int, int> pi;
#define debug(x) cerr << #x << ": " << x << endl;
#define debug2(x, y) debug(x) debug(y);
#define repn(i, a, b) for(int i = (int)(a); i < (int)(b); i++)
#define rep(i, a) for(int i = 0; i < (int)(a); i++)
#define all(v) v.begin(), v.end()
#define mp make_pair
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define fi first
#define se second
#define sq(x) ((x) * (x))
template<class T> T gcd(T a, T b){ return ((b == 0) ? a : gcd(b, a % b)); }
int vis1[200005]; //don't forget to initialize to zeroes
vi ord; //don't forget to reverse in the end
vi g[200005];
void dfs0(int cur){
vis1[cur] = 1;
for(int x : g[cur]) if(!vis1[x]) dfs0(x);
ord.pb(cur);
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
//freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
int n;
cin >> n;
map<pi, pi> m;
rep(i, n - 1){
int a, b, c, d;
cin >> a >> b >> c >> d;
a--, b--;
g[a].pb(b);
g[b].pb(a);
m[mp(a, b)] = mp(c, d);
m[mp(b, a)] = mp(c, d);
}
memset(vis1, 0, sizeof(vis1));
rep(i, n) if(!vis1[i]) dfs0(i);
reverse(all(ord));
vi pos(n, 0);
rep(i, n) pos[ord[i]] = i;
vi cnt(n + 5, 0);
repn(i, 1, n){
//we go from 0 -> 1, 1 -> 2, 2 -> 3
if(pos[i - 1] < pos[i]) cnt[pos[i - 1] + 1]++, cnt[pos[i] + 1]--;
else cnt[pos[i] + 1]++, cnt[pos[i - 1] + 1]--;
}
partial_sum(all(cnt), cnt.begin());
ll ans = 0;
repn(i, 1, n){
pi x = m[mp(ord[i - 1], ord[i])];
ans += min(cnt[i] * x.fi, x.se);
}
cout << ans << endl;
return 0;
}
/*
Things to look out for:
- Integer overflows
- Array bounds
- Special cases
Be careful!
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |