您的位置:首页 > 其它

贪心算法—Problem K

2016-03-27 17:05 281 查看
贪心算法—Problem K

题意

有n种颜色(不包括灰色),任意三种颜色各x ml混合可以得到x ml灰色,一整套颜料包括n种颜色,每种50ml,现给出对每种颜色以及灰色的需求量,要求至少需要多少套颜料才能达到要求。

解题思路

首先处理输入的几种颜色(不包括灰色),把他们放入数组中然后再输入的同时找出最大的,根据这个最大的找出至少需要多少套。然后再处理灰色,将找出的最少颜料套数减去需要的颜料得到剩余的颜料,并把它们放入剩余颜料数组中,并降序排列,用剩余的颜料去凑灰色,如果凑不够就加颜料套数,直到凑够为止。在这过程中可设置标志位结束。最后计算出套数。

感想

感觉这题目很难,换了两种思路才勉强AC,继续练习。

AC代码

#include <iostream>
#include <algorithm>
#define Num 15
using namespace std ;

bool cmp(const int &a , const int &b)
{
return a > b ;
}

int max(const int &a , const int &b)
{
if (a > b)  return a ;
else        return b ;
}

int main()
{
int need[Num] , remain[Num] ;
int n,i,j;
int gray;
while (cin >> n, n )
{
int maxx = -1 ;
for (i = 0 ; i < n ; i++ )
{
cin >> need[i] ;
maxx = max (maxx , need[i]) ;
}
cin >> gray ;
int ans = 0 ;
if (maxx%50 == 0)
{
ans = maxx/50 ;
}
else
{
ans = maxx/50 + 1 ;
}
for (i = ans ; ; i++ )
{
int k = gray ;
int flag = 0 ;
for (j = 0 ; j < n ; j++ )
{
remain[j] = i*50 - need[j] ;
}
while (1)
{
sort(remain , remain+n , cmp) ;
if (remain[2] <= 0)
{
if (k <= 0)
flag = 1 ;
break ;
}
k--;
for (j = 0 ; j < 3 ; j++ )
{
remain[j]-- ;
}
}
if(flag)  break ;
}
cout << i << endl ;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: