結果
| 問題 |
No.2531 Coloring Vertices on Namori
|
| コンテスト | |
| ユーザー |
keisuke6
|
| 提出日時 | 2023-11-03 21:49:55 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 334 ms / 2,000 ms |
| コード長 | 1,561 bytes |
| コンパイル時間 | 2,256 ms |
| コンパイル使用メモリ | 206,020 KB |
| 最終ジャッジ日時 | 2025-02-17 18:06:11 |
|
ジャッジサーバーID (参考情報) |
judge2 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 31 |
ソースコード
#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;
}
keisuke6