Array CodeForces - 300A - 数学
Array CodeForces - 300A
维塔利有一个由 n 个不同整数组成的数组,她希望将此数组划分为三个非空集,以便满足以下条件:
- 第一组中所有数字的乘积小于零( < 0).
- 第二组中所有数字的乘积大于零( > 0).
- 第三组中所有数字的乘积等于零。
- 初始数组中的每个数字必须恰好出现在一个集合中。
帮助维塔利。对给定数组进行分类。
Input
输入的第一行包含整数 n(3 ≤ n ≤ 100).
第二行包含 n 个用空格分隔的不同整数a1,a2,..., an(|ai| ≤ 1e3)- 数组元素。
Output
在第一行打印整数 n1(n1 > 0)-第一组中的元素数。
然后打印 n1 个数字-到达第一组的元素。
在下一行中打印整数 n2(n2 > 0)-第二组中的元素数。
然后打印 n2 个数字-进入第二组的元素。
在下一行中打印整数 n3(n3 > 0)-第三组元素的数量。
然后打印 n3 个数字-进入第三组的元素。
打印集必须符合所述条件。可以保证解决方案存在。
如果有多个解决方案,您可以打印其中任何一个。
Sample Input1
3
-1 2 0
Sample Output1
1 -1
1 2
1 0
Sample Input2
4
-1 -2 -3 0
Sample Output2
1 -1
2 -3 -2
1 0
分析
三个集合都不为空,且
- 集合 1:含有 2N+1 个负数。
- 集合 2:含有 2N 个负数。
- 集合 3:含有 0。
考虑将 负数,正数,0 分为三个集合,之后判断是否满足条件,再分配即可。
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e6+10,INF=0x3f3f3f3f;
int n,a[N];
int main(){
// freopen("data.in", "r", stdin);
while(cin>>n){
multiset<int> s1,s2,s3;
for(int i=1; i<=n; i++) cin>>a[i];
for(int i=1; i<=n; i++) {
if(a[i] < 0) s1.insert(a[i]);
else if(a[i] > 0) s2.insert(a[i]);
else if(a[i]==0) s3.insert(a[i]);
}
if(s2.size()==0) {
s2.insert(*s1.begin()),s1.erase(s1.begin());
s2.insert(*s1.begin()),s1.erase(s1.begin());
}
if(s1.size()%2==0){
s3.insert(*s1.begin()),s1.erase(s1.begin());
}
cout<<s1.size();
for(auto u:s1) cout<<" "<<u; cout<<endl;
cout<<s2.size();
for(auto u:s2) cout<<" "<<u; cout<<endl;
cout<<s3.size();
for(auto u:s3) cout<<" "<<u; cout<<endl;
}
return 0;
}

浙公网安备 33010602011771号