DP-- Luo Gu p1569

First summarize the meaning of the questions: an array of all in the numbers are divided into several groups, ensuring value for each number of groups under the premise of greater than or equal to 0, find the maximum number of groups eligible.
Obviously this is a prefix and problems.
Problem-solving ideas: obtaining the first n items of input values at the time of input and, add it in the array. (If the add [n] <0, the direct satisfied, output Impossible)
and from 1 to n, the i-th found; from 1 to i-1, find the number j. If add [i] -add [j] > = 0, then the state transition dp [i] = max (dp [i], dp [j] +1) ( when j = 1, the equation is given the role of dp [I] initial value, when that j> 1, from the equation as a constant update dp, dp find the maximum value) of
the codes:

#include <bits/stdc++.h>
#define maxn 1100
using namespace std;
int n,t=0,num=0;
int a[maxn],add[maxn];
int dp[maxn];
void knapsack(int n){
  for(int i=1;i<=n;i++){
    cin>>a[i];
    num+=a[i];
    add[i]=num;
  }
for(int i=1;i<=n;i++){
            if(i==1&&add[1]>=0) {
                dp[1]=1;//给dp[1]赋初值,若不赋,则输出值会少一
                //原因是当i=1时,j=0,转移方程并没有给dp[1]赋值,所以在这里赋初值
            }
            else if(i!=1&&add[i]>=0){
              for(int j=1;j<i;j++){
                if(add[i]-add[j]>=0){
                    dp[i]=max(dp[i],dp[j]+1);
                }
              }
            }
           }
          }
int main(){
   cin>>n;
   knapsack(n);
if(add[n]<0) cout<<"Impossible";
else cout<<dp[n];
return 0;
}

Released four original articles · won praise 1 · views 60

Guess you like

Origin blog.csdn.net/weixin_45186911/article/details/105144524