NOIP 2014 联合权值 [DFS]

 统计

无向连通图 G 有 n 个点, n1  条边。点从 1 到  n  依次编号,编号为  i  的点的权值为  Wi ,每条边的长度均为  1 。图上两点  (u,v) 的距离定义为  u  点到  v  点的最短距离。对于图  G 上的点对  (u,v) ,若它们的距离为  2 ,则它们之间会产生 Wv×Wu  的联合权值。

请问图  G  上所有可产生联合权值的有序点对中,联合权值最大的是多少?所有联合权值之和是多少?

输入格式

第一行包含  1 个整数 n

接下来  n1 行,每行包含  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<n100

对于60%的数据, 1<n2000

对于100%的数据, 1<n200000,0<Wi10000

保证一定存在可产生联合权值的有序点对。

时间限制: 1s

内存限制: 128MB


有点水
因为是树, 所以离你距离为二的点只有三种情况 : 
你的兄弟
你的父亲的父亲
你的儿子的儿子
我们自底而上 从左至右 处理 不用考虑两次 最后答案乘2 即可

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
*/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值