跳到正文

题解

题解:P13435 [GCJ 2009 #1B] The Next Number

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

文章信息

收录
2025年12月12日
更新
2026年5月18日
篇幅
约 3 分钟
题目
P13435

版本

  1. v1当前

传送门

P13435 [GCJ 2009 #1B] The Next Number

AC的那一刻,我真的觉得很不可思议。 这题一开始我想的是直接 next_permutation 枚举下一个:

C++
#include<bits/stdc++.h>
using namespace std;
int n2,n,a[10],b[10];
bool check(int t){
	memset(b,0,sizeof(b));
	while(t){
		b[t%10]++;
		t/=10;
	}
	for(int i = 1;i<10;i++)if(a[i]!=b[i])return 1;
	return 0;
}
int main(){
	cin.tie(0)->sync_with_stdio(0);
	cout.tie(0);
	int T;
	cin>>T;
	for(int i = 1;i<=T;i++){
		cin>>n;
		n2 = n;
		memset(a,0,sizeof(a));
		while(n2){
			a[n2%10]++;
			n2/=10;
		}
		n++;
		while(check(n))n++;
		cout<<"Case #"<<i<<": "<<n;
		cout<<'\n';
	}
	return 0;
}

非常顺利的……T了。 然后加了一堆剪枝。给优化到没分了。 然后我就想了好久。我突然一个激灵:三位数没法直接继续了然后变成四位数,不就是利用了三位数前面有个不存在的前导 00 吗?那直接默认前导 00 的存在不就好了! 举个例子:比如 511511,我前面加个 00,变成了 05110511,他的下一个数就是 10151015。 然后。

C++
cin>>(ch+1);//留出一位
ch[0] = '0';//赋值,别忘了
int n = strlen(ch+1);
next_permutation(ch,ch+n+1);//注意是ch不是ch+1,要让前导0存在

然后AC了。 完整代码:

C++
#include<bits/stdc++.h>
using namespace std;
char ch[100];
int main(){
	cin.tie(0)->sync_with_stdio(0);
	cout.tie(0);
	int T,n;
	cin>>T;
	for(int i = 1;i<=T;i++){
		cin>>(ch+1);//留出一位放前导0
		ch[0] = '0';//放置前导0
		int n = strlen(ch+1);
		next_permutation(ch,ch+n+1);//下一个排列,因为有0,所以是一定存在的
		cout<<"Case #"<<i<<": ";
		if(ch[0]-'0')cout<<ch[0];//特判,不输出前导0
		for(int i = 1;i<=n;i++)cout<<ch[i];
		cout<<'\n';
	}
	return 0;
}

作为一个OIer,我们要学会变通,懂不懂?(逃

原文