Time Limit: 2 sec / Memory Limit: 1024 MB
思路:n按奇数偶数分开写,如果n是偶数,中途最多可以有两个不选,设置dp1,dp2,
如果n是奇数,中间最多有三个可以不选,设置三个数组,算了我不知道怎么用语言解释
Score :600 points
Problem Statement
Given is an integer sequence A1,...,AN of length N .
We will choose exactly ⌊N/2⌋ elements from this sequence so that no two adjacent elements are chosen.
Find the maximum possible sum of the chosen elements.
Here ⌊x⌋denotes the greatest integer not greater than xx .
Constraints
- 2≤N≤2×105
- |Ai|≤109
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A1 ...... AN
Output
Print the maximum possible sum of the chosen elements.
Sample Input 1 Copy
Copy
6 1 2 3 4 5 6
Sample Output 1 Copy
Copy
12
Choosing 2 , 4 , and 6 makes the sum 12 , which is the maximum possible value.
Sample Input 2 Copy
Copy
5 -1000 -100 -10 0 10
Sample Output 2 Copy
Copy
0
Choosing −10and 10 makes the sum 0 , which is the maximum possible value.
Sample Input 3 Copy
Copy
10 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000
Sample Output 3 Copy
Copy
5000000000
Watch out for overflow.
Sample Input 4 Copy
Copy
27 18 -28 18 28 -45 90 -45 23 -53 60 28 -74 -71 35 -26 -62 49 -77 57 24 -70 -93 69 -99 59 57 -49
Sample Output 4 Copy
Copy
295
#include<bits/stdc++.h> using namespace std; #define ll long long #define rep(i,n) for(int i=0;i<n;i++) #define repr(i,n) for(int i=n-1;i>=0;i--) const int N=2e5; int main(){ int n; cin>>n; int a[n]; rep(i,n) scanf("%d",&a[i]); if(n%2==0){ ll dp[n]; dp[0]=a[0]; dp[1]=a[1]; for(int i=2;i<n;i++){ if(i%2==0) dp[i]=dp[i-2]+a[i]; else dp[i]=max(dp[i-3],dp[i-2])+a[i]; } printf("%lld\n",max(dp[n-1],dp[n-2])); } else{ vector<ll>l(n/2),m(n/2),r(n/2); l[0]=a[0]; m[0]=a[1]; r[0]=a[2]; for(int i=1;i<n/2;i++){ l[i]=l[i-1]+a[2*i]; m[i]=max(l[i-1],m[i-1])+a[2*i+1]; r[i]=max(l[i-1],max(m[i-1],r[i-1]))+a[2*i+2]; } printf("%lld\n",max(l[n/2-1],max(m[n/2-1],r[n/2-1]))); } return 0; }