先说题目本身。看到不断重复跳 ,考虑倍增。小数的前面的位大了就一定大,可以贪心。
记 表示 点跳 步之后达到的点, 表示长度为 时第 大的小数对应的起点(为方便起见,下标从 0 开始), 表示长度为 时第 个点作为起点的排名(小数越大,排名也越大)。
在第 层,可以采用以下的方式比较两个起点的大小:如果 与 不等,直接结束。如果相等,比较 和 即可。将这个比较函数传进 sort 里就可以得到 ,进而处理出 。从大到小排比较好。
答案的起点一定是 ,因为显然 ,则前 位最大的前 位也是最大。时间复杂度 ,虽然总和有两百万但一组数据只有十五万,肯定能过。
你发现你需要对 sort 传入有第三个参数的比较函数。只需要定义一个有 operator()(int a,int b) 的类并在这个类里放置一个变量即可。具体见代码。
Code Time
#include <bits/stdc++.h>
using namespace std;
const int N=150007;
int to[20][N],p[20][N],h[20][N];
struct cmp{
int x;
bool operator()(int a,int b){
if(h[x-1][a]!=h[x-1][b]) return h[x-1][a]>h[x-1][b];
return h[x-1][to[x-1][a]]>h[x-1][to[x-1][b]];
}
} qwq;
struct equ{
int x;
bool operator()(int a,int b){
if(h[x-1][a]!=h[x-1][b]) return 0;
return h[x-1][to[x-1][a]]==h[x-1][to[x-1][b]];
}
} qaq;
int main(){
cin.tie(0)->sync_with_stdio(0);
int t;
cin>>t;
for(int q=1;q<=t;q++){
int n;
cin>>n;
char ch;
for(int i=0;i<n;i++) cin>>ch,h[0][i]=ch-'0';
for(int i=0;i<n;i++) to[0][i]=(1ll*i*i+1)%n;
for(int i=1;i<20;i++) for(int j=0;j<n;j++) to[i][j]=to[i-1][to[i-1][j]];
for(int i=1;i<20;i++){
iota(p[i],p[i]+n,0);
qwq.x=qaq.x=i;
sort(p[i],p[i]+n,qwq);
h[i][p[i][0]]=n;
for(int j=1;j<n;j++) if(qaq(p[i][j],p[i][j-1])) h[i][p[i][j]]=h[i][p[i][j-1]];
else h[i][p[i][j]]=h[i][p[i][j-1]]-1;
}
cout<<"Case #"<<q<<": ";
int u=p[19][0];
for(int i=0;i<n;i++) cout<<h[0][u],u=to[0][u];
cout<<'\n';
}
return 0;
}