n individuals, known to each body weight, canoe load-bearing fixed, each canoe up to two people, can sit a person or two people. It is clear that the total weight does not exceed the load of the canoe, assuming that each person weighs less than the canoe load, how many canoes do I need at least?
Analysis: Greedy algorithm, abstraction of the optimal solution, find out the strategy.
1#include <stdio.h>2 #defineN 100003#include"Array.h"4 voidSortintA[],intn);5 intGetdugout (intA[],intNintm);6 intMain ()7 {8 intA[n];//weight of the person to store9 intn,i,m;Ten intK; Onescanf"%d%d",&n,&m); A for(i=0; i<n;i++) -scanf"%d",&a[i]); - //print (a,n); theSort (a,n);//print (a,n); -k=getdugout (a,n,m); -printf"%d", k); - return 0; + } - voidSortintA[],intN) + { A inti,j,minindex,temp; at for(i=0; i<n-1; i++) - { -minindex=i; - for(j=i+1; j<n;j++) - if(a[minindex]>A[j]) -minindex=J; in if(minindex!=i) - { totemp=A[minindex]; +a[minindex]=A[i]; -a[i]=temp; the } * } $ }Panax Notoginseng intGetdugout (intA[],intNintm) - { the intI=0, j=n-1; + intk=0; A while(i<j| | i==j) the { + //if (i==j&&a[i]<m| | A[I]==M) - //k++; $ if(a[i]+a[j]>m) $ { -k++; -j--; the } - ElseWuyi { thek++; -i++; Wuj--; - } About } $ returnK; -}
C-language Canoe problem