Your task is to simulate a flood damage.
For a given cross-section diagram, reports areas of flooded sections.
Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides. For example, for the above cross-section diagram, the rain will create floods which have areas of 4, 2, 1, 19 and 9 respectively.
Input
A string, which represents slopes and flatlands by '/', '\' and '_' respectively, is given in a line. For example, the region of the above example is given by a string "\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\".
output
Report the areas of floods in the following format:
AA
kk L1L1 L2L2 ... LkLk
In the first line, print the total area AA of created floods.
In the second line, print the number of floods kk and areas Li(i=1,2,...,k)Li(i=1,2,...,k) for each flood from the left side of the cross-section diagram. Print a space character before LiLi.
Constraints
- 1≤1≤ length of the string ≤20,000≤20,000
Sample Input 1
\\//
Sample Output 1
4 1 4
Sample Input 2
\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\
Sample Output 2
35 5 4 2 1 19 9
问题内容
求出每个积水处的横截面积
思路
利用栈的思想去做
- 如果是’\’则将该字符的位置i压入栈
- 如果是’/’则从栈顶取出与之对应的’\’的位置ipip
- 累加两者距离i−ipi−ip,结果即为总面积
#include<iostream>
#include<stack>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
stack<int>s1;
stack<pair<int, int> >s2;
char ch;
int sum = 0;
for (int i = 0; cin >> ch; i++)
{
if (ch == '\\')
s1.push(i);
else if (ch == '/'&&s1.size() > 0)
{
int j = s1.top();
s1.pop();
sum += i - j;
int a = i - j;
while (s2.size() > 0 && s2.top().first > j)
{
a += s2.top().second;
s2.pop();
}
s2.push(make_pair(j, a));
}
}
vector<int>ans;
while (s2.size() > 0)
{
ans.push_back(s2.top().second);
s2.pop();
}
reverse(ans.begin(), ans.end());
cout << sum << endl;
cout<<ans.size();
for (int i = 0; i < ans.size(); i++)
{
cout << " ";
cout << ans[i];
}
cout << endl;
return 0;
}