跳到正文

题解

题解:P17071 [ICPC 2017 Shenyang R] Infinite Fraction Path && 如何给 sort 传入带额外参数的比较函数

Grammar_hbw约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年7月5日
收录
2026年7月5日
更新
2026年11月16日
篇幅
约 3 分钟
获赞
1
题目
P17071

版本

  1. v2当前
  2. v1

先说题目本身。看到不断重复跳 i2+1i^2+1,考虑倍增。小数的前面的位大了就一定大,可以贪心。

记 toi,jto_{i,j} 表示 jj 点跳 2i2^i 步之后达到的点,pi,jp_{i,j} 表示长度为 2i2^i 时第 jj 大的小数对应的起点(为方便起见,下标从 0 开始),hi,jh_{i,j} 表示长度为 2i2^i 时第 jj 个点作为起点的排名(小数越大,排名也越大)。

在第 ii 层,可以采用以下的方式比较两个起点的大小:如果 hi−1,ah_{i-1,a} 与 hi−1,bh_{i-1,b} 不等,直接结束。如果相等,比较 hi−1,toi−1,ah_{i-1,to_{i-1,a}} 和 hi−1,toi−1,bh_{i-1,to_{i-1,b}} 即可。将这个比较函数传进 sort 里就可以得到 pip_i,进而处理出 hih_i。从大到小排比较好。

答案的起点一定是 p19,0p_{19,0},因为显然 219>n2^{19}>n,则前 2192^{19} 位最大的前 nn 位也是最大。时间复杂度 O(∑nlog⁡2n)O(\sum n \log ^2 n),虽然总和有两百万但一组数据只有十五万,肯定能过。

你发现你需要对 sort 传入有第三个参数的比较函数。只需要定义一个有 operator()(int a,int b) 的类并在这个类里放置一个变量即可。具体见代码。

Code Time
C++
#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;
}
原文
存档评论10 条抓取于