题目(4.6)链接: Areas on the Cross-Section Diagram
栈
- 求积水总面积:
若为"“则将其下标压入栈s1,若为”/“则从栈顶部取出对应”“的位置ip,算出二者的距离i-ip,并累加到总面积里。(不必考虑”_") - 求各积水处的面积:
需要使用结构体(beginx,area),在遇到"/"时,更新栈中原来元素(原来的水坑太小)或压入新元素(遇到新水坑),具体解法键代码。
代码:
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
struct Node
{
int beginx;//左侧开始积水的下标
int area;//积水面积
};
int main()
{
stack<int> s1;
stack<Node> s2;
string s;
int sum = 0;
cin >> s;
for(int i=0; i<s.size(); i++)
{
if(s[i]=='\\')//"\"入栈
{
s1.push(i);
}
else if(s[i]=='/' && !s1.empty())//"/"时,使用s1.top()计算总面积,
{
int j = s1.top(); s1.pop();
sum += i-j;
int a = i-j;
while(s2.size()>0 && s2.top().beginx>j)//若最右边界对应的最左边界小于栈中的最左边界,则更新栈,直到最左边界小于j(即有可能大水坑里有一些小水坑,需要更新到跳出小水坑)
{
a += s2.top().area; s2.pop();
}
Node n;
n.beginx = j;
n.area = a;
s2.push(n);
}
}
cout << sum << endl;
cout << s2.size();
vector<int> s3;
while(!s2.empty())
{
s3.push_back(s2.top().area); s2.pop();
}
reverse(s3.begin(), s3.end());//倒序便于输出
for(vector<int>::iterator it=s3.begin(); it!=s3.end(); it++)
{
cout << " " << *it;
}
cout << endl;
s3.clear();
return 0;
}