Please subscribe to the official Codeforces channel in Telegram via the link https://t.me/codeforces_official. ×

### back_to_match's blog

By back_to_match, history, 3 weeks ago,

If anybody could help please help me out as for printing i have proceeded with naive approach and my total time complexity O(no of elements connected*No of queries) total time complexity if any one can help

pls help me out

• 0

By back_to_match, history, 2 months ago,

Educational Codeforces Round 114 (Rated for Div. 2) Educational Codeforces Round 114 (Rated for Div. 2) question c

https://codeforces.com/contest/1574/problem/C

import java.util.*; import java.io.*; public class A124 { public static void process()throws IOException { int n=I(); TreeSet set=new TreeSet(); long[] a=Al(n);long sum=0; for(int i=0;i<n;i++) { set.add(a[i]); sum+=a[i]; }

int m=I();
for(int i=0;i<m;i++)
{
long xi=L();long yi=L();
if(set.first()>xi)
{
if((long)(sum-set.first())>=yi)
{
pn((long)0);
}
else
{
pn((long)(yi-(sum-set.first())));
}
}
else
if(set.last()<xi)
{
long sum1=(long)Math.abs(xi-set.last());
long s=sum-set.last();
if(s>=yi)
{
pn((long)sum1);
}
else
{
pn((long)((yi-s)+sum1));
}

}
else
{
long sum1=0;long sum2=0;

sum1=(long)Math.abs(xi-set.floor(xi));
sum2=(long)0;
if((long)(sum-set.floor(xi))<yi)
{
sum1+=(long)(yi-(sum-set.floor(xi)));
}
if((long)(sum-set.ceiling(xi))<yi)
{
sum2+=(long)(yi-(sum-set.ceiling(xi)));
}
pn((long)Math.min(sum1, sum2));
}
}
}
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static void pn(Object o){out.println(o);out.flush();}
static void p(Object o){out.print(o);out.flush();}
static void pni(Object o){out.println(o);System.out.flush();}
static int I() throws IOException{return sc.nextInt();}
static long L() throws IOException{return sc.nextLong();}
static double D() throws IOException{return sc.nextDouble();}
static String S() throws IOException{return sc.next();}
static char C() throws IOException{return sc.next().charAt(0);}
static int[] Ai(int n) throws IOException{int[] arr = new int[n];for (int i = 0; i < n; i++)arr[i] = I();return arr;}
static String[] As(int n) throws IOException{String s[] = new String[n];for (int i = 0; i < n; i++)s[i] = S();return s;}
static long[] Al(int n) throws IOException {long[] arr = new long[n];for (int i = 0; i < n; i++)arr[i] = L();return arr;}
static void dyn(int dp[][],int n,int m,int z)throws IOException {for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ dp[i][j]=z;}} }