Supreme Number
- 时间:1000ms
- 内存:131072K
A prime number (or a prime) is a natural number greater than 11 that cannot be formed by multiplying two smaller natural numbers.
Now lets define a number N as the supreme number if and only if each number made up of an non-empty subsequence of all the numeric digits of N must be either a prime number or 11.
For example, 17 is a supreme number because 1, 7, 17 are all prime numbers or 1, and 19 is not, because 9 is not a prime number.
Now you are given an integer N (2≤N≤10^100), could you find the maximal supreme number that does not exceed N?
Input
In the first line, there is an integer T (T≤100000) indicating the numbers of test cases.
In the following T lines, there is an integer N (2≤N≤10^100).
Output
For each test case print "Case #x: y"
, in which xx is the order number of the test case and yy is the answer.
样例输入
2 6 100
样例输出
Case #1: 5 Case #2: 73
题目来源
大意:定义一种"超级素数",其本身或者所有的子序列都是素数或1,这样的数叫“超级素数”,现在给出一个数N,问不超过N的最大的“超级素数”是多少?
分析:首先可以看到,N最大足足有100位,这么大的数显然是有问题的,要么就是当作字符串分析,要么就是实际找的数可能不会那么大。按照第二个想法,如果这种数不会太长,是什么限制了它的长度?这时我们可以看到,每一位数只可能从0~9这十种情况中选,那么十一位数中肯定有至少一个一位数出现了两遍。而这个题要求子序列也要是素数(注意序列是可以不连续的!),这样可以轻松想到,如果两个相同的数组成的两位数,它是不是可能不是素数?是的,在所有的这样的数中,除了11是素数,其余的22,33,…,99都是11的倍数。这样的话,如果一个数中存在两位相同的数组,那么必然存在一个由这两个数字组成的两位数,且除了11之外都不是素数。这样就简单了。也就是说,我们要找的数中,至少要满足如下要求:
对于每一位数:
1、这个数必须为素数或1。
2、除1之外,每种数只能出现1遍,1最多出现两遍。
这样就简单了,1位数中,满足要求的数只有1,2,3,5,7这5个,所有符合要求的数,只能由这5种数组成。这样我们可以暴力搜索一波,从这5个数中不重复地取出数字组成新的数,判断这个数是否为素数,是的话存下来。由于1可能出现两边,我们在一开始时可以放两个“不同的1”,用二进制表示集合,这样搜完的数中肯定有重复的,只要去个重就好了。
这样打个表出来,我们会发现符合要求的数其实很少。虽然上述打表方式不能完全保证是对的,但不会漏掉正确的解。至于会不会多出错误的解,用肉眼检查一下也能看出来。
我们可以把打出来的表直接写在代码中,对于所有输入的数(当字符串存),如果长度小于等于我们表中最大的那个数的长度,那么则将其转成数字,在表中二分查找下大于等于输入的数的前一个位置就好,否则,则输出表中最大的数。
以下是我的AC代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;
int isPrime(int x)
{
int sq = sqrt(x+0.5);
for(int i = 2; i <= sq; ++i)
if(x%i==0) return false;
return true;
}
//int su[] = {1,2,3,5,7,11,13,17,23,31,37,53,71,73,113,131,137,173,311,317};
int su[100] = {1,1,2,3,5,7};
int cnt = 6;
char s[1000];
void dfs(int x,int w)
{
for(int i = 0; i < 6; ++i)
{
if((w&(1<<i))==0)
{
int m = x*10+su[i];
if(isPrime(m))
{
//printf("%d\n",m);
su[cnt++] = m;
dfs(m,w|(1<<i));
}
}
}
}
int main()
{
for(int i = 0; i < 6; ++i)
dfs(su[i],1<<i);
sort(su,su+cnt);
cnt = unique(su,su+cnt)-su;
//for(int i = 0; i < cnt; ++i)
// printf("%d%c",su[i],i==cnt-1?'\n':' ');
//printf("%d\n",cnt);
int t,casee= 0;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
int len = strlen(s);
int ans = su[cnt-1];
if(len <= 3)
ans = *(upper_bound(su,su+cnt,atoi(s))-1);
printf("Case #%d: %d\n",++casee,ans);
}
return 0;
}