#include <bits/stdc++.h>
using namespace std;
#define int long long
struct Unionfind{
  vector<int> par, siz;
  //初期化
  Unionfind(int n) : par(n,-1) , siz(n,1) {}
  int root(int x) {
    if(par[x] == -1) return x;
    else return par[x] = root(par[x]);
  }
  bool issame(int x,int y) {
    return root(x) == root(y);
  }
  bool unite(int x, int y){
    x = root(x); y = root(y);
    if(x ==  y) return false;
    if(siz[x] < siz[y]) swap(x,y);
    par[y] =  x;
    siz[x] += siz[y];
    return  true;
  }
  int size(int x) {
    return siz[root(x)];
  }
};
int mod = 998244353;
int N,K;
int int_pow(int x, int n) {
  int ret = 1;
  while (n > 0) {
    if (n & 1) ret = ret * x % mod;
    x = x * x % mod;
    n >>= 1;
  }
  return ret;
}
int f(int a){
	if(a == 2){
		return K*(K-1)%mod;
	} 
	else {
		return (K*int_pow(K-1,a-1)-f(a-1))%mod;
	}
}
signed main(){
    cin>>N>>K;
    vector<vector<int>> G(N);
    Unionfind uf(N);
    int s = 0;
    for(int i=0;i<N;i++){
    	int a,b;
    	cin>>a>>b;
    	a--;
    	b--;
    	G[a].push_back(b);
    	G[b].push_back(a);
    	if(uf.issame(a,b)) s = a;
    	else uf.unite(a,b);
    }
    vector<int> dist(N,1e18);
    dist[s] = 0;
    stack<pair<int,int>> q;
    q.push({s,-1});
    while(!q.empty()){
    	auto pos = q.top();
    	q.pop();
    	if(dist[s]) break;
    	for(int x:G[pos.first]){
    		if(pos.second == x) continue;
    		q.push({x,pos.first});
    		dist[x] = dist[pos.first]+1;
    	}
    }
    int ans = f(dist[s]);
    for(int i=dist[s];i<N;i++) ans = (ans*(K-1))%mod;
    cout<<ans<<endl;
}