#include using namespace std; using ll = long long; ll const m = 998244353; int main () { int N; ll K; cin >> N >> K; std::vector> gr(N); for (int i = 0; i < N; i ++) { int a, b; cin >> a >> b; if (a > b) swap(a, b); gr[--a].push_back(--b); } vector D(N, -1), D2(N, -1); int len = 0; for (int i = 0; i < N; i ++) { if (D[i] != -1) continue; D[i] = D2[i] = 0; vector V; queue que; que.push(i); V.push_back(i); while (!que.empty()) { int u = que.front(); for (int v : gr[u]) { if (u == v) { len = 1; break; } if (D2[v] == -1) { D[v] = D2[v] = D2[u] + 1; que.push(v); V.push_back(v); } else { int p = D2[u] + 1, q = D2[v]; len = p - q + 2; break; } } } if (len) break; for (auto u : V) { D2[u] = -1; } } ll ans = K; ll hog = K; if (len > 1) { ans = (K * (K - 1)) % m; hog = (K * (K - 1)) % m; } for (int i = 2; i < len; i ++) { ans = (K - 2) * ans + (K - 1) * ((hog - ans + m) % m); ans %= m; hog = (hog * (K - 1)) % m; } for (int i = 0; i < N - len; i ++) { ans = (ans * (K - 1)) % m; } cout << ans << endl; }