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

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

以下为代码 

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn=1e5+5;
const int mod=1e9+7;
vector<int>ve[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<n-1;i++){
        int a,b,c;cin>>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<<ans<<endl;
    return 0;
}

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.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值