LDUOJ 1586. 【吴永辉】程序设计基础实践7-9 P. Primed Subsequence

P. Primed Subsequence

题目描述

Given a sequence of positive integers of length n, we define a primed subsequence as a consecutive subsequence of length at least two that sums to a prime number greater than or equal to two.

For example, given the sequence:

3 5 6 3 8

There are two primed subsequences of length 2 (5 + 6 = 11 and 3 + 8 = 11), one primed subsequence of length 3 (6 + 3 + 8 = 17), and one primed subsequence of length 4 (3 + 5 + 6 + 3= 17).

输入

Input consists of a series of test cases. The first line consists of an integer t (1<t<21), the number of test cases. Each test case consists of one line. The line begins with the integer n, 0<n<10001, followed by n non-negative numbers less than 10000 comprising the sequence. You should note that 80% of the test cases will have at most 1000 numbers in the sequence.

输出

For each sequence, print the “Shortest primed subsequence is length x:”, where x is the length of the shortest primed subsequence, followed by the shortest primed subsequence, separated by spaces. If there are multiple such sequences, print the one that occurs first. If there are no such sequences, print “This sequence is anti-primed.”.

Input:

3
5 3 5 6 3 8
5 6 4 5 4 12
21 15 17 16 32 28 22 26 30 34 29 31 20 24 18 33 35 25 27 23 19 21

Out:

Shortest primed subsequence is length 2: 5 6
Shortest primed subsequence is length 3: 4 5 4
This sequence is anti-primed.

题目大意:

给定一个长度为n的正整数序列,定义一个素数子序列为长度至少为2且其总和为素数且大于或等于2的连续子序列

打印“Shortest primed subsequence is length x:”,其中x是最短的质数子序列的长度,然后是最短的质数子序列,用空格分隔。如果有多个这样的序列,则打印第一个。如果没有这样的序列,则打印“This sequence is anti-primed.”

题目报告:

简单题(详解见代码注释)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e7+3;
int aa[10003];
bool prime(ll n) {
	for(ll j=2; j*j<=n; j++)
		if(n%j==0) return false;
	return true;
}
int main() {
	ll t,n,flag,sum;
	cin>>t;
	while(t--) {
		flag=0;
		cin>>n;
		for(int i=1; i<=n; i++) cin>>aa[i];
		for(int i=2; i<=n; i++) {//素数子序列的长度最少是两个,从2开始遍历 
			for(int j=1; j+i-1<=n; j++) {//注意截止条件是 j+i-1<=n 而不是 j+i<=n 判断好关系 
				sum=0;
				for(int k=j; k<j+i; k++) {//将从a[j]开始,长度是i的数加起来 
					sum+=aa[k];
				}
				if(prime(sum)) {//判断 和 是否是素数 
					flag=1;
					cout<<"Shortest primed subsequence is length "<<i<<":";
					for(int p=j; p<j+i; p++)
						cout<<" "<<aa[p];
					cout<<endl;
					break;
				}
			}
			if(flag) break;
		}
		if(!flag) cout<<"This sequence is anti-primed."<<endl;
	}

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值