贪心基础题:

5480. 截断数组 - AcWing题库

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 110; 
int n, b;
int a[N], cost[N];//存储代价 
int main(){
	cin>>n>>b;
	for(int i = 1; i<=n; i++) cin>>a[i];
	int odd = 0, even = 0, cnt = 0;
	for(int i = 1; i<n; i++){//遍历 
		if(a[i]%2==0) even ++ ;
		else odd ++ ;
		if(odd == even) cost[cnt++] = abs(a[i+1]-a[i]);
	}
	sort(cost, cost+cnt);//代价从小到大 
	int res = 0, sum = 0;
	for(int i = 0; i<cnt; i++){
		sum += cost[i];
		if(sum > b) break;
		res ++ ;
	}
	cout<<res;
	return 0;
} 

5481. 双端队列 - AcWing题库

分类讨论:

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 200010;
int n;
int w[N];
int main(){
	cin>>n;
	for(int i = 1; i<=n; i++) cin>>w[i];
	int res = 0, last = 0;//刚刚弹出的元素 
	for(int i = 1, j = n; i<=j; ){//左右指针模拟队列 
		//分类讨论
		if(w[i] != w[j]){
			if(w[i] < w[j]){
				if(w[j] <= last) break;
				if(w[i] <= last) last = w[j--];
				else last = w[i++];
				res ++ ;
			}
			else{
				if(w[i] <= last) break;
				if(w[j] <= last) last = w[i++];
				else last = w[j--];
				res ++ ;
			}
		} 
		else{
			//从左和从右 都枚举一遍
			int left = 0, tmp = last;
			for(int k = i; k<=j; k++){
				//k从左到右检查
				if(w[k] > tmp) tmp = w[k], left++;
				else break; 
			} 
			int right = 0;
			tmp = last;
			for(int k = j; k>=i; k--){
				if(w[k] > tmp) tmp = w[k], right++;
				else break;
			}
			res += max(left, right);
			break;
		}
	} 
	cout<<res;
	return 0;
}