POJ 2739:Sum of Consecutive Prime Numbers(Two pointers)
【题目链接】 http://poj.org/problem?id=2739
【题目大意】
求出一个数能被拆分为相邻素数相加的种类
【题解】
将素数筛出到一个数组,题目转化为求区段和等于某数的次数,尺取法即可。
【代码】
#include <cstdio>
#include <algorithm>
using namespace std;
int p[10010],cnt,a[10010],x;
int main(){
for(int i=2;i<=10000;i++){
if(!a[i]){p[++cnt]=i;for(int j=i+i;j<=10000;j+=i)a[j]=1;}
}
while(scanf("%d",&x)&&x){
int l=1,r=0,ans=0,s=0;
for(;l<=cnt;s-=p[l],l++){
while(r<cnt&&s<x){r++;s+=p[r];}
if(s==x)ans++;
if(p[r]>x)break;
}printf("%d\n",ans);
}return 0;
}
愿你出走半生,归来仍是少年

浙公网安备 33010602011771号