标签:图片 特点 的区别 char 递推 def 不难 names cout
这两道题看起来几乎一模一样,但是第一道是绿题,第二道却是橙题,做法也很不一样。
为什么第二道可以直接递推,第一道却得用单调栈呢?
其实也不难分析。两道题的区别是是否限制填充矩形的宽度。第一道没有限制,对于每个高度需要用几个矩形便是未知的,
故须找出最优方案,所以根据其最优处理的特点利用单调栈处理每个峰,找到最优答案。
而第二道限制了矩形的高度为1,每个位置需要的积木数是一定的,所以h[i]中 <= h[i-1]的部分一定可以被前一个位置顺带覆盖,
若还有h[i] > h[i-1],就说明这一点一定需要再堆h[i]-h[i-1]个积木,否则就不能堆满,所以可以直接递推。
代码
1 #include<iostream> 2 #include<cstdio> 3 4 using namespace std; 5 typedef long long ll; 6 7 ll read(){ 8 ll ans = 0; 9 char last = ‘ ‘,ch = getchar(); 10 while(ch < ‘0‘||‘9‘ < ch)last = ch,ch = getchar(); 11 while(‘0‘ <= ch&&ch <= ‘9‘)ans = ans*10+ch-‘0‘,ch = getchar(); 12 if(last == ‘-‘)return -ans; 13 return ans; 14 } 15 16 const int Maxn = 250010; 17 ll st[Maxn]; 18 ll n,d,top = 0,ans = 0; 19 20 int main(){ 21 n = read(); 22 for(int i = 1;i <= n;i++){ 23 d = read(),d = read(); 24 while(st[top] > d)top--; 25 if(st[top] == d)ans++; 26 st[++top] = d; 27 } 28 cout << n-ans; 29 return 0; 30 }
1 #include<iostream> 2 #include<cstdio> 3 4 using namespace std; 5 6 int last,x,n,ans; 7 8 int main(){ 9 cin >> n; 10 for(int i = 1;i <= n;i++){ 11 cin >> x; 12 if(last < x)ans += x-last; 13 last = x; 14 } 15 cout << ans << ‘\n‘; 16 return 0; 17 }
标签:图片 特点 的区别 char 递推 def 不难 names cout
原文地址:https://www.cnblogs.com/Wangsheng5/p/11406543.html