# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
200378 | arnold518 | Designated Cities (JOI19_designated_cities) | C++14 | 1020 ms | 62692 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int MAXN = 2e5;
int N, Q, lf;
map<int, int> adj[MAXN+10];
set<int> leaf[MAXN+10];
int pos[MAXN+10];
ll dist[MAXN+10], ans[MAXN+10];
void dfs(int now, int bef)
{
for(auto nxt : adj[now])
{
if(nxt.first==bef) continue;
ans[1]+=nxt.second;
dfs(nxt.first, now);
}
}
void dfs2(int now, int bef, ll val)
{
ans[1]=min(ans[1], val);
for(auto nxt : adj[now])
{
if(nxt.first==bef) continue;
dfs2(nxt.first, now, val-adj[now][nxt.first]+adj[nxt.first][now]);
}
}
pll propa(int u)
{
int now=u, nxt; ll ret=0;
while(adj[now].size()==1 && leaf[now].size()==0)
{
nxt=adj[now].begin()->first;
ret+=adj[nxt][now];
adj[now].erase(nxt); adj[nxt].erase(now);
now=nxt;
}
return {now, ret};
}
int main()
{
int i, j;
scanf("%d", &N);
for(i=1; i<N; i++)
{
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
adj[a][b]=c;
adj[b][a]=d;
}
dfs2(1, 1, 0);
dfs(1, 1);
set<pll> PQ;
vector<int> V;
for(i=1; i<=N; i++) if(adj[i].size()==1) V.push_back(i);
for(auto i : V)
{
pll t=propa(i);
leaf[t.first].insert(i);
dist[i]=t.second;
pos[i]=t.first;
PQ.insert({dist[i], i});
//printf("%d %lld\n", i, dist[i]);
lf++;
}
ll cost=0;
for(i=lf-1; i>=2; i--)
{
pll now=*PQ.begin(); PQ.erase(PQ.begin());
cost+=now.first;
//printf("!%lld %lld\n", now.first, now.second);
assert(adj[now.second].size()==0);
leaf[pos[now.second]].erase(now.second);
if(leaf[pos[now.second]].size()==1)
{
int u=*leaf[pos[now.second]].begin();
leaf[pos[now.second]].erase(leaf[pos[now.second]].begin());
PQ.erase({dist[u], u});
pll t=propa(pos[now.second]);
leaf[t.first].insert(u);
dist[u]+=t.second;
pos[u]=t.first;
PQ.insert({dist[u], u});
}
ans[i]=cost;
}
scanf("%d", &Q);
while(Q--)
{
int p;
scanf("%d", &p);
printf("%lld\n", ans[p]);
}
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |