题目:
Description:
You are given a tree (a connected undirected graph without cycles) of nn vertices. Each of the n−1n−1 edges of the tree is colored in either black or red.
You are also given an integer kk. Consider sequences of kk vertices. Let's call a sequence [a1,a2,…,ak][a1,a2,…,ak] good if it satisfies the following criterion:
- We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a1a1 and ending at akak.
- Start at a1a1, then go to a2a2 using the shortest path between a1a1 and a2a2, then go to a3a3 in a similar way, and so on, until you travel the shortest path between ak−1ak−1 and akak.
- If you walked over at least one black edge during this process, then the sequence is good.
Consider the tree on the picture. If k=3k=3 then the following sequences are good: [1,4,7][1,4,7], [5,5,3][5,5,3] and [2,3,7][2,3,7]. The following sequences are not good: [1,4,6][1,4,6], [5,5,5][5,5,5], [3,7,3][3,7,3].
There are nknk sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 109+7109+7.
Input
The first line contains two integers nn and kk (2≤n≤1052≤n≤105, 2≤k≤1002≤k≤100), the size of the tree and the length of the vertex sequence.
Each of the next n−1n−1 lines contains three integers uiui, vivi and xixi (1≤ui,vi≤n1≤ui,vi≤n, xi∈{0,1}xi∈{0,1}), where uiui and vivi denote the endpoints of the corresponding edge and xixi is the color of this edge (00 denotes red edge and 11 denotes black edge).
Output
Print the number of good sequences modulo 109+7109+7.
Examples
input
4 4 1 2 1 2 3 1 3 4 1
output
252
input
4 6 1 2 0 1 3 0 1 4 0
output
0
input
3 5 1 2 1 2 3 0
output
210
Note
In the first example, all sequences (4444) of length 44 except the following are good:
- [1,1,1,1][1,1,1,1]
- [2,2,2,2][2,2,2,2]
- [3,3,3,3][3,3,3,3]
- [4,4,4,4][4,4,4,4]
In the second example, all edges are red, hence there aren't any good sequences.
题意分析:
是个联通块的题目,红色边的联通块内任意两点之间相互到达,但是却无法形成好的回路,用总答案数减掉就好了,做这道题最开始的时候想到是求任意两个联通块到达形成好的回路的,但是无法去重,语文水平有限,具体看代码吧,代码写的还是挺容易懂的
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#define LL long long
#define N 200005
#define MOD 1000000007
using namespace std;
LL n,k,ans,x,y,z,u,v;
LL f[N],num[N];
bool vis[N];
LL ksm(LL a,LL b)
{
LL ans=1;
while(b)
{
if(b&1)
{
ans=(ans*a)%MOD;
}
b/=2;
a=(a*a)%MOD;
}
return ans;
}
LL find(LL x)
{
if(x!=f[x])f[x]=find(f[x]);
return f[x];
}
int main()
{
memset(vis,0,sizeof(vis));
scanf("%lld%lld",&n,&k);
ans=ksm(n,k)%MOD;
for(int i=1;i<=n;i++)
{
f[i]=i;
num[i]=1;
}
for(int i=1;i<n;i++)
{
scanf("%lld%lld%lld",&x,&y,&z);
if(z==0)
{
u=find(x);
v=find(y);
if(u!=v)
{
f[v]=u;
// num[u]++;//找了好久发现bug在这里,就是我当前的v点已经有一个联通快里面有很多个点了,如果只是++,那么就会少算了点
num[u]+=num[v];
}
}
}
for(int i=1;i<=n;i++)
{
z=find(i);
if(!vis[z])
{
ans=(ans-ksm(num[z],k)+MOD)%MOD;//注意这里要+MOD
vis[z]=1;
}
}
printf("%lld",ans);
return 0;
}