flattening

yellow boxes are stacked being adjacent to the wall,making a two-dimensional plane,We call it a 'flattening'to reduce the distance between the highest hight and the lowest height of the boxes by moving boxes in the high positions to the lowest height becomes not more than 1,inclusive.

if the number of times moving boxes for a 'flattening' is limited,write a C function which returns the distance between the highest height and the lowest height of boxes,after moving boxes by limited times.

用冒泡给数组排序。

排完序以后分三种情况讨论。

#include<stdio.h>
#include<stdlib.h>

int test_main(int data[100],int dumpCount);
void build_data(int data[100],int*dumpCount)
{
    for(int i=0;i<100;i++)
    {
        data[i]=rand()%100+1;
    }
    *dumpCount=rand()%1000+1;
}
void main(void)
{
    int data[100];
    int dumpCount;
    for(int l=0;l<10;l++)
    {
        build_data(data,&dumpCount);
        printf("%d
",test_main(data,dumpCount));
    }
}


int test_main(int data[100],int dumpCount)
{
    int dis,p;
    for(p=0;p<dumpCount;p++)
    {
        int m=0,n=0,t;
        for(m=0;m<100;m++)
            {
                for(n=0;n<100-1-m;n++)
                {
                        if(data[n]>data[n+1])
                        {
                            t=data[n];
                            data[n]=data[n+1];
                            data[n+1]=t;
                        }
                }
            }  
                if(data[0]==data[99])
                    {
                        dis=0;
                        break;
                    }
                    else
                        if(data[99]-data[0]==1)
                        {
                            dis=1;
                            break;
                        }
                        else{
                                data[0]=data[0]+1;
                                data[99]=data[99]-1;
                                dis=data[99]-data[0];
                             }
    }
return dis;
}
原文地址:https://www.cnblogs.com/ZzznOoooo/p/6627757.html