C - Rain Water trapping

本文介绍了一种使用动态规划算法解决积水计算问题的方法。通过分析铁杆排列形成的地形,计算雨后最大积水单位。文章提供了详细的输入输出示例及代码实现,展示了如何利用左侧和右侧最高石块高度确定各位置的水深。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sai Charan is a professional programmer such that whatever he finds interesting, he would immediately convert it into a problem and try to get an algorithm for it which is the stepping stone for solving a problem. He saw water stagnation infront of his house after a heavy rain. So, he got an idea to write a program to find the amount of water stagnated, which is the inspiration for this problem

Problem Description

 
You are given an iron bar which is of dimension 1 unit. Iron bars are placed in a particular format for each test case, You must display the maximum units of accumulation of water between the iron bars if rainfall has occured in that building.

You can refer to the below image for clear understanding of the problem

Input

  • "The first line of the input contains an integer T denoting the number of test cases
  • "The first line of each test case contains a single integer N denoting the total number of bars that can be arranged horizontally
  • The second line of each test case contains N space-separated integers A0A1, ..., AN-1 denoting the bars which are placed vertically one above the other at each place A0,A1...AN-1 respectively

 

Output

  • For each test case, output a single line containing a single integer max which contains the maximum units of accumulation of water assuming a unit as the place between alternate bars

 

Constraints

  • 1≤ T ≤ 100
  • 1N≤ 1000
  • 1≤ A0,A1,....AN-1 ≤ 1000

 

Example

Input:
2
6
3 0 0 2 0 4
6
3 0 3 3 3 3
Output:
10
3

动态规划的思想:

某位置的水深=min(左侧石块的最高,右侧石块的最高)-该位置的高度;

#include <iostream>
#include <set>
#include <cstdio>
#include <map>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <queue>
#include <vector>
#include <algorithm>
#include <set>
#include <cmath>
#include <limits.h>
using namespace std;
typedef long long LL;
const int maxn=1000+5;
int arr[maxn];
int max_sum[maxn];

int main(){
    int time;
    cin>>time;
    while(time--){
        int n;
        cin>>n;

        int mat[maxn];
        for(int i=0;i<n;i++){
            cin>>mat[i];
        }
        int sum=0;
        for(int i=1;i<n;i++){
            int max1=*max_element(mat,mat+i);
            int max2=*max_element(mat+i,mat+n);
            sum+=(min(max1,max2)-mat[i])>0 ? (min(max1,max2)-mat[i]):0;
        }
        cout<<sum<<endl;
    }


}

哈哈哈,用了黑科技,max_element(begin,end);min_element(begin,end);

注意:1.头文件 #include <algorithm>

 2.返回的是迭代器,想要输出数值,需要加*

3.vj提交的时候语言不要选c++(6.3),要选c++14(6.3),不然会出现错误,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值