Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2502272
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2011-04-26 17:07:29

    贪心算法,就是总是做出在当前看来是最好的选择的一种方法。
    贪心算法,具备如下的性质:
    1.贪心选择性质;2.最优子结构性质;
    有一批集装箱要装入一个载质量为C的货船,每个集装箱的质量由用户自己输入指定,在货物的装载体积不限的前提下,如何装载集装箱才能尽可能多地将集装箱装入货船中。
  1. #include <stdio.h>

  2. void sort(int w[], int t[], int n)
  3. {
  4.   int i,j,tmp;
  5.   int *w_tmp = (int *)malloc(sizeof(int) * n);
  6.   
  7.   for(i=0;i<n;i++)
  8.   {
  9.     t[i] = i;
  10.   }
  11.   for(i=0;i<n;i++)
  12.   {
  13.     w_tmp[i] = w[i];
  14.   }
  15.   for(i=0;i<n-1;i++)
  16.   {
  17.     for(j=0;j<n-i-1;j++)
  18.     {
  19.       if(w_tmp[j] > w_tmp[j+1])
  20.       {
  21.         tmp = w_tmp[j];
  22.         w_tmp[j] = w_tmp[j+1];
  23.         w_tmp[j+1] = tmp;
  24.         tmp = t[j];
  25.         t[j] = t[j+1];
  26.         t[j+1] = tmp;
  27.       }
  28.     }
  29.   }
  30. }

  31. void loading(int x[], int w[], int c, int n)
  32. {
  33.   int i,s = 0;
  34.   int *t = (int *) malloc(sizeof(int) * n);
  35.   sort(w,t,n);
  36.   for(i=0;i<n;i++)
  37.   {
  38.     x[i] = 0;
  39.   }
  40.   
  41.   for(i = 0; i < n && w[t[i]] <= c; i++)
  42.   {
  43.     x[t[i]] = 1;
  44.     c = c - w[t[i]];
  45.   }
  46. }

  47. int main(int argc, char* argv[])
  48. {
  49.   int x[5],w[5],c,i;
  50.   printf("please input the maximum loading of the sheep\n");
  51.   scanf("%d",&c);
  52.   printf("please input the weight of FIVE box\n");
  53.   for(i = 0; i < 5; i++)
  54.   {
  55.     scanf("%d",&w[i]);
  56.   }
  57.   
  58.   loading(x,w,c,5);
  59.   printf("the following boxes will be loaded\n");
  60.   for(i = 0; i < 5; i++)
  61.   {
  62.     if(x[i] == 1)
  63.     {
  64.       printf("Box:%d ",i);
  65.     }
  66.   }
  67.   printf("\n");
  68. }
执行结果如下:
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./3.8
please input the maximum loading of the sheep
15
please input the weight of FIVE box
2 4 5 6 8
the following boxes will be loaded
Box:0 Box:1 Box:2 

阅读(2823) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~