sdut2404 Super Prime ACM算法设计

Super Prime

Time Limit: 5000MS Memory limit: 65536K

题目描述

We all know, prime is a kind of special number which has no other factors except of 1 and itself.
2,3,5,7,11,13,17,19,23,29 are the top 20 primes.
Now there is a new question about prime:
We call a prime as super prime when and only when which can be represented as the sum of multiple continuous primes. For example: 5=2+3, so 5 is a super prime.
Please program to judge whether a number is a super prime or not.

输入

The first line is an integer T (T<=1000), and then T lines follow.
There is only one positive integer 
N(1

输出

For each case you should output the case number first, and then the word "yes" if the integer N is a super prime, and you should output "no" otherwise.

示例输入

3
5
7
8

示例输出

Case 1: yes
Case 2: no
Case 3: no

提示

 

来源

2012年"浪潮杯"山东省第三届ACM大学生程序设计竞赛(热身赛)
/************************************************************************/
/*  
作者:iFinVer
特点:数量级趋于无穷时效率亦趋于无穷,数量级较小时效率一般。
实现方式:记忆性数组
*/
/************************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <cmath>
using namespace std;

vector<int> primes;
vector<int> superPrimes;
vector<int>::iterator front,back;

inline bool IsPrime(const int& in)
{
	if(in == 0 || in == 1) return false;
	if(in == 2 || in == 3 || in == 5 || in == 7) return true;
	for(int i = 2;i <= sqrt(in);i ++)
	{
		if(in % i == 0) return false;
	}
	return true;
}
bool IsSuperPrime(const int& in)
{
	if(in == 2 || in == 3 || in == 7) return false;
	else if(in == 5) return true;

	if(find(superPrimes.begin(),superPrimes.end(),in) != superPrimes.end())
		return true;
	front = back = find(primes.begin(),primes.end(),in);
	back --;
	front --;
	front --;
	int total = 0;
	total += *back;
	total += *front;
	while (true)
	{
		if(total > in)
		{
			total -= *back;
			back --;
			if(back == front)
			{
				if(front == primes.begin()) return false;
				else front--,total += *front;
			}
			
		}
		else if(total == in)
		{
			return true;
		}
		else
		{
			if(front == primes.begin()) return false;
			front --;
			total += *front;
		}
	}
	return false;
}
int main()
{
	//ifstream cin("in.txt");
	//The first prime number	
	primes.push_back(2);

	int rowCount;
	cin>>rowCount;
	int cases = 1;	
	while(rowCount --)
	{
		int num;
		cin>>num;
		if(num > primes.back())
		{			
			for(int i = primes.back()+1;;i++)
			{
				if(IsPrime(i))
				{
					primes.push_back(i);
					if(i == num) 
						break;						
				}
				if(i >= num)
				{
					break;
				}
			}					
		}
		if(IsPrime(num) && IsSuperPrime(num))
		{
			cout<<"Case "<<cases++<<": yes"<<endl;
			continue;
		}
		cout<<"Case "<<cases++<<": no"<<endl;
		//cout<<num<<" Is Not Prime"<<endl;
	}

	return 0;
}

AC耗时 68毫秒. 本题的测试数据较少,所以如果去掉记忆性代码,会减少耗时.

本博客所有博文,若无专门说明皆为原创,转载请注明作者和出处!
原文地址:https://www.cnblogs.com/ifinver/p/3013029.html