题解 树
艹,我直到发现题解死活读不懂才发现自己题读错了
发现一条 \((u, t), (t, v)\) 的路径可以合并成一条 \((u, v)\) 的路径
所以为了最小化总路径数每个点要么只当起点要么只当终点
然后发现每条边被正反经过的次数抵消后的值的绝对值是容易求的
\[a_u\gets a_u-\sum\limits_{v\in son_u}a_v
\]
令 \(f_u\) 为 \(u\) 为起点次数,若为负数则表示为终点次数
分类讨论 \(u, v\) 大小关系是可以转移的
然后贪心匹配出入点即可
复杂度 \(O(n)\)
点击查看代码
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define N 1000010
#define pb push_back
#define ll long long
//#define int long long
char buf[1<<21], *p1=buf, *p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf, 1, 1<<21, stdin)), p1==p2?EOF:*p1++)
inline int read() {
int ans=0, f=1; char c=getchar();
while (!isdigit(c)) {if (c=='-') f=-f; c=getchar();}
while (isdigit(c)) {ans=(ans<<3)+(ans<<1)+(c^48); c=getchar();}
return ans*f;
}
int n;
vector<int> out, in;
int head[N], a[N], f[N], ecnt, cnt;
struct edge{int to, next;}e[N<<1];
inline void add(int s, int t) {e[++ecnt]={t, head[s]}; head[s]=ecnt;}
void dfs(int u, int fa) {
for (int i=head[u],v; ~i; i=e[i].next) {
v = e[i].to;
if (v==fa) continue;
dfs(v, u);
a[u]-=a[v];
if (u<v) f[v]-=a[v], f[u]+=a[v];
else f[v]+=a[v], f[u]-=a[v];
}
}
signed main()
{
freopen("tree.in", "r", stdin);
freopen("tree.out", "w", stdout);
n=read();
memset(head, -1, sizeof(head));
for (int i=1; i<=n; ++i) a[i]=read();
for (int i=1,u,v; i<n; ++i) {
u=read(); v=read();
add(u, v); add(v, u);
}
dfs(1, 0);
for (int i=1; i<=n; ++i)
if (f[i]<0) in.pb(i);
else out.pb(i), cnt+=f[i];
// cout<<"in : "; for (auto it:in) cout<<it<<' '; cout<<endl;
// cout<<"out: "; for (auto it:out) cout<<it<<' '; cout<<endl;
int pos=0;
printf("%d\n", cnt);
for (auto it:out) {
while (f[it]) {
if (!f[in[pos]]) ++pos;
printf("%d %d\n", it, in[pos]);
--f[it]; ++f[in[pos]];
}
}
return 0;
}