算法題_遊戲揹包問題

題目:
在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

思路: 我們可以使用貪心算法,時間複雜度爲O(n)。

接下來我們用C++進行編程:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e3;
vector<int> hostc;
vector<int> hostw;

int main(){
	int n, m;
	while(cin >> n >> m)
	{
		for(int i = 0; i < n; i++)
		{
			int c, w;
			cin >> c >> w;
			hostc.push_back(c);
			hostw.push_back(w);
		}
		ll energy = 0;
		int coins = 0;
		for(int i = 0; i < n; i++)
		{
			if(1ll * hostw[i] * m > hostc[i])
			{
				energy += hostc[i];
				coins += hostw[i];
			}
		}
		int result = coins - energy / m;
		if(energy % m != 0)
			result -= 1;
		cout << result << endl;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章