一、题面
二、分析
这题刚开始没读懂题意,后来明白了,原来就是一个数连通块里点数的问题。首先在建图的时候,只考虑红色路径上的点。为什么呢,因为为了不走红色的快,那么我们可以反着想只走红色的路径,这样把所有的可能数再减去只走红色路径的数就是最终的答案了。这里要注意的是,如果连通块里只有一个点,那么就是K个点都是这个点的情况,根据题意是不满足的,也要减去。
三、AC代码
1 #include<bits/stdc++.h> 2 3 using namespace std; 4 5 typedef long long LL; 6 const int MOD = 1e9 + 7; 7 const int MAXN = 1e5 + 15; 8 vector<int> Graph[MAXN]; 9 bool visited[MAXN]; 10 int T, N, K; 11 12 LL Pow(LL a, LL b) 13 { 14 LL ans = 1; 15 while(b) 16 { 17 if(b&1) 18 { 19 ans = ans * a % MOD; 20 } 21 a = a * a % MOD; 22 b >>= 1; 23 } 24 return ans; 25 } 26 27 void DFS(int v) 28 { 29 if(visited[v]) 30 return; 31 visited[v] = 1; 32 T++; 33 for(auto &itr:Graph[v]) 34 { 35 DFS(itr); 36 } 37 } 38 39 40 41 int main() 42 { 43 scanf("%d %d", &N, &K); 44 memset(visited, 0, sizeof(visited)); 45 for(int i = 1; i < N; i++) 46 { 47 int x, y, c; 48 scanf("%d %d %d", &x, &y, &c); 49 if(c == 0) 50 { 51 52 Graph[x].push_back(y); 53 Graph[y].push_back(x); 54 } 55 } 56 LL Ans = 0; 57 for(int i = 1; i <= N; i++) 58 { 59 if(visited[i]) 60 continue; 61 T = 0; 62 DFS(i); 63 Ans = (Ans + Pow(T, K)) % MOD; 64 } 65 Ans = (Pow(N, K) - Ans + MOD) % MOD; 66 printf("%I64d ", Ans); 67 return 0; 68 }