题目地址:http://poj.org/problem?id=3842 或者: https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2610
思路就是暴力求出每一种可能的情况,进行全排列(next_permutation可以去重)然后对每一种排列考虑前面的子串。
为了防止一个情况被考虑两次,设置一个占位符b[10000000]
每次新输入数,记得将b清空,然后先转化成int数组,每次翻译成一个int时快一些。
这个代码在UvaLive上过了,poj上TLE,看来是卡常数了,有空进行修改吧
#include<iostream>
#include<string>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstdio>
using namespace std;
bool b[10000000];
char p[7];
int pp[7];
int prime[10000000];
int ten[7];
void pre()
{
prime[0]=1;
prime[1]=1;
int len=sqrt(10000000);
for(int i=2;i<=len;i++)
if(prime[i]==0)
for(int j=i*i;j<=10000000;j+=i)
prime[j]=1;
int first=1;
for(int i=0;i<7;i++)
{
ten[i]=first;
first*=10;
}
}
int main()
{
pre();
int T;
cin>>T;
while(T--)
{
memset(b,0,10000000);
//cin>>p;
scanf("%s",p);
int count=0;
int n=strlen(p);
for(int i=0;i<n;i++)
pp[i]=p[i]-'0';
sort(pp,pp+n);
do{
for(int len=1;len<=n;len++)
{
int cur=0;
for(int i=0;i<len;i++)
{
cur+=ten[i]*pp[n-1-i];
}
if(b[cur]==1) continue;
if(prime[cur]==0)
{
count++;
b[cur]=1;
}
}
}
while(next_permutation(pp,pp+n));
//cout<<count<<endl;
printf("%d\n",count);
}
}