from collections import deque class UnionFind: def __init__(self, N): self.tree_size = N self.parent = [i for i in range(N)] self.rank = [1 for _ in range(N)] def root(self, a): now = a while now != self.parent[now]: now = self.parent[now] return now def same(self, a, b): return self.root(a) == self.root(b) def merge(self, a, b): rta = self.root(a) rtb = self.root(b) if rta != rtb: if self.rank[rta] == self.rank[rtb]: self.parent[rtb] = self.parent[rta] self.rank[rta] += 1 elif self.rank[rta] > self.rank[rtb]: self.parent[rtb] = self.parent[rta] else: self.parent[rta] = self.parent[rtb] mod = 998244353 N, K = map(int, input().split()) graph = [[] for _ in range(N)] tree = UnionFind(N) dist = [N + 2 for _ in range(N)] cnt = 0 dq = deque() for i in range(N): u, v = map(int, input().split()) u -= 1 v -= 1 if tree.same(u, v): dist[u] = 0 dq.append(u) while len(dq) > 0: p = dq.popleft() for x in graph[p]: if dist[x] < N: continue dist[x] = dist[p] + 1 dq.append(x) cnt = dist[v] + 1 break else: graph[u].append(v) graph[v].append(u) tree.merge(u, v) dp = [[0, 0] for _ in range(N)] dp[0][0] = K for i in range(1, N): dp[i][0] = dp[i - 1][1] dp[i][1] = (dp[i - 1][0] * (K - 1) + dp[i - 1][1] * (K - 2)) % mod ans = dp[cnt - 1][1] for i in range(N - cnt): ans = (ans * (K - 1)) % mod print(ans)