Linear dp worship (Los Valley P1564)

Worship

Title Description

There are many sacred cow ... of course ... each student has their own heartfelt worship of the sacred cow.

There are two schools of a sacred cow, oxen A and B sacred cow. N bits of newly enrolled students had heard their myths.

Therefore, it has been one of the heartfelt worship. Now, the teacher points to give them room. However, to ensure that the entire room is either the same God worshiped by cattle, or the difference between the number of worshipers of no more than two oxen m. Further, now a row n bits students, the teacher will only continuous sub-section of students into a room. The teacher wanted to know how many rooms need at least.

Input Format

The first line of the input file contains two integers n and m.

Second to (n + 1) row, i.e. an integer of 1 to 2 per line non, the (i + 1) line represents an integer of i-th student objects of worship, A represents 1, B represents 2.

Output Format

Output an integer representing the number of minimum required room.


The 2 becomes -1, the subject can be transformed into: the length into a continuous string of paragraphs is n, the absolute value of each segment and <= m, find the minimum number of segments;

State transition equation: dp [i] = min (dp [j] + 1, dp [i]), j is the front position i, j to ensure that this part and absolute value of i <= m, n complexity ^ 2;

Code:

#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=3000;
const int M=2000100;
const int mod=1e9;
int sum[N],a[N],dp[N];
int main(){
	int n,m;
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
		if(a[i]==2) a[i]=-1;
		sum[i]=sum[i-1]+a[i];
		dp[i]=2e9;
	}
	for(int i=1;i<=n;i++){
		for(int j=0;j<i;j++){
			if(abs(sum[i]-sum[j])<=m||abs(sum[i]-sum[j])==i-j) dp[i]=min(dp[j]+1,dp[i]);
		}
	}
	cout<<dp[n]<<endl;
	return 0;
}
Published 264 original articles · won praise 46 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_44291254/article/details/105336538