#include #include #include #include #include #include #include #include using namespace std; using namespace atcoder; using ll = long long; ll mod = 998244353; int main() { ll N, K; cin >> N >> K; vector u(N); vector v(N); for (ll i = 0; i < N; i++) { cin >> u[i] >> v[i]; u[i]--; v[i]--; } map, ll> mp; for (ll i = 0; i < N; i++) { mp[pair(u[i], v[i])]++; } for (ll i = 0; i < N; i++) { ll val = mp[pair(u[i], v[i])]; assert(val == 1); } vector dist(N, N + 2); queue que; vector> graph(N, vector(0)); dsu tree(N); ll cnt = 0; for (ll i = 0; i < N; i++) { if (!tree.same(u[i], v[i])) { graph[u[i]].push_back(v[i]); graph[v[i]].push_back(u[i]); tree.merge(u[i], v[i]); } else { que.push(u[i]); dist[u[i]] = 0; while (que.size()) { ll p = que.front(); que.pop(); for (ll x : graph[p]) { if (dist[x] < N) { continue; } dist[x] = dist[p] + 1; que.push(x); } } cnt = dist[v[i]] + 1; break; } } vector> dp(N, vector(2, 0)); dp[0][0] = K; for (ll i = 1; i < N; i++) { dp[i][0] = dp[i - 1][1]; dp[i][1] = (dp[i - 1][0] * (K - 1) + dp[i - 1][1] * (K - 2)) % mod; } ll ans = dp[cnt - 1][1]; for (ll i = 0; i < N - cnt; i++) { ans = (ans * (K - 1)) % mod; } cout << ans << endl; for (int i = 0; i < N; i++) { assert(tree.same(0, i)); } return 0; }