尽管 卡了我一早上,我一点都不气….
这数据是真的强.
观察题目发现实际上偶数链是没有任何用的.
然后这种树上路径一般考虑用点分治。
那么记录从一个点跑出去的奇/偶链数量与和,
然后令所有 奇链 偶链 互相链接,然后就得到了从该点延出去的所有边,
但是要注意一开始要把这个点排除最后单独算.
注意边界问题..炸了ll调了一早上
c++代码如下:
#include<bits/stdc++.h>
#define rep(i,x,y) for(register int i = x;i <= y;++i)
#define repd(i,x,y) for(register int i = )
using namespace std;
typedef long long ll;
template<typename T>inline void read(T&x)
{
x = 0;char c;int sign = 1;
do { c = getchar(); if(c == '-') sign = -1; }while(!isdigit(c));
do { x = x * 10 + c - '0'; c = getchar(); }while(isdigit(c));
x *= sign;
}
const int N = 2e5+50,p = 1e9+7;
int head[N],nxt[N << 1],to[N << 1],tot;
int n,m;ll val[N];
inline void add(int x,int y)
{
nxt[tot] = head[x];
to[tot] = y;
head[x] = tot++;
}
int rt,nsum,mx[N],size[N];
bool vis[N];
void get_rt(int x,int fa)
{
size[x] = mx[x] = 1;
for(register int i = head[x];~i;i=nxt[i])
if(!vis[to[i]] && to[i] != fa)
{
get_rt(to[i],x);
size[x] += size[to[i]];
mx[x] = max(mx[x],size[to[i]]);
}
mx[x] = max(mx[x],nsum - size[x]);
if(mx[rt] > mx[x]) rt = x;
}
ll d[2],num[2];
void dfs(int x,int fa,int n,ll w)
{
d[n] += w;d[n] %= p;++ num[n];
for(register int i = head[x];~i;i=nxt[i])
if(!vis[to[i]] && to[i] != fa)
{
dfs(to[i],x,n^1,val[to[i]] * (n ? 1:-1) + w);
}
}
ll calc1(int x)
{
d[0] = d[1] = 0;
num[0] = num[1] = 0;
dfs(x,x,0,0); d[1] = -d[1];
return (d[0] * num[0] * 2 + d[1] * num[1] * 2 +
val[x] * (( num[0] * num[0] - num[1] * num[1])%p)%p)%p;
}
ll calc2(int x,ll w)
{
d[0] = d[1] = 0;
num[0] = num[1] = 0;
dfs(x,x,1,-val[x]); d[1] = -d[1];
return (d[0] * num[0] * 2 + d[1] * num[1] * 2 +
w * ((num[0] * num[0] - num[1] * num[1])%p)%p)%p;
}
ll ans;
void solve(int x)
{
vis[x] = 1;
ans = (ans + calc1(x)) % p;
for(register int i = head[x];~i;i = nxt[i])
if(!vis[to[i]])
{
ans = (ans - calc2(to[i],val[x])) % p;
rt = 0;nsum = size[to[i]];
get_rt(to[i],to[i]);
solve(rt);
}
}
int main()
{
memset(head,-1,sizeof head);
read(n);
rep(i,1,n) read(val[i]);
rep(i,2,n)
{
int u,v;
read(u); read(v);
add(u,v); add(v,u);
}
mx[0] = N;
nsum = n;
get_rt(1,1);
solve(rt);
cout << (ans + p) % p << endl;
return 0;
}