- The product of all numbers in the first set is less than zero ( < 0).
- The product of all numbers in the second set is greater than zero ( > 0).
- The product of all numbers in the third set is equal to zero.
- Each number from the initial array must occur in exactly one set.
意思就是从一大堆书中选取 3堆数,使得第一堆所有数乘机<0,第二堆数的成绩>0,第三堆数的成绩等于0
这道题困扰了我一个小时~~囧
我的算法是
先分成a,b,c 三堆,然后a存放大于0的,b存放小于0的,c存放0;
然后 (1)若a堆的个数=0,则从b堆中拿出两个放到a堆;
(2) 经过1操作后若b堆的个数为偶数,则取出一个放到c堆中
即可就是最后答案
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
vector<int>first,second,third;
int main(){
int n;
while(scanf("%d",&n)!=EOF){
first.clear();
second.clear();
third.clear();
int num;
for(int i=1;i<=n;i++){
scanf("%d",&num);
if (num<0){
second.push_back(num);
}
if(num>0){
first.push_back(num);
}
if(num==0){
third.push_back(num);
}
}
if( first.size()==0 ){ //操作1
int sum=second.size()-1;
num=second[sum];
second.erase(second.end()-1); //删数应该是最后项-1;
first.push_back(num);
sum=second.size()-1;
num=second[sum];
second.erase(second.end()-1);
first.push_back(num);
}
int sum=second.size();
if( sum%2==0 ){ //操作2
num=second[sum-1];
second.erase(second.end()-1);
third.push_back(num);
}
sort(first.begin(),first.end()); //从小到大排序
sort(second.begin(),second.end());
sort(third.begin(),third.end());
printf("%d",second.size());
for(int i=0;i!=second.size();i++)
printf(" %d",second[i]);
printf("\n");
printf("%d",first.size());
for(int i=0;i!=first.size();i++)
printf(" %d",first[i]);
printf("\n");
printf("%d",third.size());
for(int i=0;i!=third.size();i++)
printf(" %d",third[i]);
printf("\n");
}
}