Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:
- 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.
Help Vitaly. Divide the given array.
The first line of the input contains integer n (3 ≤ n ≤ 100). The second line contains n space-separated distinct integers a1, a2, ..., an (|ai| ≤ 103) — the array elements.
In the first line print integer n1 (n1 > 0) — the number of elements in the first set. Then print n1 numbers — the elements that got to the first set.
In the next line print integer n2 (n2 > 0) — the number of elements in the second set. Then print n2 numbers — the elements that got to the second set.
In the next line print integer n3 (n3 > 0) — the number of elements in the third set. Then print n3 numbers — the elements that got to the third set.
The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.
3 -1 2 0
1 -1 1 2 1 0
4 -1 -2 -3 0
1 -1 2 -3 -2 1 0
题意:给一个数组,把它分成3个集合,第一个集合的乘积<0;第二个大于0;第三个等于0;
题解:先排序,后分情况 有4种情况
1 小于0的元素个数是奇数,存在大于零的数
2 小于0的元素个数是奇数,不存在大于零的数
3 小于0的元素个数是偶数,存在大于零的数
4 小于0的元素个数是偶数,不存在大于零的数
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int al,ab,n,i,d[113];
while(scanf("%d",&n)!=EOF)
{
al=0,ab=0;
for(i=0;i<n;i++){
scanf("%d",&d[i]);
if(d[i]<0)
al++;
if(d[i]>0)
ab++;
}
sort(d,d+n);
if(al&1) {
if(d[n-1]>0){
printf("1 %d\n",d[0]);
printf("%d",n-2);
for(i=1;i<n;i++){
if(d[i]==0) continue;
printf(" %d",d[i]);
}
printf("\n");
printf("1 0\n");
}
else {
printf("1 %d\n",d[0]);
printf("%d",n-2);
for(i=1;i<n-1;i++){
printf(" %d",d[i]);
}
printf("\n");
printf("1 0\n");
}
}
else{
if(d[n-1]>0){
printf("1 %d\n",d[0]);
printf("%d",ab);
for(i=al+1;i<n;i++){
printf(" %d",d[i]);
}
printf("\n");
printf("%d 0",al);
for(i=1;i<al;i++){
printf(" %d",d[i]);
}
printf("\n");
}
else {
printf("1 %d\n",d[0]);
printf("%d",al-2);
for(i=2;i<al;i++){
printf(" %d",d[i]);
}
printf("\n");
printf("2 0 %d\n",d[1]);
}
}
}
return 0;
}