Gym-101353H Simple Path(树型dp)

H. Simple Path

Score: 100

CPU: 1s

Memory: 1024MB

You will be given a weighted rooted tree, where root is node 1. For each subtree of that tree, you will have to compute the summation of lengths of all possible simple paths present in that subtree. Eventually you need to print the summation of those values modulo 1000000007.

Image of the tree in the first sample is given below.

Input Specification:

First line of input will contain an integer T (1 <= T <= 10) denoting the number of test cases. Each test case will begin with an integer N, indicating number of nodes. The following N-1 lines will have three integers each, U (1 <= U <= N), V (1 <= V <= N), W (1 <= W <= 1000000000), which denotes that there is an edge in the tree from node U to node V having W weight.

Input File is large. Use fast I/O methods.

Subtask 1: 1<= N <=1000 (15 points)

Subtask 2: 1<= N <=100000 (85 points)

Output Specification For each test case, print the case number, and then print the answer to the problem modulo 1000000007 in separate lines.

Sample

Input

2

7

1 2 3

1 3 2

2 4 1

2 5 4

3 6 6

3 7 8

6

1 2 3

1 3 2

1 4 4

3 5 7

3 6 1

Output 

Case 1: 212

Case 2: 109

Explanation of the 1​st​ sample:

Summation of lengths of all possible sample paths for each subtree is given below:

1: 174

2: 10

3: 28

4: 0

5: 0

6: 0

7: 0

Explanation of the 2​nd​ sample: Summation of lengths of all possible sample paths for each subtree is given below:

1: 93

2: 0

3: 16

4: 0

5: 0

6: 0

c[i]是每个子树的节点个数  a[i]是i与每个子节点距离之和  sum[i]是i这颗树的价值

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int ,int > P;
#define INF 0x3f3f3f3f
#define pb push_back
#define mp make_pair
#define mem(a) memset(a,0,sizeof(a))
const int Max=200000+10;
const int mod=1000000007;
int t,n;
ll a[Max],c[Max],sum[Max];
struct node {
	int to,dis;
};
vector<node> g[Max];
void dfs(int x,int fa) {
	c[x]=1;
	for(auto &i:g[x]) {
		if(i.to==fa) continue;
		dfs(i.to,x);
		c[x]+=c[i.to];
		a[x]=(a[x]+a[i.to]+c[i.to]*i.dis%mod)%mod;
	}

	for(auto &i:g[x]) {
		if(i.to==fa) continue;
		sum[x]=(sum[x]+(c[x]-c[i.to])*(a[i.to]+c[i.to]*i.dis%mod)+sum[i.to])%mod;
	}
}
int main() {
	scanf("%d",&t);
	int ans=0;
	while(t--) {
		scanf("%d",&n);
		for(int i=1; i<=n; i++)
			g[i].clear();

		int u,v,w;
		for(int i=1; i<n; i++) {
			scanf("%d%d%d",&u,&v,&w);
			g[u].pb(node {v,w});
			g[v].pb(node {u,w});
		}
		mem(a);
		mem(sum);
		dfs(1,0);
		ll temp=0;
		for(int i=1; i<=n; i++)
			temp=(temp%mod+sum[i]%mod)%mod;
		printf("Case %d: %lld\n",++ans,temp);
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值