当前位置:网站首页>【洛谷】P1318 积水面积
【洛谷】P1318 积水面积
2022-07-23 01:49:00 【记录算法题解】
题目地址:
https://www.luogu.com.cn/problem/P1318
题目描述:
一组正整数,分别表示由正方体叠起的柱子的高度。若某高度值为 x x x,表示由 x x x个正立方的方块叠起(如下图, 0 < = x < = 5000 0<=x<=5000 0<=x<=5000)。找出所有可能积水的地方(图中蓝色部分),统计它们可能积水的面积总和(计算的是图中的横截面积。一个立方体的位置,为一个单位面积)。如图:柱子高度变化为0 1 0 2 1 2 0 0 2 0
图中蓝色部分为积水面积,共有 6 6 6个单位面积积水。
输入格式:
两行,第一行 n n n,表示有 n n n个数 ( 3 < = n < = 10000 ) (3<=n<=10000) (3<=n<=10000)。第 2 2 2行连续 n n n个数表示依次由正方体迭起的高度,保证首尾为 0 0 0。
输出格式:
一个数,可能积水的面积。
可以用单调栈。参考https://blog.csdn.net/qq_46105170/article/details/103840733。代码如下:
#include <iostream>
#define x first
#define y second
using namespace std;
using PII = pair<int, int>;
const int N = 10010;
int n, top;
PII stk[N];
int main() {
scanf("%d", &n);
int res = 0;
for (int i = 0; i < n; i++) {
int c;
scanf("%d", &c);
while (top && stk[top - 1].y <= c) {
int h = stk[--top].y;
if (!top) break;
res += (min(stk[top - 1].y, c) - h) * (i - stk[top - 1].x - 1);
}
stk[top++] = {
i, c};
}
printf("%d\n", res);
}
时空复杂度 O ( n ) O(n) O(n)。
边栏推荐
- Repeatable-read RR mode interval lock
- Tidb 3.0安装
- 1058 A+B in Hogwarts
- 肽核酸(PNA)偶联穿膜肽(CCPs)(KFF)3K形成CCPs-PNA|肽核酸的使用方法
- MongoDB的CRUD操作(2)
- Judge whether the two types are the same
- Solve the greatest common divisor and the least common multiple
- mysql的key和index的区别及创建删除索引
- 申请炒股账户在手机开户安全吗?
- Animation demonstration of binary tree implemented by MFC
猜你喜欢

How to learn MySQL efficiently and systematically?

How to determine the end point of a software test

xmpp 服务研究(一)

使用HiFlow场景连接器查看每天处于地区的疫情

线性反馈移位寄存器(LSFR)

35 year old programmer, early middle-aged crisis

Solution of equipment inspection in sewage treatment plant

【无标题】

Installation, configuration and use of sentry

Wallys/DR4019S/IPQ4019/11ABGN/802.11AC/high power
随机推荐
canal 第四篇
virtualbox NAT网络模式配置
PyG利用MessagePassing搭建GCN实现节点分类
Solve the greatest common divisor and the least common multiple
一文搞定C语言指针
网站建设开始前要考虑的7个问题
Developers must see | devweekly issue 1: what is time complexity?
[simple bug handling]
Canal Chapter 5
Emmet 语法简结
Easyv semi annual ranking of "popular content on official websites"
Selenium.webdriver gets the result and converts it to JSON format
Verilog语法基础HDL Bits训练 04
La fosse Piétinée par l'homme vous dit d'éviter les 10 erreurs courantes dans les tests automatisés
污水处理厂设备巡检的解决方案
Is it safe to apply for a stock trading account and open an account on your mobile phone?
博客里程碑
Judge whether it is void type
程序环境和预处理
【C语言】预处理详解