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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值