zoukankan      html  css  js  c++  java
  • 最优装载问题

    问题描述:
    有一批集装箱要装上一艘载重量为c的轮船。其中集装箱i的重量为Wi。最优装载问题要求确定在装载体积不受限制的情况下,将尽可能多的集装箱装上轮船。

    编程任务: 对于给定的n个集装箱和轮船的载重量C,编程计算装入最多时的集装箱个数。

    输入:
    输入由多组测试数据组成。每组测试数据输入的第1行中有2个正整数n和C。正整数n是集装箱个数;正整数C是轮船的载重量。接下来的一行中有n个整数,分别表示n个集装箱的重量,它们之间用空格分隔。其中1<=n<=2000,所有正整数不超过231-1
    输出:
    对应每组输入,输出的每行是计算出的装入最多时的集装箱个数。

    样例输入:
    4 5
    3 5 2 1
    样例输出:
    2

    解决:贪心算法入门题,其实代码可以很短的,就是选择最小的装在里边就行了,但是还是练习下记录哪个装入为好

     1 #include <iostream> 
     2 #include <algorithm> 
     3 #include <bitset> 
     4 using namespace std; 
     5 struct node 
     6 { 
     7     int id; 
     8     int val; 
     9 }; 
    10 node box[2005]; 
    11 int n,c; 
    12 bool operator <(const node &a,const node &b) 
    13 { 
    14     return a.val<b.val; 
    15 } 
    16 void greedySelect() 
    17 { 
    18     sort(box,box+n);               
    19     bitset<2005> b; 
    20     b.reset(); 
    21     for(int i=0;i<n;i++) 
    22      if(box[i].val <= c) 
    23      { 
    24           b[box[i].id]=1; 
    25           c-=box[i].val; 
    26      } 
    27      else break; 
    28      cout<<b.count()<<endl; 
    29 } 
    30 int main() 
    31 { 
    32     while(cin>>n>>c) 
    33     { 
    34         for(int i=0;i<n;i++) 
    35         { 
    36             box[i].id=i; 
    37             cin>>box[i].val; 
    38         } 
    39         greedySelect();  
    40     } 
    41     return 0; 
    42 }

     

  • 相关阅读:
    [笔迹]java范型
    转:APNS设置
    orientation in a UIView add to a UIWindow
    no password for ssh
    webservice soap
    set the region for all annotation
    iOS与Java服务器GZip压缩问题【转】
    useful commands for Mac / iOS
    textView使用总结
    总结(不断更新)
  • 原文地址:https://www.cnblogs.com/liwenbin/p/2830351.html
Copyright © 2011-2022 走看看