动态规划:求连续的元素的和(素数个)

xiaoxiao2021-02-28  3

//题意:

 Rhezo and Prime Problems Attempted by:  3257 / Accuracy:  77% / Maximum Score:  20 /   630 Votes Tag(s):  

Data Structures, Dynamic Programming, Easy, Number Theory

PROBLEM EDITORIAL MY SUBMISSIONS ANALYTICS

Rhezo and his friend Vanya love problem solving. They have a problem set containing NN problems, with points assigned to each. Rhezo wants to solve problems in such a way that he gets the maximum number of points. Rhezo has a weird habit of solving only prime number of consecutive problems, that is, if he solves XX consecutive problems from the problem set, then XX should be prime. Vanya has already solved all problems from the problem set and he wonders how much maximum points Rhezo can get. Vanya can answer this, but can you?

Input:

First line contains a single integer NN, denoting the number of problems in the problem set. Next line contains NN space separated integers denoting the points assigned to the problems.

Output:

Print a single integer, the maximum points Rhezo can get.

Constraints:

1N50001≤N≤5000

11≤Points of Problems105≤105

SAMPLE INPUT   4 8 1 3 7 SAMPLE OUTPUT   12

//代码:

import java.util.*; import java.io.*; import java.math.*; class Main { public static void main(String args[]) { //File file= new File("COMPLETE_FILE_PATH"); //InputStream is = new FileInputStream(file); //InputReader in = new InputReader(is); //InputReader in = new InputReader(System.in); //PrintWriter out = new PrintWriter(System.out); int t = 1; while (t-- > 0) { Task solver = new Task(); solver.solve(t); } } static class Task{ long mod=1000000007; static boolean[]isPrime; static List<Integer>Prime; public static void solve(int testNumber) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); long []arr=new long[n+1]; long []dp=new long[n+1]; for(int i=1;i<=n;i++) { arr[i]=arr[i-1]+sc.nextInt(); } Prime=new ArrayList<>(); judge(n); dp[0]=dp[1]=0; /* for(int i=2;i<=n;i++) dp[i]=dp[i-1];*/ for(int i=2;i<=n;i++) { dp[i]=dp[i-1]; for(int j=0;j<Prime.size()&&Prime.get(j)<=i;j++){ if(Prime.get(j)==i){ dp[i]=Math.max(dp[i],arr[i]); } else{ int p=i-Prime.get(j)-1; dp[i]=Math.max(dp[i],dp[p]+arr[i]-arr[p+1]); } } } System.out.println(dp[n]); } public static void judge(int N) { isPrime=new boolean[N+1]; for(int i=2;i<=N;i++){ isPrime[i]=true; } for(int i=2;i<=N;i++){ if(isPrime[i]){ Prime.add(i); } for(int j=i*i;j<=N;j+=i){ isPrime[j]=false; } } } } }https://doigetitnow.quora.com/Rhezo-and-Prime-problems

转载请注明原文地址: https://www.6miu.com/read-2450182.html

最新回复(0)