#16. 【NOIP2014】联合权值
统计无向连通图 G 有 n 个点, n−1 条边。点从 1 到 n 依次编号,编号为 i 的点的权值为 Wi ,每条边的长度均为 1 。图上两点 (u,v) 的距离定义为 u 点到 v 点的最短距离。对于图 G 上的点对 (u,v) ,若它们的距离为 2 ,则它们之间会产生 Wv×Wu 的联合权值。
请问图 G 上所有可产生联合权值的有序点对中,联合权值最大的是多少?所有联合权值之和是多少?
输入格式
第一行包含 1 个整数 n。
接下来 n−1 行,每行包含 2 个用空格隔开的正整数 u,v ,表示编号为 u 和编号为 v 的点之间有边相连。
最后 1 行,包含 n 个正整数,每两个正整数之间用一个空格隔开,其中第 i 个整数表示图 G 上编号为 i 的点的权值为 Wi 。
输出格式
输出共 1 行,包含 2 个整数,之间用一个空格隔开,依次为图 G 上联合权值的最大值和所有联合权值之和。由于所有联合权值之和可能很大,输出它时要对 10007 取余。
样例一
input
5 1 2 2 3 3 4 4 5 1 5 2 3 10
output
20 74
explanation
距离为 2 的有序点对有 (1,3),(2,4),(3,1),(3,5),(4,2),(5,3) 。其联合权值分别为 2,15,2,20,15,20 。其中最大的是 20 ,总和为 74。
限制与约定
对于30%的数据, 1<n≤100 ;
对于60%的数据, 1<n≤2000 ;
对于100%的数据, 1<n≤200000,0<Wi≤10000 。
保证一定存在可产生联合权值的有序点对。
时间限制: 1s
内存限制: 128MB
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#190948 | #16. 【NOIP2014】联合权值 | Sakura_ | 100 | 90ms | 7408kb | C++ | 1.2kb | 2017-09-12 12:23:56 | 2017-09-12 12:23:57 |
answer
#include <bits/stdc++.h>
using namespace std;
const int N = 200005, mod = 10007;
int n, head[N], top;
inline void read( int &res )
{
char ch = getchar(); res = 0;
while(ch < '0' || ch > '9') ch = getchar();
while(ch >= '0' && ch <= '9') res = res * 10 + ch - 48, ch = getchar();
}
struct Node
{
int y, nxt;
Node() { }
Node( int y, int nxt ) : y(y), nxt(nxt) { }
} e[N << 1];
inline void Adde( int x, int y )
{
e[++top] = Node(y, head[x]), head[x] = top;
e[++top] = Node(x, head[y]), head[y] = top;
}
int sum[N], mx[N], ans, ssm, w[N];
void Dfs( int u, int f )
{
for(int i = head[u]; i; i = e[i].nxt)
{
int v = e[i].y;
if(v == f) continue;
ssm = (ssm + 1LL * sum[u] * w[v] % mod) % mod;
ans = max(ans, w[v] * mx[u]);
sum[u] += w[v];
mx[u] = max(mx[u], w[v]);
Dfs(v, u);
ssm = (ssm + 1LL * w[u] * sum[v] % mod) % mod;
ans = max(ans, mx[v] * w[u]);
}
}
int main()
{
read(n);
for(int i = 1, u, v; i < n; ++i)
read(u), read(v), Adde(u, v);
for(int i = 1; i <= n; ++i) read(w[i]);
Dfs(1, 0);
cout << ans << " " << 1LL * ssm * 2 % mod << endl;
return 0;
}
/*
5
1 2
2 3
3 4
4 5
1 5 2 3 10
5
2 1
2 3
3 4
3 5
3 2 5 3 4
*/