BIGARRAY - Editorial

PROBLEM LINK:

Contest Division 1
Contest Division 2
Contest Division 3
Practice

Setter: Utkarsh Gupta
Tester: Samarth Gupta
Editorialist: Taranpreet Singh

DIFFICULTY

Simple

PREREQUISITES

Basic Math

PROBLEM

Given N and S, consider an array of length N where A_i = i, find position x(1 \leq x \leq N) such that
\displaystyle \sum_{i = 1}^{x-1} A_i + \sum_{i = x+1}^N A_i = S.

If there are multiple such x, print any one of them. If no such x exists, print -1.

QUICK EXPLANATION

  • For chosen x, \displaystyle \sum_{i = 1}^{x-1} A_i + \sum_{i = x+1}^N A_i can be written as \displaystyle \sum_{i = 1}^N A_i - x. Since A_i = i, \displaystyle \sum_{i = 1}^N A_i = \frac{N*(N+1)}{2}
  • So, we can only choose x = \displaystyle \frac{N*(N+1)}{2} - S.
  • If 1 \leq x \leq N is satisfied, chosen x is the answer, otherwise no such x exists.

EXPLANATION

Let’s focus on the expression first.

\displaystyle \sum_{i = 1}^{x-1} A_i + \sum_{i = x+1}^N A_i = S.
If we consider both summations, we can see that only element not added is A_x. All elements before x-th element is included in the first summation, while all elements after x-th element are covered in second summation.

So we can write \displaystyle \sum_{i = 1}^{x-1} A_i + \sum_{i = x+1}^N A_i = \sum_{i = 1}^N A_i - A_x.

We can also replace A_i by i, so we have \displaystyle \sum_{i = 1}^{N}i - x =S.

The first summation is just sum of first N natural numbers, which is \displaystyle \frac{N*(N+1)}{2}. Hence the expression becomes \displaystyle x = \frac{N*(N+1)}{2} - S. This way, we have computed the required x.

We also require 1 \leq x \leq N, since the element with value x has to exist in the array. Hence, if the condition is not satisfied, there’s no such x which can satisfy the requirements. Otherwise found x is the required answer.

TIME COMPLEXITY

The time complexity is O(1) per test case.

SOLUTIONS

Setter's Solution
//Utkarsh.25dec
#include <bits/stdc++.h>
#include <chrono>
#include <random>
#define ll long long int
#define ull unsigned long long int
#define pb push_back
#define mp make_pair
#define mod 1000000007
#define rep(i,n) for(ll i=0;i<n;i++)
#define loop(i,a,b) for(ll i=a;i<=b;i++)
#define vi vector <int>
#define vs vector <string>
#define vc vector <char>
#define vl vector <ll>
#define all(c) (c).begin(),(c).end()
#define max3(a,b,c) max(max(a,b),c)
#define min3(a,b,c) min(min(a,b),c)
#define deb(x) cerr<<#x<<' '<<'='<<' '<<x<<'\n'
using namespace std;
#include <ext/pb_ds/assoc_container.hpp> 
#include <ext/pb_ds/tree_policy.hpp> 
using namespace __gnu_pbds; 
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
// ordered_set s ; s.order_of_key(val)  no. of elements strictly less than val
// s.find_by_order(i)  itertor to ith element (0 indexed)
typedef vector<vector<ll>> matrix;
ll power(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll modInverse(ll a){return power(a,mod-2);}
const int N=500023;
bool vis[N];
vector <int> adj[N];
void solve()
{
    ll n,s;
    cin>>n>>s;
    ll total_sum=(n*(n+1))/2;
    ll ele=(total_sum-s);
    if(ele>=1 && ele<=n)
        cout<<ele<<'\n';
    else
        cout<<-1<<'\n';
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int T=1;
    cin>>T;
    int t=0;
    while(t++<T)
    {
        //cout<<"Case #"<<t<<":"<<' ';
        solve();
        //cout<<'\n';
    }
    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
}
Tester's Solution
#include <bits/stdc++.h>
using namespace std;

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);
}

int main() {
    // your code goes here
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int t;
    t = readIntLn(1, 1000);
    int sum = 0;
    while(t--){
        int n;
        n = readIntSp(2, 1e9);
        long long s = readIntLn(1, 1e18);
        long long sum = n * 1ll * (n + 1)/2;
        if(sum - s <= n && sum - s > 0)
            cout << sum - s << '\n';
        else
            cout << -1 << '\n';
    }
    readEOF();
    return 0;
}
Editorialist's Solution
import java.util.*;
import java.io.*;
class BIGARRAY{
    //SOLUTION BEGIN
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        long N = nl(), S = nl();
        long sum = (N*N+N)/2;
        if(sum-S >= 1 && sum-S <= N)pn(sum-S);
        else pn(-1);
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    static boolean multipleTC = true;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        //Solution Credits: Taranpreet Singh
        int T = (multipleTC)?ni():1;
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        new BIGARRAY().run();
    }
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

    class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws Exception{
            br = new BufferedReader(new FileReader(s));
        }

        String next() throws Exception{
            while (st == null || !st.hasMoreElements()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException  e){
                    throw new Exception(e.toString());
                }
            }
            return st.nextToken();
        }

        String nextLine() throws Exception{
            String str = "";
            try{   
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }  
            return str;
        }
    }
}

Feel free to share your approach. Suggestions are welcomed as always. :slight_smile:

Here’s my approach

#include<bits/stdc++.h> 
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define ll long long 
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
const unsigned int M = 1000000007;
using namespace std;
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> tree;
void solve()
{
    ll t, n, s;
    cin>>t;
    while(t--){
        cin>>n>>s;
        ll sum = n*(n+1)/2;
        if( sum-s >= 1 and sum-s <= n)
        cout<<sum-s<<"\n";
        else
        cout<<"-1\n";
    }
}
int main()
{
ios_base::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);
solve();
return 0;
}

binary search approach

implementation
#include <bits/stdc++.h>
using namespace std;
using ll=long long ;
#define all(x) (x).begin(),(x).end()
#define rall(v) v.rbegin(),v.rend()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1> void ZZ(const char* name, Arg1&& arg1){std::cerr << name << '=' << arg1 << endl;}
template <typename Arg1, typename... Args>void ZZ(const char* names, Arg1&& arg1, Args&&... args)

{
const char* comma = strchr(names + 1, ',');
std::cerr.write(names, comma - names) << '=' << arg1;
ZZ(comma, args...);
}

const int mod=(int)(1e9)+7;

void solve() {
        ll n,s;
        cin>>n>>s;
        ll sum=n*(n+1)/2;
        ll l=1,r=n;
         while(l<r){
                ll mid=(l+r)>>1;
                if((sum-mid)>s){
                       l=mid+1;
                }
                else r=mid;
         }
         if((sum-r)==s) cout<<r<<'\n';
         else cout<<"-1\n";
}

int32_t main()
{
IOS;

// comment for single Test Case
int t=1;
 cin>>t;
 for(int T=1;T<=t;T++)
 {

   // cout << "Case #" << T << ": ";
   solve();
}

return 0;
}

Someone explain me please why I have AC for same method in C++ and WA in Python

C++ attempt: Solution: 51119422 | CodeChef

Python attempt: Solution: 51110889 | CodeChef

It seems identical to me, Please someone help me out with this. Thank you.

import os
import sys
from io import BytesIO, IOBase
def main():
pass
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")

if name == “main”:
main()

t=int(input())
for qq in range(t):
n,s=map(int,input().split())
xo=int((n*(n+1)-2*s)/2)

xo=int(xo)

m=n-1

x1=(m*(m+1))/2

x1=int(x1)

if(s=x1):

print(xo-s)

else:

print(-1)

if xo>=1 and xo<=n:
	print(xo)
else:
	print(-1)

Here the modified code.
Hope it helps.

The ones which have become bold are due to # symbol.
Those lines are simply comments.

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner s=new Scanner(System.in);

        int t=s.nextInt();
        while(t-->0){
            long n=s.nextInt();
            int x=s.nextInt();
            long sum=(n*(n+1))/2;
            if(sum-x>0 && sum-x<=n){
                System.out.println(sum-x);
            }else
                System.out.println(-1);
        }
	}
}

this is my code.
Please help me find where is the problem.
Thanks…

I don’t need the solution for this, I got AC in C++ for the exact same thing and WA in python idk why.

take x and sum both using long long and it will work.

I too faced the same problem.
Please help me find the error.

Use nextLong for both n & x and make their datatypes long as well. That should solve it.

Why this code giving RE (SIGXFSZ) error?
#include<bits/stdc++.h>
using namespace std;
#define endl ‘\n’
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<vector> vii;

/User defined function/
const int N = 3e5+5;

void solve_problem() {
ll n, s;
cin >> n >> s;

ll sum = (n * (n+1)) / 2;
sum = sum - s;
if(sum >= 1 && sum <= n) 
    cout << sum << endl;
else
    cout << -1 << endl;

}

/main function/
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);

#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif

cout << fixed << showpoint;
cout << setprecision(16);

int test = 1;
cin >> test;
while(test--) solve_problem();

return 0;

}

I have one dought

We are checking that x should be between 1 and n

If x comes out to be 1 or n in this case if x=1 then we have no elements below it and we have only elements above it

And if x comes out to be n than we elements only below it and not above it

Then why we are taking this check x should be between 1 and n I think this condition should be modified

it says x can be 1<=x<=n which means it can be 1 and n;

Can any body tell for test case : 10 15 why answer should be -1 as there are multiple position of x so we can print any?

Could someone tell me what’s wrong in my code? I got WA, I am guessing I should have used long long instead of int.

#include <bits/stdc++.h>

#define for0(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define forc(i, l, r) for (int i = (int)(l); i <= (int)(r); ++i)
#define forr0(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define forr1(i, n) for (int i = (int)(n); i >= 1; --i)

using namespace std;

#define pb push_back
#define pob pop_back
#define fi first
#define se second

typedef vector vi;
typedef vector vvi;
typedef pair<int, int> ii;
typedef vector vii;
typedef long long ll;
typedef vector vll;
typedef vector vvll;
typedef double ld;

int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.precision(10);
cout << fixed;
int t;
cin>>t;
while(t–) {
int n,s;
cin>>n>>s;
int count;
int ans=0;
count=(n*(n+1))/2;
ans=count-s;
if(ans>0 && ans<=n) cout<<ans<<endl;
else cout<<-1<<endl;
}
return 0;
}

What did I miss?

t = int(input())
for tt in range(t):
n, s = map(int, input().split())
total_sum = int((n * (n + 1)) / 2)
temp = total_sum - s
# print(total_sum, temp)
if (temp >= 1) & (temp <= n):
print(temp)
else:
print(-1)

https://www.codechef.com/viewsolution/51200108

Can anyone help me with test cases , its giving WA.
Thanks

Yes brother as in the constraints It was given 10^18 and that number can’t be stored by int so you have to used long long instead of int