caioj:1682: 【greedy】buy one get one free

Topic description

【Question
    CH recently found a hay buy-one-get-one deal on the Internet. For every bale of hay he buys, he can get a bale of hay of size B (1 ≤ B < A) for free. Note that B < A.
    However, there are limits to this sale: the hay that costs money is high-quality, and the hay that is given away for free is inferior. Yet the frugal CH doesn't care about quality: he will buy hay of any quality to save money.
    Given N bales of high quality hay, and M bales of defective hay, find out how many bales CH can buy at most. He can buy high quality hay alone without receiving free defective hay; but he cannot buy inferior hay alone.

[Input description]
    Line 1: Two integers separated by spaces: N and M.
    Lines 2 to N+1: One integer per line, representing the size of a bale of high-quality hay.
    Lines N+2 to N+M+1: One integer per line representing the size of a bale of defective hay.

[Output description]
    The only line: an integer, indicating the maximum number of hay bales that CH can buy.

【Sample input】
3 4
6
1
3
1
5
3
4

[Sample output]
5

【提示】
    样例说明:
    共有3捆高质量的干草,尺寸分别是6,1,和3; 共有4捆次品干草,尺寸分别是1,5,3,和4。
    显然,FJ可以买到所有高质量的干草。当他买尺寸为6的高质量干草时,他可以获赠尺寸为3的次品。当他买尺寸为3的高质量干草时,他可以获赠尺寸为1的次品。然而,当他买质量为1的高质量干草时,无论如何,他都不可能再获赠次品干草。所以答案就是3+2=5。
1 ≤ A ≤ 1,000,000
1 ≤ N ≤ 10,000
1 ≤ M ≤ 10,000

题解:

  这道题十分水,首先高级稻草我们可以全部买齐,每个低级稻草都要配对一个离它最近且比他大的稻草才不会浪费,最后加上能派对上高级稻草的低级稻草的个数


代码(建议自己打):

#include<cstdio>
#include<cstring>
#include<algorithm>
using  namespace  std;
int  a[21000],b[21000],n,m;
int  main()
{
     scanf ( "%d%d" ,&n,&m);
     for ( int  i=1;i<=n;i++) scanf ( "%d" ,&a[i]);
     for ( int  i=1;i<=m;i++) scanf ( "%d" ,&b[i]);
     sort(a+1,a+n+1);
     sort(b+1,b+m+1);
     int  ni=n;//ni表示没配对低级稻草的个数
     for ( int  i=m;i>=1;i--)
     {
         if (ni==0) break ;
         if (b[i]<a[ni])ni--;//如果这颗高级稻草配对了一枚低级稻草,那么把他踢出为匹配队列
     }
     printf ( "%d\n" ,n+n-ni);
     return  0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325683888&siteId=291194637
one
ONE