CodeForces 372A Counting Kangaroos is Fun 动物PK

原题: http://codeforces.com/problemset/problem/372/A

题目:

Counting Kangaroos is Fun
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo’s pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.

Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.

The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.

Input
The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105).

Output
Output a single integer — the optimal number of visible kangaroos.

Sample test(s)
input
8
2
5
7
6
9
8
4
2
output
5
input
8
9
1
6
2
6
5
8
3
output
5

思路:

找到尽可能多的两满足a*2<=b的一对数数(每个数只能用一次),最后输出总数-对数。

如果我们直接比较并标记,需要用时是O(n^2),并且不一定能找到最优解。
这里的处理办法是先对所有数据排一次序。

显然,对于n个数,最多有n/2组。如下:
这里写图片描述
当n为偶数时,如图,当n为奇数时,我们只需要留下最中间的值即可。

来一组样例:
这里写图片描述
这组数据我们排序后,只需要从最后一位开始比较,比如现在是5和9比较,不满足条件,我们知道,如果最数都找不到比他除以二后小的数,那么就肯定没有了。所以我们先找9的搭配,就让前面的位置前移,找到4和9,满足。这里就有一对了。
找到第一对后,需要同时前移进入新状态,因为每个数只能用一次,这里又找到一对,知道前面的数移到了0的位置。
巧妙的把用时从O(n^2)下降到O(nlogn)+O(n/2),一次快排一次比较。

代码:

#include <iostream>
#include"string.h"
#include"cstdio"
#include"stdlib.h"
#include"algorithm"
using namespace std;
const int N = 500005;
int a[N];


int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        memset(a,0,sizeof(a));
        for(int i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }
        sort(a,a+n);
        int mid=(n-1)/2;
        int big=n-1;
        int small=mid;
        int ok=0;
        while(big>mid&&small>=0)
        {
            if(a[small]*2<=a[big])
            {
                ok++;
                small--;
                big--;
            }
            else
            {
                small--;
            }
        }
        printf("%d\n",n-ok);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值