列表

详情


XM22. 计算题

描述

给定n个非负整数表示每个宽度为1的柱子的高度题,计算按此排列的柱子,下雨之后能接多少雨水。

输入描述

逗号分隔的整数,表示每根柱子的高度。
柱子数n<=1000000,每根柱子的高度不大于100000

输出描述

雨水量(高度和)

示例1

输入:

0,1,0,2,1,0,1,3,2,1,2,1

输出:

6

原站题解

C++ 解法, 执行用时: 28ms, 内存消耗: 4608KB, 提交时间: 2022-07-06

#include <iostream>
#include <vector>
using namespace std;
int main(){
    vector<int> arr;
    char c;
    int flag=0;
    while((c=getchar())!='\n'){
        if(c!=',')flag=flag*10+(c-'0');
        else{
            arr.push_back(flag);
            flag=0;
        }
    }
    arr.push_back(flag);
    int i=0,j=arr.size()-1;
    int leftmax=0,rightmax=0;
    long ans=0;
    while(i<j){
        leftmax=max(leftmax,arr[i]);
        rightmax=max(rightmax,arr[j]);
        if(leftmax<rightmax){
            ans+=leftmax-arr[i];
            i++;
        }else{
            ans+=rightmax-arr[j];
            j--;
        }
    }
    cout<<ans<<endl;
    return 0;
}

C++ 解法, 执行用时: 32ms, 内存消耗: 4572KB, 提交时间: 2020-09-09

#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector<int> Heights;
    char c;
    int flag = 0;
    while((c = getchar()) != '\n'){
        if(c != ','){
            flag = flag * 10 + (c - '0');
        }
        else {
            Heights.push_back(flag);
            flag = 0;
        }
    }
    Heights.push_back(flag);
    long Sum = 0;
    int len=Heights.size();
     
    int left = 0;
    //variable left represents the left border of the area where can contain water
    while(left < len - 1 && Heights[left + 1] >= Heights[left]) {
        left++;
    }
    int right = len - 1;
    //variable right represents the right border of the area where can contain water
    while(right >= 1 && Heights[right - 1] >= Heights[right]) {
        right--;
    }
    while(left < right) {
        int leftHeight = Heights[left];
        int rightHeight = Heights[right];
        if(leftHeight <= rightHeight) {
            while(left < right) {
                left++;
                if(Heights[left] < leftHeight) {
                    Sum += leftHeight - Heights[left];
                }else {
                    break;
                }
            }
        }else {
            while(left < right) {
                right--;
                if(Heights[right] < rightHeight) {      
                    Sum += rightHeight - Heights[right];
                }else {
                    break;
                }
            }
        }
    }
    cout<<Sum<<endl;
    return 0;
}

上一题