GMINEQ-Editorial

PROBLEM LINK:

Contest Division 1
Contest Division 2
Contest Division 3
Contest Division 4

Setter: Hriday
Tester: Aryan, Satyam
Editorialist: Devendra Singh

DIFFICULTY:

1254

PREREQUISITES:

None

PROBLEM:

You are given an array A of length N containing the elements -1 and 1 only. Determine if it is possible to rearrange the array A in such a way that A_i is not the geometric mean of A_{i-1} and A_{i+1}, for all i such that 2 \leq i \leq N-1.

Y is said to be the geometric mean of X and Z if Y^2 = X \cdot Z.

EXPLANATION:

An observation: A_i and A_{i+2} cannot be equal as then A_i \cdot A_{i+2} = A_i^2 = 1 = A_{i+1}^2, independent of the value of A_i and A_{i+1} ( as they can be 1 and -1 only )
This means if we fix A_0 all values at even indices can be retrieved using the formula
A_i=-A_{i-2}. Similarly if we fix A_1 all values at odd indices can be retrieved with the same formula.
There are four combinations for first two values and they are [1,1] , [1,-1] , [-1,1] , [-1,-1]. We can generate four different sequences of length N using these four combinations and then check if one of them is an arrangement of the given array.

TIME COMPLEXITY:

O(N) for each test case.

SOLUTION:

Tester-1's Solution
/* in the name of Anton */

/*
  Compete against Yourself.
  Author - Aryan (@aryanc403)
  Atcoder library - https://atcoder.github.io/ac-library/production/document_en/
*/

#ifdef ARYANC403
    #include <header.h>
#else
    #pragma GCC optimize ("Ofast")
    #pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
    //#pragma GCC optimize ("-ffloat-store")
    #include<bits/stdc++.h>
    #define dbg(args...) 42;
#endif

// y_combinator from @neal template https://codeforces.com/contest/1553/submission/123849801
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0200r0.html
template<class Fun> class y_combinator_result {
    Fun fun_;
public:
    template<class T> explicit y_combinator_result(T &&fun): fun_(std::forward<T>(fun)) {}
    template<class ...Args> decltype(auto) operator()(Args &&...args) { return fun_(std::ref(*this), std::forward<Args>(args)...); }
};
template<class Fun> decltype(auto) y_combinator(Fun &&fun) { return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun)); }

using namespace std;
#define fo(i,n)   for(i=0;i<(n);++i)
#define repA(i,j,n)   for(i=(j);i<=(n);++i)
#define repD(i,j,n)   for(i=(j);i>=(n);--i)
#define all(x) begin(x), end(x)
#define sz(x) ((lli)(x).size())
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define endl "\n"

typedef long long int lli;
typedef long double mytype;
typedef pair<lli,lli> ii;
typedef vector<ii> vii;
typedef vector<lli> vi;

const auto start_time = std::chrono::high_resolution_clock::now();
void aryanc403()
{
#ifdef ARYANC403
auto end_time = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end_time-start_time;
    cerr<<"Time Taken : "<<diff.count()<<"\n";
#endif
}

long long readInt(long long l, long long r, char endd) {
    long long x=0;
    int cnt=0;
    int fi=-1;
    bool is_neg=false;
    while(true) {
        char g=getchar();
        if(g=='-') {
            assert(fi==-1);
            is_neg=true;
            continue;
        }
        if('0'<=g&&g<='9') {
            x*=10;
            x+=g-'0';
            if(cnt==0) {
                fi=g-'0';
            }
            cnt++;
            assert(fi!=0 || cnt==1);
            assert(fi!=0 || is_neg==false);

            assert(!(cnt>19 || ( cnt==19 && fi>1) ));
        } else if(g==endd) {
            if(is_neg) {
                x=-x;
            }
            assert(l<=x&&x<=r);
            return x;
        } else {
            assert(false);
        }
    }
}
string readString(int l, int r, char endd) {
    string ret="";
    int cnt=0;
    while(true) {
        char g=getchar();
        assert(g!=-1);
        if(g==endd) {
            break;
        }
        cnt++;
        ret+=g;
    }
    assert(l<=cnt&&cnt<=r);
    return ret;
}
long long readIntSp(long long l, long long r) {
    return readInt(l,r,' ');
}
long long readIntLn(long long l, long long r) {
    return readInt(l,r,'\n');
}
string readStringLn(int l, int r) {
    return readString(l,r,'\n');
}
string readStringSp(int l, int r) {
    return readString(l,r,' ');
}

void readEOF(){
    assert(getchar()==EOF);
}

vi readVectorInt(int n,lli l,lli r){
    vi a(n);
    for(int i=0;i<n-1;++i)
        a[i]=readIntSp(l,r);
    a[n-1]=readIntLn(l,r);
    return a;
}

bool isBinaryString(const string s){
    for(auto x:s){
        if('0'<=x&&x<='1')
            continue;
        return false;
    }
    return true;
}

// #include<atcoder/dsu>
// vector<vi> readTree(const int n){
//     vector<vi> e(n);
//     atcoder::dsu d(n);
//     for(lli i=1;i<n;++i){
//         const lli u=readIntSp(1,n)-1;
//         const lli v=readIntLn(1,n)-1;
//         e[u].pb(v);
//         e[v].pb(u);
//         d.merge(u,v);
//     }
//     assert(d.size(0)==n);
//     return e;
// }

const lli INF = 0xFFFFFFFFFFFFFFFL;

lli seed;
mt19937 rng(seed=chrono::steady_clock::now().time_since_epoch().count());
inline lli rnd(lli l=0,lli r=INF)
{return uniform_int_distribution<lli>(l,r)(rng);}

class CMP
{public:
bool operator()(ii a , ii b) //For min priority_queue .
{    return ! ( a.X < b.X || ( a.X==b.X && a.Y <= b.Y ));   }};

void add( map<lli,lli> &m, lli x,lli cnt=1)
{
    auto jt=m.find(x);
    if(jt==m.end())         m.insert({x,cnt});
    else                    jt->Y+=cnt;
}

void del( map<lli,lli> &m, lli x,lli cnt=1)
{
    auto jt=m.find(x);
    if(jt->Y<=cnt)            m.erase(jt);
    else                      jt->Y-=cnt;
}

bool cmp(const ii &a,const ii &b)
{
    return a.X<b.X||(a.X==b.X&&a.Y<b.Y);
}

const lli mod = 1000000007L;
// const lli maxN = 1000000007L;

    lli T,n,i,j,k,in,cnt,l,r,u,v,x,y;
    lli m;
    string s;
    vi a;
    //priority_queue < ii , vector < ii > , CMP > pq;// min priority_queue .

int main(void) {
    ios_base::sync_with_stdio(false);cin.tie(NULL);
    // freopen("txt.in", "r", stdin);
    // freopen("txt.out", "w", stdout);
// cout<<std::fixed<<std::setprecision(35);
T=readIntLn(1,200);
while(T--)
{

    n=readIntLn(3,1000);
    a=readVectorInt(n,-1,1);
    for(auto x:a)
        assert(abs(x)==1);
    sort(all(a));
    bool fl=false;
    vi b(n);
    for(auto p0:{-1,1})
        for(auto p1:{-1,1}){
            b[0]=p0;
            b[1]=p1;
            for(lli i=2;i<n;i++)
                b[i]=-b[i-2];
            sort(all(b));
            if(a==b)
                fl=true;
        }

    cout<<(fl?"yEs":"nO")<<endl;
}   aryanc403();
    readEOF();
    return 0;
}

Tester-2's Solution
#include <bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE    
#define debug(x) cerr<<#x<<" "; _print(x); cerr<<nline;
#else
#define debug(x);  
#endif 
#define ll long long
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());  
 
 
/*
------------------------Input Checker----------------------------------
*/
 
long long readInt(long long l,long long r,char endd){
    long long x=0;
    int cnt=0;
    int fi=-1;
    bool is_neg=false;  
    while(true){
        char g=getchar();
        if(g=='-'){  
            assert(fi==-1);
            is_neg=true;
            continue;
        }
        if('0'<=g && g<='9'){
            x*=10;
            x+=g-'0';
            if(cnt==0){
                fi=g-'0';
            }
            cnt++;
            assert(fi!=0 || cnt==1);
            assert(fi!=0 || is_neg==false);
 
            assert(!(cnt>19 || ( cnt==19 && fi>1) ));
        } else if(g==endd){
            if(is_neg){
                x= -x;
            }
 
            if(!(l <= x && x <= r))
            {
                cerr << l << ' ' << r << ' ' << x << '\n';
                assert(1 == 0);
            }
 
            return x;
        } else {
            assert(false);
        }
    }
}
string readString(int l,int r,char endd){
    string ret="";
    int cnt=0;
    while(true){
        char g=getchar();
        assert(g!=-1);
        if(g==endd){
            break;
        }
        cnt++;
        ret+=g;
    }
    assert(l<=cnt && cnt<=r);
    return ret;
}
long long readIntSp(long long l,long long r){
    return readInt(l,r,' ');
}
long long readIntLn(long long l,long long r){
    return readInt(l,r,'\n');
}
string readStringLn(int l,int r){
    return readString(l,r,'\n');
}
string readStringSp(int l,int r){
    return readString(l,r,' ');
}
 
 
/*
------------------------Main code starts here----------------------------------
*/
ll MAX=100000;
ll tes_sum=0;
vector<string> YS={"YES","yes","yES","YeS","yEs","YEs","Yes","yeS"};
vector<string> NO={"NO","no","No","nO"}; 
void solve(){  
    ll n=readIntLn(3,MAX);
    ll x; map<ll,ll> freq; 
    for(ll i=1;i<n;i++){  
        x=readIntSp(-1,1);
        freq[x]++; 
    }
    x=readIntLn(-1,1);
    freq[x]++;
    assert((freq[-1]+freq[1])==n); 
    ll l=(n+1)/2,r=n/2;
    vector<ll> a={(l+1)/2,l/2},b={(r+1)/2,r/2};
    for(auto i:a){
        for(auto j:b){
            if(i+j==freq[1]){
                cout<<YS[rng()%8]<<"\n";
                return;
            }
        }
    }
    cout<<NO[rng()%4]<<"\n";
    return;
}
int main(){  
    ios_base::sync_with_stdio(false);                         
    cin.tie(NULL);                              
    #ifndef ONLINE_JUDGE                 
    freopen("input.txt", "r", stdin);                                              
    freopen("output.txt", "w", stdout);  
    freopen("error.txt", "w", stderr);                          
    #endif         
    ll test_cases=readIntLn(1,200); 
    while(test_cases--){
        solve();
    }
    assert(getchar()==-1);
    return 0;
}

Editorialist's Solution
#include "bits/stdc++.h"
using namespace std;
#define ll long long
#define pb push_back
#define all(_obj) _obj.begin(), _obj.end()
#define F first
#define S second
#define pll pair<ll, ll>
#define vll vector<ll>
const int N = 1e5 + 11, mod = 1e9 + 7;
ll max(ll a, ll b) { return ((a > b) ? a : b); }
ll min(ll a, ll b) { return ((a > b) ? b : a); }
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
void sol(void)
{
    bool can = false;
    int cntone = 0, cntminusone = 0, n, a;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> a;
        cntone += (a == 1);
        cntminusone += (a == -1);
    }
    int tcntone = 0, tcntminusone = 0;
    int arr[n];
    arr[0] = arr[1] = 1;
    tcntone = 2;
    for (int i = 2; i < n; i++)
    {
        arr[i] = -arr[i - 2];
        tcntone += (arr[i] == 1);
        tcntminusone += (arr[i] == -1);
    }
    if (tcntone == cntone && tcntminusone == cntminusone)
        can = true;
    arr[0] = -1, arr[1] = 1;
    tcntone = tcntminusone = 1;
    for (int i = 2; i < n; i++)
    {
        arr[i] = -arr[i - 2];
        tcntone += (arr[i] == 1);
        tcntminusone += (arr[i] == -1);
    }
    if (tcntone == cntone && tcntminusone == cntminusone)
        can = true;
    arr[0] = 1, arr[1] = -1;
    tcntone = tcntminusone = 1;
    for (int i = 2; i < n; i++)
    {
        arr[i] = -arr[i - 2];
        tcntone += (arr[i] == 1);
        tcntminusone += (arr[i] == -1);
    }
    if (tcntone == cntone && tcntminusone == cntminusone)
        can = true;
    arr[0] = arr[1] = -1;
    tcntminusone = 2;
    tcntone=0;
    for (int i = 2; i < n; i++)
    {
        arr[i] = -arr[i - 2];
        tcntone += (arr[i] == 1);
        tcntminusone += (arr[i] == -1);
    }
    if (tcntone == cntone && tcntminusone == cntminusone)
        can = true;
     if(can)
     cout<<"Yes\n";
     else
     cout<<"No\n";
    return;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL), cout.tie(NULL);
    int test = 1;
    cin >> test;
    while (test--)
        sol();
}

Solution based on observation:-

  1. For every N>=4 we need 2 different parity elements for every 4 elements in the given sequence
    Ex. N =5
(1, -1, -1, 1, 1) 1= 3 -1= 2
(1, 1, -1, -1, 1) 1= 3 -1= 2
(-1, -1, 1, 1, -1) 1= 2 -1= 3
(-1, 1, 1, -1, -1) 1= 2 -1= 3

Here at every 4 elements we require 2 different parity elements (1,1) or (-1,-1)

  1. For Every N >=4 if N is divisible by 2 then we can arrange the elements as
    Ex. N = 6
6 (1, 1, -1, -1, 1, 1) 1= 4 -1= 2
6 (-1, 1, 1, -1, -1, 1) 1= 3 -1= 3
6 (1, -1, -1, 1, 1, -1) 1= 3 -1= 3
6 (-1, -1, 1, 1, -1, -1) 1= 2 -1= 4
  1. For every N >=4 if N %4 == 3 then we need “-1” or “1” to arrange the element in given condition

based on the observation :-
The code :

# cook your dish here
for _ in range(int(input())):
  N = int(input())
  li = list(map(int, input().split()))
  # counting 1
  poz = li.count(1)
  # counting -1
  neg = li.count(-1)
  summ = sum(li)
  # 1/-1 needed per 4 elements
  neededCountPerFour = 2
  ans = 0
  # handling N =3 separatly
  if N == 3:
    if summ == 3 or summ == -3:
      print('No')
    else:
      print('Yes')
  # logic based on observations
  else:
    if N%4 == 3:
      ans = (neededCountPerFour*(N//4)) +1
    else:
      ans = (neededCountPerFour*(N//4))
    # `ans` contains the requied no of 1/-1 for the sequence to be become non geometric.
    if (ans == poz or ans == neg) or (poz == neg):
      print('Yes')
    else:
      print('No')
1 Like

I tried it with a simpler observation approach.

I observed that:

  1. In every consecutive four, there is an equal number of 1 and -1 present.
  2. For each case when N is divisible by 4, the difference must be 0.
  3. For other cases, the absolute difference between the count of 1 and -1 must be lesser than or equal to 2.
    (i) For N%4==1 and N%4==3, the absolute difference must be 1.
    (ii) For N%4==2, the absolute difference can be 0 and 2.

Here’s the python code:-

for t in range(int(input())):
    n = int(input())
    arr = list(map(int,input().split()))
    diff = abs(sum(arr))
    if diff>2:
        print("No")
    elif n%4==0 and diff>0:
        print("No")
    else:
        print("Yes")

Here’s the solution link:-
https://www.codechef.com/viewsolution/63630148

Hope you like it:)

1 Like

this is more elegant @sarkar_arthur , well done!!

1 Like