贪心--uva11039 building designing

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1980

题目大意:给你n个数,要求取出尽可能多的数构成一个序列使得这个序列满足

(1)正负交替

(2)绝对值递增

其中取数不需要按照输入的顺序。



分析:首先按照绝对值大小从小到大排序。最开始想的是dp,n^2的,很好写,但是500000的数据明显爆炸!!!然后想能不能贪心呢?可以!

对于一个数,假设选取它并且他是个整数。那么下一个数必须选负数,贪心的想:肯定选离它最近的一个负数。有没有更优的方案呢?如果选这个负数的下一个负数,有两种情况:

(1)这两个负数之间都是负数,不影响。

(2)这两个负数之间有正数,那么明显选这两个负数加中间那个正数更优。

贪心成立!


代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
using namespace std;
int a[100005];
int pos[100005];
int neg[100005];
int n,po=0,egg=0;
bool cmp(int a,int b){
	return abs(a)<abs(b);
}
int main(){
	int i,j,k,x;
	memset(a,0,sizeof(a));
	scanf("%d",&n);
	for(i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	sort(a+1,a+1+n,cmp);
	for(i=1;i<=n;i++){
		if(a[i]<0){
			neg[++egg]=-a[i];
		}
		else {
			pos[++po]=a[i];
		}
	}
	i=1,j=1;
	int temp=0,ans=1;
	bool last=true;
	temp=pos[1];
	while(i<=po&&j<=egg){
		if(last==true){
			while(neg[j]<=temp&&j<=egg)j++;
			if(j>egg)break;
			ans++;
			last=false;
			temp=neg[j];
		}
		else{
			while(pos[i]<=temp&&i<=po)i++;
			if(i>po)break;
			ans++;
			last=true;
			temp=pos[i];
		}
	}
	i=1,j=1,temp=0;
	last=false;
	temp=neg[1];
	int ans2=1;
	while(i<=po&&j<=egg){
		if(last==true){
			while(neg[j]<=temp&&j<=egg)j++;
			if(j>egg)break;
			ans2++;
			last=false;
			temp=neg[j];
		}
		else{
			while(pos[i]<=temp&&i<=po)i++;
			if(i>po)break;
			ans2++;
			last=true;
			temp=pos[i];
		}
	}
	printf("%d\n",max(ans,ans2));
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值