题目
你的任务是模拟洪水灾害。
对于给定的横截面图,给出淹没部分的面积。
假设该地区不断地下雨,而从该地区溢出的水正在落入两侧的海中。 例如,对于上面的横截面图,雨水将产生洪水,其面积分别为 4、2、1、19 和 9。
输入
在一行中给出一个字符串,分别用/
,\
和_
表示斜坡和平原。
例如,上面例子的区域由字符串“\ \ / / / \ _ / \ / \ \ \ \ / _ / \ \ / / / _ _ \ \ \ _ \ \ / _ \ / _ / ”给出。
输出
按以下格式输出:
AK
L1,L2,…,Lk
在第一行,打印出洪水区域的总面积A。
在第二行,打印出洪水区域的个数K和每个区域的面积Li(从左到右)。
约束
1 ≤ length of the string ≤ 20000
样例
输入:\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\
输出:35
5 4 2 1 19 9
思路
因为面积区域的'\'与'/'是一一匹配的,因此采用栈来存储’\‘实现与'/'的匹配。
对于面积的计算,采用一层一层计算面积的策略。对于每层的面积来说,左右两个三角形刚好能凑成一个,也正好可以用左边坐标减去右边的坐标来表示。说到这里就很明朗了,我们可以在入栈出栈的同时将利用'\'与'/'的坐标之差来计算面积,同时将最左边的数值保存下来。当有新的'\'出栈时,让其坐标与现有的左边数值相比,若小于现有最左数值(即在现有最左数值的左侧),则扩大现有区域:更改现有区域最左坐标,增大现有区域面积。否则创建一个新的区域。
根据以上思路可以写出AC代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
/* \\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\ */
typedef struct Node
{
int num;
struct Node* next;
}Node;
typedef struct Stack
{
Node* top;
Node* bottom;
}Stack;
typedef struct Area
{
int st;
int wi;
}Area;
void push_back(Area *a,int x,int y)
{
a->st=x;
a->wi=y;
}
void push(Stack*s,int c)
{
Node* temp=(Node*)malloc(sizeof(Node));
temp->num=c;
temp->next=s->top;
s->top=temp;
if(s->bottom==NULL)
{
s->bottom=temp;
}
}
void pop(Stack*s)
{
Node*temp=s->top;
if(s->top==s->bottom)
{
s->bottom=NULL;
}
s->top=s->top->next;
free(temp);
}
int main()
{
Stack s;
s.bottom=NULL;
s.top=NULL;
char ground[200020];
Area area[200020];
int totalArea=0;
int totalNum=0;
scanf("%s",ground);
for(int i=0;ground[i]!='\0';i++)
{
if(ground[i]=='\\') push(&s,i);
if(ground[i]=='/' && (s.top!=NULL))
{
int left=s.top->num;
pop(&s);
int width=i-left;
totalArea+=width;//一层一层计算
while(totalNum!=0 && area[totalNum-1].st>left)
{
width+=area[totalNum-1].wi;//width相当于面积
totalNum--;
}
push_back(&area[totalNum++],left,width);
}
}
printf("%d\n%d",totalArea,totalNum);
for(int i=0;i<totalNum;i++)
{
printf(" %d",area[i].wi);
}
return 0;
}