Codeforces Round #548 (Div. 2)C. Edgy Trees(dfs,思维)

题解:总的全排列减去不符合的全排列,不符合的就是从一个点到另一个点的路径全部为红边(0),具体看代码,挺水的一个题。

以下为代码 

#include 
using namespace std;
#define int long long
const int maxn=1e5+5;
const int mod=1e9+7;
vectorve[maxn];
bool v[maxn];
int n,k;

int num=0;
void dfs(int x){
    v[x]=1;
    num++;
    for(int y:ve[x]){
        if(!v[y])dfs(y);
    }
}
signed main(){
    ios::sync_with_stdio(0); cin.tie(0);//for  ok
    cin>>n>>k;
    for(int i=0;i>a>>b>>c;
        if(!c)ve[a].push_back(b),ve[b].push_back(a);
    }
    int ans=1;
    for(int i=1;i<=k;i++)ans=ans*n%mod;

    for(int i=1;i<=n;i++){
        if(!v[i]){
            num=0;
            dfs(i);
            int res=1;
            for(int i=1;i<=k;i++)res=res*num%mod;
            ans=(ans-res+mod)%mod;
        }
    }
    cout<

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.

你可能感兴趣的:(Codeforces)