题目链接: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));
}