C 直方图中最大的矩形
我试图写一个代码来计算直方图中最大矩形的面积和它的顶部坐标。 为了达到这个目的,我使用了堆栈,以便在每个小节的情况下将较小的小节向左和向右移动 根据Geeksforgeks文章中的指南,我遵循以下步骤: 1创建一个空堆栈 2从第一个条开始,对每个条“hist[i]”执行以下操作,其中“i”从0到n-1不等。 ……如果堆栈为空或hist[i]高于堆栈顶部的条,则按“i”键进入堆栈。 ……b如果该条小于堆栈顶部,则在堆栈顶部较大时继续移除堆栈顶部。将移除的条设为hist[tp]。以hist[tp]作为最小条计算矩形的面积。对于hist[tp],“左索引”位于堆栈中tp项之前,“右索引”是“i”当前索引 3如果堆栈不是空的,则逐个从堆栈中移除所有棒,并对每个移除的棒执行步骤2.b 但是我的代码给了我一些任意大的值,怀疑是地址值。 请帮我调试 这是我的密码:`C 直方图中最大的矩形,c,arrays,function,stack,C,Arrays,Function,Stack,我试图写一个代码来计算直方图中最大矩形的面积和它的顶部坐标。 为了达到这个目的,我使用了堆栈,以便在每个小节的情况下将较小的小节向左和向右移动 根据Geeksforgeks文章中的指南,我遵循以下步骤: 1创建一个空堆栈 2从第一个条开始,对每个条“hist[i]”执行以下操作,其中“i”从0到n-1不等。 ……如果堆栈为空或hist[i]高于堆栈顶部的条,则按“i”键进入堆栈。 ……b如果该条小于堆栈顶部,则在堆栈顶部较大时继续移除堆栈顶部。将移除的条设为hist[tp]。以hist[tp]作
#include <stdio.h>
#include <stdlib.h>
void maxRectangle(int hist[], int n);
void push(int stack[],int item,int *top,int n);
int pop(int stack[],int *top);
int peek(int stack[],int *top);
int isEmpty(int top);
int isFull(int top,int n);
void display(int stack[],int top);
int main()
{
int n,i;
printf("How many bars do you want to enter in the histogram?\n");
scanf("%d",&n);
int hist[n];
printf("enter the hights of the consecutive bars\n");
for(i=0;i<n;i++)
{
scanf("%d",&hist[i]);
}
maxRectangle(hist,n);
return 0;
}
void maxRectangle(int hist[], int n)
{
int top=-1;
int i;
int x1,y1,x2,y2;
int max_area,idx, top_area;
int stack[n];
int bar=stack[top];
while(i<n)
{
if(isEmpty(top)||(hist[bar]<hist[i]))
{
push(stack,i,&top,n);i++;
}
else
{
idx=peek(stack,&top); //smaller idx to the right
pop(stack,&top); //bar idx to compute the area for
top_area= hist[idx]*(isEmpty(top)?i:i-peek(stack,&top)-1); //top(stack)is the smaller bar to the left
if(top_area<max_area)
{
max_area=top_area;
x1=(peek(stack,&top)+1);
x2=idx+1;
y1=y2=hist[idx];
}
}
}
printf("the largest area is %d, the top left coordinate is (%d,%d) and top-right coordinate is (%d,%d)\n",max_area,x1,y1,x2,y2);
}
void push(int stack[],int item,int *top,int n)
{
if(isFull(*top,n))
{
printf("stack overflow!!\n");
return;
}
*top=*top+1;
stack[*top]=item;
}
int pop(int stack[],int *top)
{
int item;
if(isEmpty(*top))
{
printf("stack underflow!\n");
exit(1);
}
item=stack[*top];
*top=*top-1;
return item;
}
int peek(int stack[],int *top)
{
if(isEmpty(*top))
{
printf("stack underflow!");
exit(1);
}
return stack[*top];
}
int isEmpty(int top)
{
if(top==-1) return 1;
else return 0;
}
int isFull(int top,int n)
{
if(top==(n-1)) return 1;
else return 0;
}
void display(int stack[],int top)
{
int i;
printf("stack elements are:\n\n");
for(i=top;i>=0;i++)
{
printf("%d\n",stack[i]);
}
printf("\n");
}
`这里有一些东西 int bar=堆栈[顶部];是不好的,因为top=-1 大多数变量都未初始化。这就是它们是奇数值的原因。
isEmptytop | | hist[bar]堆栈[-1]不会有好的结局。您可以在int bar=stack[top]中执行此操作,其中top=-1当您使用调试器时看到了什么?