cf915F(神思维)

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

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

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

语文不好请看代码。。。




#include
#include
#include
#include
#include
#include
#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<>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]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


你可能感兴趣的:(其他算法)