Samkit5025

Untitled

Aug 15th, 2022
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const long long int mod = 1000000007;
  5. vector<vector<long long int>> g(100005);
  6.  
  7. // bin_expo(int a, int b) calculates a*a*a*a ......... *a (b times)
  8. long long int bin_expo(int a,int b){
  9.     if(b==0)return 1;
  10.     long long int res = bin_expo(a,b/2);
  11.     if(b%2){
  12.         return (((res*res)%mod)*a)%mod;
  13.     }  
  14.     else{
  15.         return (res*res)%mod;
  16.     }
  17. }
  18.  
  19. void dfs(int src,vector<bool> &visited,int *count){
  20.     (*count)++;
  21.     visited[src] = true;
  22.  
  23.     for(auto i : g[src]){
  24.         if(!visited[i]){
  25.             dfs(i,visited,count);
  26.         }
  27.     }
  28. }
  29.  
  30. int totalMagicalSequence(int N, int X, vector<vector<int>> &edge){
  31.     long long int tot = bin_expo(N, X);
  32.  
  33.     for(int i=0;i<N-1;i++){
  34.         if(edge[i][2]==0){
  35.             g[edge[i][0]].push_back(edge[i][1]);
  36.             g[edge[i][1]].push_back(edge[i][0]);
  37.         }
  38.     }
  39.  
  40.     vector<bool> visited(N+1,false);
  41.  
  42.     for(int i=1;i<=N;i++){
  43.         if(!visited[i]){
  44.             int count =0;
  45.             dfs(i,visited,&count);
  46.             tot = (tot - bin_expo(count,X) + mod) %mod;
  47.         }
  48.     }
  49.     return tot;
  50. }
  51.  
  52. signed main() {
  53.     int N,X;
  54.     cin>>N>>X;
  55.  
  56.     vector<vector<int>> edge(N-1);
  57.     for(int i=0;i<N-1;i++){
  58.         for(int j=0;j<3;j++){
  59.             int x;
  60.             cin>>x;
  61.             edge[i].push_back(x);
  62.         }
  63.     }
  64.  
  65.     cout<<totalMagicalSequence(N,X,edge)<<endl;
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment