1512D - Corrupted Array - CodeForces Solution


constructive algorithms data structures greedy *1200

Please click on ads to support us..

Python Code:

from math import log
from math import ceil
import os
import sys
from collections import Counter as ctr, deque as dq,defaultdict as dd
from io import BytesIO, IOBase
from types import GeneratorType

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0
 
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None
 
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
 
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
 
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
 
 
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda: self.buffer.read().decode('ascii')
        self.readline = lambda: self.buffer.readline().decode('ascii')
 
 
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
 
from bisect import bisect_left as bl
from bisect import bisect_right as br

inp = lambda: int(input())
li = lambda: list(map(int, input().split()))
lb = lambda: list(map(int, input()))
ls = lambda: list(input())
bi = lambda n: bin(n).replace("0b", "")

def yn(f):
    if f:
        print("YES")
    else:
        print("NO")

def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to
 
    return wrappedfunc

def isPrime(n):
    if n <= 1:
        return True
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i = i + 6
    return True

def nf(n,a):
    b=a*a
    c=b*a
    d=c*a
    e=n
    ct=0
    while e%a==0:
        if e%d==0:
            ct+=4
            e=e//d
        if e%c==0:
            ct+=3
            e=e//c
        if e%b==0:
            ct+=2
            e=e//b
        if e%a==0:
            ct+=1
            e=e//a
    return ct

def main(__=1):
    for _ in range(__):
        n=inp()
        a=sorted(li())
        s=sum(a[:n+1])
        if s>a[-1] and (s-a[-1]) in a[:n+1]:
            f=False
            for i in range(n+1):
                if a[i]!=(s-a[-1]) or f:
                    print(a[i],end=" ")
                else:
                    f=True
            print()
        elif s-a[-2] == a[-2]:
            print(*a[:n])
        else:
            print(-1)

        

if __name__ == "__main__":
        main(inp())

C++ Code:

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

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<char,int> pci;
typedef map<int,int> mapii;
typedef vector<int> vi;

#define fastIO  ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define int long long
#define endl "\n"
#define space " "
#define printbay(a, n)  for(int i=0;i<n;i++)    cout<<a[i]<<space;    cout<<endl;

const int MOD = 1e9 + 7;

//---------------------------------------------------------------------------------------------------//

long long power(int aa, int n, int m = MOD) 
{
    long long ans = 1LL;
    while(n) {
        if(n&1) ans = 1LL * (ans%m * aa%m)%m;
        aa = (1LL*aa%m * aa%m)%m;
        n >>= 1;
    }
    return ans;
}

long long gcd(long long a, long long b)
{
    return b == 0 ? a : gcd(b, a % b);
    //O(log(min(a,b)), O(log(min(a,b))
}

long long LCM(int a, int b)
{
    return a*b/gcd(a,b);
}


long long factorial(int n)
{
    if (n >= MOD)
        return 0;
 
    int result = 1;
    for (int i = 1; i <= n; i++)
        result = (result * i) % MOD;
 
    return result;
}

static bool cmp(pair<int,int> a, pair<int,int> b)
{
    if (a==b)
    {
        return a.second<b.second;
    }
    
    return a.first<b.first;
}

//---------------------------------------------------------------------------------------------------//

void solve()
{
    int n;
    cin>>n;

    int b[n+2];
    int totalSum=0;
    for(int i=0;i<n+2;i++)
    {
        cin>>b[i];
        totalSum+=b[i];
    }

    sort(b, b+n+2);
    int greatest=b[n+1];
    int secondGreatest=b[n];
    
    int k=2;
    int sumIndex=n+1;
    while(k--)
    {
        int requiredSum=b[sumIndex];
        for(int i=0;i<n+2;i++)
        {
            if (i!=sumIndex)
            {
                if (totalSum-requiredSum-b[i]==requiredSum)
                {
                    //got an answer
                    for(int j=0;j<n+2;j++)
                    {
                        if (j!=sumIndex && j!=i)
                        {
                            cout<<b[j]<<space;
                        }
                    }
                    cout<<endl;
                    return;
                }
            }
        }

        sumIndex--;
    }

    cout<<-1<<endl;
}

int32_t main()
{
    fastIO;
    int t;
    cin>>t;
    while(t--)
    {
        solve();


    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

977. Squares of a Sorted Array
852. Peak Index in a Mountain Array
461. Hamming Distance
1748. Sum of Unique Elements
897. Increasing Order Search Tree
905. Sort Array By Parity
1351. Count Negative Numbers in a Sorted Matrix
617. Merge Two Binary Trees
1450. Number of Students Doing Homework at a Given Time
700. Search in a Binary Search Tree
590. N-ary Tree Postorder Traversal
589. N-ary Tree Preorder Traversal
1299. Replace Elements with Greatest Element on Right Side
1768. Merge Strings Alternately
561. Array Partition I
1374. Generate a String With Characters That Have Odd Counts
1822. Sign of the Product of an Array
1464. Maximum Product of Two Elements in an Array
1323. Maximum 69 Number
832. Flipping an Image
1295. Find Numbers with Even Number of Digits
1704. Determine if String Halves Are Alike
1732. Find the Highest Altitude
709. To Lower Case
1688. Count of Matches in Tournament
1684. Count the Number of Consistent Strings
1588. Sum of All Odd Length Subarrays
1662. Check If Two String Arrays are Equivalent
1832. Check if the Sentence Is Pangram
1678. Goal Parser Interpretation