cf915F(神思维)

初看这题还以为可以链剖。。。和bzoj3626非常相似。。往这个方向想了一下发现可行性并不是很好。。因为要统计链上最小数而且如果有一样的最小数就麻烦了。。。

然后看了下cyc的代码。。。只能深深的被其想法折服。。

先找最大值。。按点权从小到大依次加进去,等到相邻的时候就可以统计了。。。

语文不好请看代码。。。




#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<cmath>
#define inc(i,l,r) for(int i=l;i<=r;i++)
#define dec(i,l,r) for(int i=l;i>=r;i--)
#define link(x) for(edge *j=h[x];j;j=j->next)
#define eps 1e-8
#define inf (ll)10000000000
#define mem(a) memset(a,0,sizeof(a))
#define ll long long
#define succ(x) (1<<x)
#define lowbit(x) (x&(-x))
#define sqr(x) ((x)*(x))
#define ls T[i<<1]
#define rs T[i<<1|1]
#define op T[i]
#define mid (x+y>>1)
#define NM 1000005
#define nm 2000005
#define pi 3.141592653
using namespace std;
int read(){
    int x=0,f=1;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
    while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
    return f*x;
}


struct edge{int t;edge*next;}e[nm],*h[NM],*o=e;
void add(int x,int y){o->t=y;o->next=h[x];h[x]=o++;}
int n,_x,_y,f[NM],tmp[NM];
ll ans,a[NM],size[NM];
int find(int x){return f[x]==x?x:f[x]=find(f[x]);}
void solve(){
	mem(f);mem(size);
	inc(i,1,n)tmp[i]=i;
	sort(tmp+1,tmp+1+n,[](int x,int y){return a[x]<a[y];});
	for(int k=1,i=tmp[k];k<=n;i=tmp[++k]){
		f[i]=i;size[i]++;
		link(i)if(f[j->t]){
			int t=find(j->t);
			ans+=size[t]*size[i]*a[i];
			size[i]+=size[t];f[t]=i;
		}
	}
}

int main(){
	n=read();
	inc(i,1,n)a[i]=read();
	inc(i,1,n-1){_x=read();_y=read();add(_x,_y);add(_y,_x);}
	solve();
	inc(i,1,n)a[i]=-a[i];
	solve();
	return 0*printf("%I64d\n",ans);
}



F. Imbalance Value of a Tree
time limit per test
4 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a tree T consisting of n vertices. A number is written on each vertex; the number written on vertex i is ai. Let's denote the function I(x, y) as the difference between maximum and minimum value of ai on a simple path connecting vertices x and y.

Your task is to calculate .

Input

The first line contains one integer number n (1 ≤ n ≤ 106) — the number of vertices in the tree.

The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the numbers written on the vertices.

Then n - 1 lines follow. Each line contains two integers x and y denoting an edge connecting vertex x and vertex y (1 ≤ x, y ≤ n, x ≠ y). It is guaranteed that these edges denote a tree.

Output

Print one number equal to .

Example
Input
4
2 2 3 1
1 2
1 3
1 4
Output
6


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值