Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const long long int mod = 1000000007;
- vector<vector<long long int>> g(100005);
- // bin_expo(int a, int b) calculates a*a*a*a ......... *a (b times)
- long long int bin_expo(int a,int b){
- if(b==0)return 1;
- long long int res = bin_expo(a,b/2);
- if(b%2){
- return (((res*res)%mod)*a)%mod;
- }
- else{
- return (res*res)%mod;
- }
- }
- void dfs(int src,vector<bool> &visited,int *count){
- (*count)++;
- visited[src] = true;
- for(auto i : g[src]){
- if(!visited[i]){
- dfs(i,visited,count);
- }
- }
- }
- int totalMagicalSequence(int N, int X, vector<vector<int>> &edge){
- long long int tot = bin_expo(N, X);
- for(int i=0;i<N-1;i++){
- if(edge[i][2]==0){
- g[edge[i][0]].push_back(edge[i][1]);
- g[edge[i][1]].push_back(edge[i][0]);
- }
- }
- vector<bool> visited(N+1,false);
- for(int i=1;i<=N;i++){
- if(!visited[i]){
- int count =0;
- dfs(i,visited,&count);
- tot = (tot - bin_expo(count,X) + mod) %mod;
- }
- }
- return tot;
- }
- signed main() {
- int N,X;
- cin>>N>>X;
- vector<vector<int>> edge(N-1);
- for(int i=0;i<N-1;i++){
- for(int j=0;j<3;j++){
- int x;
- cin>>x;
- edge[i].push_back(x);
- }
- }
- cout<<totalMagicalSequence(N,X,edge)<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment