贪心算法,重载问题

来源:互联网 发布:简单软件开发工具 编辑:程序博客网 时间:2024/06/16 01:56

算法设计与分析
      1. 用快速排序把随机生成的一组数排序放到数组中。
      2.将排好的数从第一个开始与总的装载重量相比较,如过小于总重量则小标加一,并记录该数,并且将总重量减去第一个数的重量,以此循环。
      3.将下标输出和该数输出,即装载的个数和装的那些数。


说明:运行环境::ubuntu 
input.txt:
6 50
2 3 13 8 80 20
装入的数据是:
2 3 8 13 20
output.txt:
5

源代码:
#include<stdio.h>

#include<stdlib.h>

#include<fcntl.h>

#include<math.h>

#include<time.h>

#define N 20

//快速排序递归,a[]代表数组,low代表数组的第一个数的下标,high代标数组最后一个数的下标

int Partition(int a[],int low,int high)

{

 

        int x=a[low];//将数组的第一个数赋给x

        while(low<high)

        {

                while(a[high]>=x && low<high)//从后往前找比x小的数

                          high--;

                if(low<high)

                {

                        a[low]=a[high];//从后往前找到比x小的数赋给a[low]

                        low++;

                }

                while(a[low]<x && low<high)//从前往后找比x大的数 

                        low++;

                if(low<high)

                {

                        a[high]=a[low];//从前往后找比x大的数赋给a[high]

                        high--;

                }

}

                a[low]=x; 

return low;

 

}

//开速排序

void QuickSort(int a[],int low,int high)

{  

 

      if(low<high)

        {

         int pos=Partition(a,low,high);//递归调用

                QuickSort(a,low,pos-1);

                QuickSort(a,pos+1,high);

        }

 

}

//找出最多可以存储的数,a[]代表数组,low代表数组开始小标 high代表数组最大下标

void maxnumber(int a[],int low,int high)

{

int i,t;

FILE *fp1;

printf("装入的数据分别是:\n");

for(i=low;i<high;i++)

                if(a[i]<a[1])

{

                       printf("%d ",a[i]); 

       a[1]=a[1]-a[i];

}

                else //将结果写入文件

{

fp1=fopen("output.txt","wt");

if(fp1==NULL)

{

printf("Connot open file!");

exit(0);

}

fprintf(fp1,"%d",(i-2));

fclose(fp1);

}

printf("\noutput.txt:\n");

fp1=fopen("output.txt","rt");//读文件

                        if(fp1==NULL)

                        {

                                printf("Connot open file!");

                                exit(0);

                        }

                        i=0;

                        while(fscanf(fp1,"%d",&a[i])!=EOF)

                        {

                                printf("%d\n",a[i]);

                                i++;

                        }

                 fclose(fp1);

 

}

main()

{

FILE *fp;

int i,t,a[N];

printf("input.txt:\n"); //读文件

fp=fopen("input.txt","rt");

if(fp==NULL)

{

printf("Connot open file!");

exit(0);

}

i=0;

while(fscanf(fp,"%d",&a[i])!=EOF)

i++;

t=i;

printf("%d %d\n",a[0],a[1]);

for(i=2;i<t;i++)

printf("%d ",a[i]);

printf("\n");

fclose(fp);

QuickSort(a,2,t);

maxnumber(a,2,t);

}


0 0