342A - Xenia and Divisors - CodeForces Solution


greedy implementation *1200

Please click on ads to support us..

Python Code:

from collections import Counter
n = int(input())
arr = list(map(int, input().split()))
ans = []
c = Counter(arr)
for i in range((n//3) + 1):
    if c[4] > 0 and c[2] > 0 and c[1] > 0:
        ans.append(['1', '2', '4'])
        c[4] -= 1
        c[2] -= 1
        c[1] -= 1
    elif c[6] > 0 and c[2] > 0 and c[1] > 0:
        ans.append(['1', '2', '6'])
        c[6] -= 1
        c[2] -= 1
        c[1] -= 1
    elif c[6] > 0 and c[3] > 0 and c[1] > 0:
        ans.append(['1', '3', '6'])
        c[6] -= 1
        c[3] -= 1
        c[1] -= 1
if any(x > 0 for x in c.values()):
    print(-1)
else:
    for group in ans:
        print(' '.join(group))

C++ Code:

#include<bits/stdc++.h>
using namespace std;

int main(){
    int n;
    cin>>n;
    int x[n];
    int a=0,b=0,c=0,d=0,e=0;
    for(int i=0;i<n;i++){
        cin>>x[i];
        if(x[i]==1){
            a++;
        }
        else if(x[i]==2){
            b++;
        }
        else if(x[i]==3){
            c++;
        }
        else if(x[i]==4){
            d++;
        }
        else if(x[i]==6){
            e++;
        }
    }
    if((a==n/3) && (b+c==n/3) && (d+e==n/3)){
        if((b>=d) && (e>=c)){
            for(int i=0;i<d;i++){
                cout<<1<<" "<<2<<" "<<4<<endl;
            }
            b=b-d;
            for(int i=0;i<b;i++){
                cout<<1<<" "<<2<<" "<<6<<endl;
            }
            e=e-b;
            for(int i=0;i<e;i++){
                cout<<1<<" "<<3<<" "<<6<<endl;
            }
        }
        else{
            cout<<-1<<endl;
        }
    }
    else{
        cout<<-1;
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

13. Roman to Integer
2. Add Two Numbers
515. Find Largest Value in Each Tree Row
345. Reverse Vowels of a String
628. Maximum Product of Three Numbers
1526A - Mean Inequality
1526B - I Hate 1111
1881. Maximum Value after Insertion
237. Delete Node in a Linked List
27. Remove Element
39. Combination Sum
378. Kth Smallest Element in a Sorted Matrix
162. Find Peak Element
1529A - Eshag Loves Big Arrays
19. Remove Nth Node From End of List
925. Long Pressed Name
1051. Height Checker
695. Max Area of Island
402. Remove K Digits
97. Interleaving String
543. Diameter of Binary Tree
124. Binary Tree Maximum Path Sum
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
501A - Contest
160A- Twins
752. Open the Lock
1535A - Fair Playoff
1538F - Interesting Function
1920. Build Array from Permutation
494. Target Sum