XM22. 计算题
描述
输入描述
逗号分隔的整数,表示每根柱子的高度。输出描述
雨水量(高度和)示例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; }