codeforces 372A. Counting Kangaroos is Fun

A. Counting Kangaroos is Fun
time limit per test 1 second
memory limit per test
256 megabytes
input
standard input
output
standard 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 s i — the size of the i-th kangaroo (1 ≤ s i ≤ 105).
Output

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

8
2
5
7
6
9
8
4
2

Output
Copy

5

Input
Copy

8
9
1
6
2
6
5
8
3

Output
Copy

5
大意:大袋鼠套小袋鼠,只有是自己两倍以上的袋鼠能套自己,每个袋鼠只能套一只,问最后剩下多少袋鼠。
思路:考虑最好情况,即每只大袋鼠都能套到一只,如:1,2,3,4,5,6;最后只剩3只袋鼠,即对半砍后,看看右边最大能否套下左边最大,能的话两个指针-1,否则左边-1,右边不变。
双指针:两个指针起始并不一定都在一边,像这一道题,一个指针在末尾,一个指针在中间,两个指针向左跑。为什么?因为用了贪心的思想,详见注释添加链接描述

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<map>
#define ll long long 
using namespace std;
ll a[5*100000+100];
int main()
{
	ll n;
	scanf("%lld",&n);
	memset(a,0,sizeof(a));
	for(int i=1;i<=n;i++)
		scanf("%lld",&a[i]);
	sort(a+1,a+1+n);
	/*
	for(int i=1;i<=n;i++)
		cout<<a[i]<<" ";
	cout<<endl;
	*/
	ll cnt=0;
	ll r=n;					//右指针
	/*贪心思想   将序列一分为二: 前半部分为小序列 后半部分为大序列,小序列的小对大序列的小, 同,大对大  ,对不起来就移动右指针 */
	for(int i=n/2;i>=1;i--)	//枚举左指针	:不管能否配对 左指针始终每次向左推进
	{
		if(a[i]*2<=a[r])
		{
			//cout<<"l: "<<i<<"r: "<<r<<endl;
			cnt++;
			r--;				//若配对,右指针向左推进;不配对,右指针不动,等待下一个左指针与之配对
		}
	}
	cout<<n-cnt<<endl;
	return 0;
}
/*

*/

2021/4/9
更新双指针代码
注意:中间位置必须是n/2 而不是(n+1)/2

#include <iostream>
#include<bits/stdc++.h>
#define ll long long

using namespace std;
int a[5*100100];
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    sort(a+1,a+1+n);
    int l=n/2;
    int r=n;
    int ans=0;
    while(1)
    {
        //cout<<"l: "<<l<<"  r: "<<r<<"   "<<"ans:  "<<ans<<endl;
        while(l>=1 && a[l]*2<=a[r])
        {
            l--;
            r--;
            ans++;
        }
        if(l<=1)
            break;
        l--;

    }
    cout<<n-ans<<endl;

    return 0;
}

posted @ 2020-07-08 11:59  DuJunlong  阅读(8)  评论(0编辑  收藏  举报  来源