結果
| 問題 |
No.101 ぐるぐる!あみだくじ!
|
| コンテスト | |
| ユーザー |
koyumeishi
|
| 提出日時 | 2014-11-28 08:46:42 |
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
| 結果 |
AC
|
| 実行時間 | 2 ms / 5,000 ms |
| コード長 | 2,595 bytes |
| コンパイル時間 | 914 ms |
| コンパイル使用メモリ | 82,576 KB |
| 実行使用メモリ | 6,820 KB |
| 最終ジャッジ日時 | 2025-01-03 10:05:38 |
| 合計ジャッジ時間 | 2,203 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 37 |
ソースコード
//想定解法 union-find tree
//1.あみだくじを1回だけシミュレートして置換先を決定し、置換先をunion-find treeでまとめ上げる。
// このとき森が出来て、木のそれぞれが一つのループになっている。
//2.それぞれの木の大きさを計算する
//3.木の大きさの最小公倍数が答え
//n<=100のため最大ケースは232792560 = 16*9*5*7*11*13*17*19となる。多分。オーバーフローはしないはず
#include <iostream>
#include <vector>
#include <map>
#include "assert.h"
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <sstream>
using namespace std;
#define MAX_N 100
#define MAX_K 1000
class UnionFindTree{
typedef struct {
int parent;
int rank;
}base_node;
vector<base_node> node;
public:
UnionFindTree(int n){
node.resize(n);
for(int i=0; i<n; i++){
node[i].parent=i;
node[i].rank=0;
}
}
int find(int x){
if(node[x].parent == x) return x;
else{
return node[x].parent = find(node[x].parent);
}
}
bool same(int x, int y){
return find(x) == find(y);
}
void unite(int x, int y){
x = find(node[x].parent);
y = find(node[y].parent);
if(x==y) return;
if(node[x].rank < node[y].rank){
node[x].parent = y;
}else if(node[x].rank > node[y].rank){
node[y].parent = x;
}else{
node[x].rank++;
unite(x,y);
}
}
};
long long gcd(long long a, long long b){
if(b==0) return a;
return gcd(b, a%b);
}
long long lcm(long long a, long long b){
if(a<b) swap(a,b);
if(b==1) return a;
return a* (b/gcd(a,b));
}
int solve_union_find(const vector<int> &v){
int N = v.size();
UnionFindTree uft(N);
for(int i=0; i<N; i++){
uft.unite(i, v[i]);
}
map<int,int> forest;
for(int i=0; i<N; i++){
int parent = uft.find(i);
auto itr = forest.find(parent);
if(itr != forest.end()){
itr->second += 1;
}else{
forest[parent] = 1;
}
}
int ans = 1;
for(auto itr = forest.begin(); itr != forest.end(); itr++){
int val = itr->second;
ans = lcm(ans, val);
}
return ans;
}
int main(){
int N;
cin >> N;
assert(2<=N && N<=MAX_N);
int K;
cin >> K;
assert(0<=K && K<=MAX_K);
vector<int> v(N);
for(int i=0; i<N; i++){
v[i] = i;
}
for(int i=0; i<K; i++){
int x,y;
cin >> x >> y;
assert(1<=x && x<= N);
assert(1<=y && y<= N);
assert(x<y);
assert(x+1 == y);
x--;
y--;
swap( v[x], v[y] );
}
cout << solve_union_find(v) << endl;
return 0;
}
koyumeishi