# [CF915F] Imbalance Value of a Tree

## Code

#include<bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = (a), i##_end_ = (b); i <= i##_end_; ++i)
#define drep(i, a, b) for(int i = (a), i##_end_ = (b); i >= i##_end_; --i)
#define clar(a, b) memset((a), (b), sizeof(a))
#define debug(...) fprintf(stderr, __VA_ARGS__)
typedef long long LL;
typedef long double LD;
char ch = getchar();
int x = 0, flag = 1;
for (;!isdigit(ch); ch = getchar()) if (ch == '-') flag *= -1;
for (;isdigit(ch); ch = getchar()) x = x * 10 + ch - 48;
return x * flag;
}
void write(int x) {
if (x < 0) putchar('-'), x = -x;
if (x >= 10) write(x / 10);
putchar(x % 10 + 48);
}

const int Maxn = 1e6 + 9;
struct edge {
int to, nxt;
}g[Maxn << 1];
LL ans, a[Maxn], n;
void add(int u, int v) {
}

void init() {
rep (i, 1, n) a[i] = read();
rep (i, 1, n - 1) {
}
}

struct node {
int Id, Val;
int operator < (const node b) const {
return Val < b.Val;
}
}s[Maxn];

int find(int u) { return fa[u] ^ u ? (fa[u] = find(fa[u])) : u; }
int vis[Maxn], size[Maxn];

void solve() {
rep (i, 1, n) {
s[i] = (node){i, a[i]};
fa[i] = i; vis[i] = 0; size[i] = 1;
}

sort(s + 1, s + n + 1);

rep (i, 1, n) {
int u = s[i].Id; vis[u] = 1;

for (int j = head[u]; ~j; j = g[j].nxt) {
int v = g[j].to;
if (vis[v]) {
int l = find(v);
ans += 1ll * size[l] * size[u] * s[i].Val;
size[u] += size[l], fa[l] = u;
}
}
}

rep (i, 1, n) s[i].Val = -s[i].Val;
rep (i, 1, n) fa[i] = i, vis[i] = 0, size[i] = 1;

sort(s + 1, s + n + 1);

rep (i, 1, n) {
int u = s[i].Id; vis[u] = 1;

for (int j = head[u]; ~j; j = g[j].nxt) {
int v = g[j].to;
if (vis[v]) {
int l = find(v);
ans += 1ll * size[l] * size[u] * s[i].Val;
size[u] += size[l], fa[l] = u;
}
}
}
cout << ans << endl;
}

int main() {
freopen("tree.in", "r", stdin);
freopen("tree.out", "w", stdout);

init();
solve();

#ifdef Qrsikno
debug("\nRunning time: %.3lf(s)\n", clock() * 1.0 / CLOCKS_PER_SEC);
#endif
return 0;
}
posted @ 2019-01-27 00:57 Qrsikno 阅读(...) 评论(...) 编辑 收藏