1. 程式人生 > >Gym-101353H Simple Path(樹型dp)

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;
}