标签:
Sum of Consecutive Prime Numbers
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 21924 | Accepted: 11996 |
Description
Input
Output
Sample Input
2
3
17
41
20
666
12
53
0
Sample Output
1
1
2
3
0
0
1
2
Source
#include<cstdio>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include<map>
#include <algorithm>
#include <set>
using namespace std;
#define MM(a) memset(a,0,sizeof(a))
typedef long long LL;
typedef unsigned long long ULL;
const int mod = 1000000007;
const double eps = 1e-10;
const int inf = 0x3f3f3f3f;
bool prime(int n)
{
for(int i=2;i*i<=n;i++)
if(n%i==0)
return 0;
return 1;
}
int a[2000];
void init()
{
a[0]=0;
for(int i=2,cnt=0;i<=10000;i++)
if(prime(i))
a[++cnt]=i;
}
int main()
{
init();
int n;
while(~scanf("%d",&n)&&n)
{
int l=1,r=0,sum=0,ans=0;
for(;;)
{
while(sum<n&&a[r+1]<=n)/*a[r+1]<=n表示
该数是可加的,意即右端点还可以继续右移*/
sum+=a[++r];
if(sum<n)/*右端点无法继续右移,而左端点的右移只能使sum
减小,意即sum数组无法再大于等于n,就可以退出循环*/
break;
else if(sum>n)
{
sum-=a[l];
l++;
}
else if(sum==n)
{
ans++;
sum-=a[l];
l++;
}
}
printf("%d\n",ans);
}
return 0;
}
下面是re代码,好好体会下为什么会re:
#include<cstdio>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include<map>
#include <algorithm>
#include <set>
using namespace std;
#define MM(a) memset(a,0,sizeof(a))
typedef long long LL;
typedef unsigned long long ULL;
const int mod = 1000000007;
const double eps = 1e-10;
const int inf = 0x3f3f3f3f;
bool prime(int n)
{
for(int i=2;i*i<=n;i++)
if(n%i==0)
return 0;
return 1;
}
int a[2000];
void init()
{
a[0]=0;
for(int i=2,cnt=0;i<=10000;i++)
if(prime(i))
a[++cnt]=i;
}
int main()
{
init();
int n;
while(~scanf("%d",&n)&&n)
{
int l=1,r=0,sum=0,ans=0;
for(;;)
{
while(sum<n)
/*如果不添加a[r]<=n的话,会一直加下去,
即右端点一直往右移动,从而爆数组*/
sum+=a[++r];
if(sum<n)
break;
else if(sum>n)
{
sum-=a[l];
l++;
}
else if(sum==n)
{
ans++;
sum-=a[l];
l++;
}
}
printf("%d\n",ans);
}
return 0;
}
poj 2739 Sum of Consecutive Prime Numbers 尺取法
标签:
原文地址:http://www.cnblogs.com/smilesundream/p/5131537.html