题解:P17071 [ICPC 2017 Shenyang R] Infinite Fraction Path
hanhanli10 · · 题解
思路
观察题面,让我们求出最优无限小数,简化题面,转换成图,就会发现这是一个有向图,且有环,思考从一个节点到一个环的路径和环的长度,很容易便能想出环的长度和到环路径的长度均不超过
代码
#include <iostream>
#define fast ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define endl '\n'
using namespace std;
const int N = 2e6 + 10;
const int mmmm = 300;
//最大环的长度
int r[N];
char d[N];
int n;
void ddd(int &x, int y){
int a = x, b = y, cnt = 0;
while (d[a] == d[b]){
a = r[a], b = r[b];
cnt ++;
if (cnt >= min(n, mmmm)) break;
//小优化
}
if (d[a] < d[b]) x = y;
}
int main(){
fast;
int t;
cin >> t;
int cnt = 1;
while (t--){
cin >> n;
for (int i = 0; i < n; i++){
r[i] = (1ll * i * i % n + 1) % n;
cin >> d[i];
}
cout << "Case #" << cnt++ << ": ";
int mx = 0;
for (int i = 1; i < n; i++){
ddd(mx, i);
}
for (int i = 1; i <= n; i++){
cout << d[mx];
mx = r[mx];
}
cout << '\n';
}
return 0;
}
结尾
如果题解有误,可以指出。