Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:
- a < b < c;
- a divides b, b divides c.
Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups
of three.
Help Xenia, find the required partition or else say that it doesn't exist.
The first line contains integer n (3 ≤ n ≤ 99999) — the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7.
It is guaranteed that n is divisible by 3.
If the required partition exists, print groups
of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them.
If there is no solution, print -1.
6 1 1 1 2 2 2
-1
6 2 2 1 1 4 6
1 2 41 2 6
思路:从题意中可以推出,有5和7肯定不对,能组成的3个数的组合也是有限的,即(1 2 4,1 2 6,1 3 6)。首先3和4的个数是唯一的,然后为了和4组合需要用掉等数量的2,同理也需要等数量的6,然后如果剩余的2和6的数量相等,就说明可以组成。一开始wa了一发,因为忘了还有1的个数没判断。因为1的个数和6的个数加4的个数总和相等,所以,需要再加个判断。
#include<cstdio>
using namespace std;
int num[10];
int main()
{
int n;
scanf("%d",&n);
for(int i = 0;i < n;i++)
{
int m;
scanf("%d",&m);
num[m]++;
}
int o = 0,p = 0,q = 0;
if(num[5]>0||num[7]>0||num[1]!=num[6]+num[4])
printf("-1\n");
else{
int n4 = num[4];
int n6 = num[6];
int n2 = num[2];
int n3 = num[3];
n2-=n4;
if(n2<0)
printf("-1\n");
else
{
n6 -= n2;
if(n3!=n6)
{
printf("-1\n");
}
else
{
for(int i = 0;i < n4;i++)
printf("1 2 4\n");
for(int i = 0;i < n2;i++)
printf("1 2 6\n");
for(int i = 0;i < n3;i++)
printf("1 3 6\n");
}
}
}
return 0;
}