題目連結
- 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"); } }