Simple optimal loading problem - greedy algorithm

Greedy algorithm - optimal loading problem

Optimal loading problems : a ship load is c, the weight of the container i is Wi, in the case where the volume contained in unrestricted, as many containers loaded on the ship.

Greedy strategy: first container means lightest
time complexity: T (n) = O ( nlogn)
mainly two phases: Sort -> Load

Examples

Problem Description: Xiaoming cousin recommended a number of small learning computer programming video for him, these video playback time length is not exactly the same. Now a given period of time, you can tell Bob he could see the maximum number of videos? (Play time and a given total time for each video units are in minutes)

Entry

The single set of input data
a first behavior Mn
m for a given length of time (minutes) (0 <n, m <= 1000)
n represents the number of video
followed n is an integer representing the playback time of each video (video playback per time is not more than 1000 positive integer)

Sample input

84 6
65 46 18 76 79 3

Export

Output integer representing a number of XP up to see the video.

Sample Output

3

#include<iostream>
#include<algorithm>
#define MAXN 1000005
using namespace std;
int w[MAXN];
int main()
{
	int c,n;
	int sum = 0; 
	int tmp = 0;
	cin >> c >> n;	 
	for(int i= 1; i <= n; ++i)
		cin >> w[i];
	sort(w+1,w+1+n);
	for(int i = 1; i <= n; ++i)
	{
		tmp += w[i];
		if(tmp <= c)
	 		++sum;
		else
			break;
	}
	cout << sum << endl;
	return 0;
} 
Released two original articles · won praise 0 · Views 47

Guess you like

Origin blog.csdn.net/liangsena/article/details/104314083