Considering 4-digit primes containing repeated digits it is clear that they cannot all be the same: 1111 is divisible by 11, 2222 is divisible by 22, and so on. But there are nine 4-digit primes containing three ones:
1117, 1151, 1171, 1181, 1511, 1811, 2111, 4111, 8111
We shall say that M(n, d) represents the maximum number of repeated digits for an n-digit prime where d is the repeated digit, N(n, d) represents the number of such primes, and S(n, d) represents the sum of these primes.
So M(4, 1) = 3 is the maximum number of repeated digits for a 4-digit prime where one is the repeated digit, there are N(4, 1) = 9 such primes, and the sum of these primes is S(4, 1) = 22275. It turns out that for d = 0, it is only possible to have M(4, 0) = 2 repeated digits, but there are N(4, 0) = 13 such cases.
In the same way we obtain the following results for 4-digit primes.
Digit, d M(4, d) N(4, d) S(4, d)
0 2 13 67061
1 3 9 22275
2 3 1 2221
3 3 12 46214
4 3 2 8888
5 3 1 5557
6 3 1 6661
7 3 9 57863
8 3 1 8887
9 3 7 48073
For d = 0 to 9, the sum of all S(4, d) is 273700.
Find the sum of all S(10, d).
定义M(n,d)是n位素数中d出现次数的最大值
N(n,d)是使得M(n,d)取得最大值的个数
S(n,d)是这些素数的和
1<=n<=10,0<=d<=9
首先感觉肯定像是数位DP吧..
但是没做过用数位DP,然后还跟素数有关的题目吖QAQ
q巨随便猜了一下说d出现的数位个数或许是大于等于n-3的..
然后写了个暴力跑了一下..
30s就能跑出答案…在ProjectEuler的可接受范围内..
交上去竟然还是对的..[哔—-]
不知道这个结论为什么对..
Find the sum of all S(10, d).
Ans=612407567715
UPD.A了之后在Discuss里看到了有人有1s以内能跑出来的做法..
这样这题就可以正式出到OI考场上了..
先全部填成d,然后从0-n枚举有几位不是d,全排列,爆搜
很多人都这么写的然后1s内能出解..
但是有没有老司机能告诉我为什么这么做复杂度是对的..
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define LL long long
using namespace std;
int n,d;
LL ans,tmp,T,sum;
int b[15];
bool check(LL x)
{
for (int i=2;i<=(int)(sqrt(x));++i) if (x%i==0) return 0;
return 1;
}
void dfs(int now,LL sum)
{
if (now==n+1)
{
if (sum>=T&&check(sum)) tmp+=sum;
return;
}
if (b[now]) sum=sum*10+d,dfs(now+1,sum);
else
{
LL t;
for (int i=0;i<=9;i++) if (i!=d) t=sum*10+i,dfs(now+1,t);
}
}
int main()
{
scanf("%d",&n);T=1;
for (int i=1;i<n;++i) T*=10;
for (d=0;d<=9;d++)
{
ans=0;
for (int i=0;i<=3;++i)
{
memset(b,0,sizeof(b));tmp=0;
for (int j=n;j>i;--j) b[j]=1;
do { dfs(1,0); } while (next_permutation(b+1,b+n+1));
if (tmp&&!ans) ans=tmp;
}
sum+=ans;
}
cout<<sum<<endl;
}