【线形DP练习】洛谷 P1868饥饿的奶牛 P1091合唱队形 P1541乌龟棋 P1020导弹拦截

这篇博客详细介绍了洛谷平台上的四道动态规划问题——P1868饥饿的奶牛、P1091合唱队形、P1541乌龟棋和P1020导弹拦截的解题思路。针对每道题目,博主提供了具体的动态规划算法实现,并分享了在优化空间和时间复杂度方面的经验。
摘要由CSDN通过智能技术生成

洛谷 P1868 饥饿的奶牛

https://www.luogu.com.cn/problem/P1868
思路:
dp[N]表示 在前i块草皮中最多能吃到几块
sort 把所有区间按照右端的大小排序
for 遍历[0,区间中出现过的最大长度]
{
dp[i] = dp[i-1] (继承上一个草皮的dp)
if存在区间[x,y] 使得y=i 则dp[y] = max ( dp[y] , dp[x-1]+len([x,y]) )
}

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <vector>
typedef long long LL;
typedef std::pair<int ,int> PP;
const int N = 3e6+5;
int n,v,vv;
int dp[N];
bool cmp(PP x, PP y)
{
   
   return x.second < y.second ;
}

int main()
{
   
   std::vector<PP> vc;
   std::cin >> n;
   for(int i=0; i<n; i++){
   
      std::cin>> v  >> vv;
      vc.push_back(std::make_pair(v,vv));
   }
   std::sort(vc.begin(),vc.end(),cmp);
   int idx=1;
   for(std::vector<PP>::iterator iter = vc.begin(); iter != vc.end(); iter++){
   
      //这里要加等号,否则最后两个样例会WA
      while(idx <= iter->second){
   
         dp[idx] = std::max(dp[idx],dp[idx-1]);
         idx += 1;
      }
      dp[iter->second] = std::max(dp[iter->first-1]+iter->second-iter->first+1,dp[iter->second]);
   }
   std::cout << dp[vc[vc.size()-1].second] << std::endl;
   return 0;
}

洛谷 P1091 合唱队形

https://www.luogu.com.cn/problem/solution/P1091
此题要求提出最少的人,获得一个最长的先单调递增后点掉递减的队伍,对于队伍递增递减部分的长度没有要求。
思路:
up[]数组记录 在正向遍历下 第i个位置的最长升序列长度(第一个长度计0)
dn[]数组记录 在反向遍历下 第i个位置的最长升序列长度(第一个长度计0)
然后遍历一遍 [0,n-1],找出最大的 先增后降序列长度 (up[i]+dn[i]+1)
n-最大长度 即为答案

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <vector>
typedef long long LL;
typedef std::pair<int ,int> PP;
const int N = 105;
int qu[N],up[N],dn[N];
int n;

int main()
{
   
   scanf("%d",&n);
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值