原题: 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);
}
}