import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.NoSuchElementException;

public class Main {
	public static void main(String[] args) {

		for(int i=0;i<1;i++) {

			slover();
			out.flush();
		}
	}
	static FastScanner sc = new FastScanner();
	static PrintWriter out = new PrintWriter(System.out);

		private static class D{

			ArrayList<Integer> X=new ArrayList<Integer>();
			ArrayList<Integer> Y=new ArrayList<Integer>();
			int t=0;
			int index=0;
			D(ArrayList<Integer> X,ArrayList<Integer> Y,int t,int index){
				this.X=X;;
				this.Y=Y;
				this.t=t;
				this.index=index;
			}

		}

	//Set<Long> a=new HashSet<Long>();

	//Integer.toBinaryString(i);
	//Integer.toString(i, 2);
//	//Integer.parseInt(bin, 2);
	//bitset
		//StringBuffer S = new StringBuffer(sc.next());
				//String hoge2 = str.reverse().toString();
				//map.containsKey(A)
				//Map<Integer, Integer> map = new HashMap<Integer, Integer>(N);
				/*for ( キーのデータ型 key : マップの名前.keySet() ) {
					データのデータ型 data = マップの名前.get( key );

					// keyやdataを使った処理;
				}*/
				//int i = Integer.parseInt(s);
				//Queue<String> qq=new ArrayDeque<>(); //add,poll,peek BFSは前から実行される
				//Deque<String> dd=new ArrayDeque<>();//push後ろに入れる,poll(pop)後ろからとる,peek addは先頭に入るからバグ注意
				//stackdfsは後ろから実行される
				//ArrayList<Integer> cc = new ArrayList<>(N);
				//cc.contains(tmp)
				//Arrays.asList(c).contains("a")
				//list.set(1,"walk");//1 1 2 3 5
				//PriorityQueue<Integer> r=new PriorityQueue<Integer>();//add poll

		public static class Pair<K, V> extends AbstractMap.SimpleEntry<K, V> implements Comparable<Pair<K, V>> {
			/** serialVersionUID. */
		    private static final long serialVersionUID = 6411527075103472113L;

		    public Pair(final K key, final V value) {
		        super(key, value);
		    }

			@Override
			public int compareTo(Pair<K, V> o) {

				Comparable key = (Comparable)this.getKey();
				Comparable key2 = (Comparable)o.getKey();

				return key.compareTo(key2);
			}

		}

		// 文字列として入力を取得

	private static long mod=1000000009;
	private static int INF =999999999;
	private static long LINF=4000000000000000000L;

	private static long ncr(long n,long r) {
		long res=1;

		for(int i=0;i<r;i++) {
			res*=n-i;
			res/=i+1;
		}
		return res;
	}

	private static int slover()   {
		int W=sc.nextInt(),H=sc.nextInt();
		long x=sc.nextLong(),y=sc.nextLong();

		long V=W*H;
		long a[]= {x*H,y*W};
		double ans=0;
		int c=0;
		for(int i=0;i<2;i++) {
			a[i]=Math.min(a[i], V-a[i]);
			if(ans<a[i]) {
				ans=a[i];
				c=0;
			}else if(ans==a[i]) {
				c=1;
			}
		}
		p(ans+" "+c);

		//System.out.println(Arrays.toString(a));

		return 0;
	}
	private static void shape(int Q[]) {
		for(int i=0;i<Q.length;i++) {
			find2(Q,i);
		}
	}
	private static int find2(int Q[],int a) {
		//aの根をbの根にする。
		if(Q[a]==a) {
			return Q[a];
		}else {
			return Q[a]=find2(Q,Q[a]);
		}

	}
	private static void union2(int Q[],int a,int b) {

		int root1=find2(Q,a);
		int root2=find2(Q,b);
		Q[root1]=Q[root2];
	}

	private static void set_add(int Q[],int index,int value) {
		if(Q[index]==value) {

		}
		else if(Q[index]==INF) {
			Q[index]=value;

		}else if(value<Q[index]) {
			set_add(Q,index*2+1,value);
		}else {
			set_add(Q,index*2+2,value);
		}
	}

	private static void priority_queue_add(int Queue[],int index,int value) {
		Queue[index]=value;

		if(index!=0) {
			if((index-1)/2>=0&&Queue[(index-1)/2]>value) {
				Queue[index]=Queue[(index-1)/2];
				priority_queue_add(Queue,(index-1)/2,value);

			}
			if((index-2)/2>=0&&Queue[(index-2)/2]>value) {
				Queue[index]=Queue[(index-2)/2];
				priority_queue_add(Queue,(index-2)/2,value);

			}
		}

	}
private static int priority_queue_getFirst(int[] Queue) {
		int res=Queue[0];
		Queue[0]=Queue[Queue.length-1];
		Queue[Queue.length-1]=INF;
		//System.out.println(Arrays.toString(Queue));
		//大きさのチェック
		Q_shape(Queue,0);

		return res;
	}
	private static void Q_shape(int[] Queue,int index) {

			if(index*2+1<Queue.length&&Queue[index*2+1]<Queue[index]) {
				int v=Queue[index];
				Queue[index]=Queue[index*2+1];
				Queue[index*2+1]=v;
				Q_shape(Queue,index*2+1);

			}
			if(index*2+2<Queue.length&&Queue[index*2+2]<Queue[index]) {
				int v=Queue[index];
				Queue[index]=Queue[index*2+2];
				Queue[index*2+2]=v;
				Q_shape(Queue,index*2+2);

			}

	}
	private static int union_MaxSize(int[] tree) {

		union_shape(tree);

		int V[]=new int[tree.length+1];

		for(int i=0;i<tree.length;i++) {
			V[tree[i]]++;
		}
		int max=0;
		for(int i=0;i<=tree.length;i++) {
			max=Math.max(max, V[i]);
		}
		return max;
	}

	public static int find(int[] tree,int idx) {
        if(tree[idx]==idx) return idx;
        else {

        	return tree[idx] = find(tree,tree[idx]);
        }
    }
	public static void union_shape(int[] tree) {
		for(int i=0;i<tree.length;i++) {
			find(tree,i);
		}
	}

    //union idx2 tree to idx1 tree O(a(N))
    public static int[] union(int tree[],int idx1,int idx2) {
        int root1 = find(tree,idx1);
        int root2 = find(tree,idx2);
        tree[root2] = root1;
        return tree;
    }
	private static boolean heihou(long T) {
		if(Math.pow((int)Math.sqrt(T), 2)==T)return true;
		return false;
	}
	private static String zeroume(String S) {
		while(S.length()<6)S='0'+S;
		return S;
	}

	//速度が足りないときは、前計算を1回だけにしたり、longをintに変えたりするといい
	private static long modNcR2(int n,int r) {
		long x_b=1;

		for(int i=0;i<r;i++) {
			x_b*=(n-i);
			x_b%=mod;
		}

		long y=1;
		for(int i=1;i<=r;i++) {
			y*=i;
			y%=mod;
			//nPrにr!%modの逆元を掛ける
		}
		return  (x_b*modPow((int) y,mod-2,mod)%mod);

	}

	private static long modPow(int i,long t,long mod) {
		//iのt乗をO(log t)で返す
		i%=mod;
		t%=mod;
		long a=i;
		long res=1;
		//for(int i=0;i<S.length();i++) {if(S.charAt(N-i)=='1') {res=res*a%mod;}
		//tをStringで受け取りたい時用
		while(t!=0) {
			if((1&t)==1) {
				res=res*a%mod;
			}
			a=a*a%mod;
			t=t>>1;
		}
		return res;
	}

	public static long gcd(long num1,long num2) {
        if(num2==0) return num1;
        else return gcd(num2,num1%num2);
    }
	public static long lcm(long num1,long num2) {
		return num1*num2/gcd(num1,num2);
	}
	//O(N^0.5)
	private static boolean isPrime(long t) {
		if(t<2)return false;
		for(int i=2;i*i<=t;i++) {
			if(t%i==0)return false;
		}
		return true;
	}
	private static ArrayList<Long> Divisors(long t) {
		ArrayList<Long> c=new ArrayList<Long>();

		for(long i=1;i*i<=t;i++) {
			if(t%i==0) {

				if(i*i!=t) {
					c.add(t/i);
				}
				c.add((long)i);
			}
		}
		return c;
	}
	private static ArrayList<Long> Sorted_Divisors(long t) {
		ArrayList<Long> c=new ArrayList<Long>();
		for(long i=2;i*i<=t;i++) {

			if(t%i==0) {
				p(t+" "+i);
				c.add((long)i);
				t/=i;
				i--;
			}
		}
		if(t!=1)c.add(t);
		Collections.sort(c);

		return c;
	}
	private static void bubunwa() {
		int N=sc.nextInt();
		int K=sc.nextInt();
		int a[]=sc.nextIntArray(N, false);

		boolean dp[] =new boolean[K+1];

		Arrays.fill(dp, false);
		dp[0]=true;
		for(int i=0;i<N;i++) {
			for(int x=K-a[i];x>=0;x--) {
				if(dp[x])dp[x+a[i]]=true;
			}
		}

		p(dp[K] ? "Yes":"No");
	}

	private static String bitToString(int i) {
		return Integer.toBinaryString(i);
	}
/*********************************************************************/
	//target以下までの値のindexを返す
	//target以上が欲しいときは返り値+1すればいい
	//0-indexで個数を求めるときはさらにindex+1する必要あり
	private static int lower_bound(long a[],long target) {
	//p(target+ " "+Arrays.toString(a));
	if(a[0]>target)return -1;
	//最後の値がtarget以下であるときは最後のindexを返す。
	//target以上が欲しいときは注意する必要あり
	if(a[a.length-1]<=target) return a.length-1;

	int S=-1;
	int E=a.length;

	while(S<E) {

		int G=(S+E)/2;
		if(G+1==a.length) {
			G--;
		}
		//未満にしたいときは=の場所を変える
		if(a[G]<=target&&a[G+1]>target) {
			return G;

		}else if(a[G]<=target){
			S=G;
		}else if(a[G]>target) {
			E=G;
		}

	}

	return -1;
	}
	static String nextPermutation(String s) {
		ArrayList<Character> list=new ArrayList<Character>();
		for(int i=0;i<s.length();i++) {
			list.add(s.charAt(i));
		}
		int pivotPos=-1;
		char pivot=0;
		for(int i=list.size()-2;i>=0;i--) {
			if(list.get(i)<list.get(i+1)) {
				pivotPos=i;
				pivot=list.get(i);
				break;
			}
		}
		if(pivotPos==-1&&pivot==0) {
			return "Final";
		}
		int L=pivotPos+1,R=list.size()-1;

		int minPos=-1;
		char min =Character.MAX_VALUE;

		for(int i=R;i>=L;i--) {
			if(pivot<list.get(i)) {
				if(list.get(i)<min) {
					min=list.get(i);
					minPos=i;
				}
			}
		}

		Collections.swap(list, pivotPos, minPos);
		Collections.sort(list.subList(L, R+1));

		StringBuilder sb=new StringBuilder();
		for(int i=0;i<list.size();i++) {
			sb.append(list.get(i));
		}
		return sb.toString();
	}
private static long[][] com;
private static void nCr() {
	int MAX = 3001;
	com= new long[MAX][MAX];
	for(int i = 0; i < MAX; i++)
	    com[i][0] = 1;
	for(int i = 1; i < MAX; i++) {
	    for(int j = 1; j <= i; j++) {
	        com[i][j] = com[i-1][j-1] + com[i-1][j];
	        com[i][j] %= mod;
	    }
	}
}

	static void p(String ans) {out.println(ans);}
	static void p(int ans) {out.println(ans);}
	static void p() {out.println();}
	static void p(long ans) {out.println(ans);}
	static void p(double ans) {out.println(ans);}
	static void p(boolean ans) {out.println(ans);}

	static void pn(String ans) {out.print(ans);};
	static void pn(int ans) {out.print(ans);};
	static void pn() {out.print("");};
	static void pn(long ans) {out.print(ans);};
	static void pn(double ans) {out.print(ans);};

	static class FastScanner {
	    private final InputStream in = System.in;
	    private final byte[] buffer = new byte[1024];
	    private int ptr = 0;
	    private int buflen = 0;

	    private boolean hasNextByte() {
	      if (ptr < buflen) {
	        return true;
	      } else {
	        ptr = 0;
	        try {
	          buflen = in.read(buffer);
	        } catch (IOException e) {
	          e.printStackTrace();
	        }
	        if (buflen <= 0) {
	          return false;
	        }
	      }
	      return true;
	    }

	    private int readByte() {
	      if (hasNextByte()) return buffer[ptr++];
	      else return -1;
	    }

	    private static boolean isPrintableChar(int c) {
	      return 33 <= c && c <= 126;
	    }

	    private void skipUnprintable() {
	      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
	    }

	    public boolean hasNext() {
	      skipUnprintable();
	      return hasNextByte();
	    }

	    public String next() {
	      if (!hasNext()) throw new NoSuchElementException();
	      StringBuilder sb = new StringBuilder();
	      int b = readByte();
	      while (isPrintableChar(b)) {
	        sb.appendCodePoint(b);
	        b = readByte();
	      }
	      return sb.toString();
	    }

	    public long nextLong() {
	      if (!hasNext()) throw new NoSuchElementException();
	      long n = 0;
	      boolean minus = false;
	      int b = readByte();
	      if (b == '-') {
	        minus = true;
	        b = readByte();
	      }
	      if (b < '0' || '9' < b) {
	        throw new NumberFormatException();
	      }
	      while (true) {
	        if ('0' <= b && b <= '9') {
	          n *= 10;
	          n += b - '0';
	        } else if (b == -1 || !isPrintableChar(b)) {
	          return minus ? -n : n;
	        } else {
	          throw new NumberFormatException();
	        }
	        b = readByte();
	      }
	    }

	    public int nextInt() {
	      return (int) nextLong();
	    }

	    public double nextDouble(){
	    	return Double.parseDouble(next());
	    }

	    public int[] nextIntArray(int N, boolean oneBased) {
	      if (oneBased) {
	        int[] array = new int[N + 1];
	        for (int i = 1; i <= N; i++) {
	          array[i] = sc.nextInt();
	        }
	        return array;
	      } else {
	        int[] array = new int[N];
	        for (int i = 0; i < N; i++) {
	          array[i] = sc.nextInt();
	        }
	        return array;
	      }
	    }

	    public long[] nextLongArray(int N, boolean oneBased) {
	      if (oneBased) {
	        long[] array = new long[N + 1];
	        for (int i = 1; i <= N; i++) {
	          array[i] = sc.nextLong();
	        }
	        return array;
	      } else {
	        long[] array = new long[N];
	        for (int i = 0; i < N; i++) {
	          array[i] = sc.nextLong();
	        }
	        return array;
	      }
	    }
	  }
}

Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int w = sc.nextInt();
        int h = sc.nextInt();
        int x = sc.nextInt();
        int y = sc.nextInt();
        sc.close();

        System.out.print(Double.valueOf(w) * Double.valueOf(h) / 2.0);
        if (w / 2 == x && w % 2 == 0 && h / 2 == y && h % 2 == 0) {
            System.out.println(" 1");
        } else {
            System.out.println(" 0");
        }
    }

}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


import java.io.*;
import java.math.*;
import java.util.*;

public class Main {

	public static void main(String[] args){
		FastScanner sc = new FastScanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		solve(sc,out);

		out.flush();
	}

	public static void solve(FastScanner sc, PrintWriter out) {
		double w = sc.nextDouble();
		double h = sc.nextDouble();
		double x = sc.nextDouble();
		double y = sc.nextDouble();

		double a = 0;
		double b = 0;

		a = Math.min((h - y) * w, y * w);
		b = Math.min((w - x) * h, x * h);

		out.println(new BigDecimal(Math.max(a, b)).toPlainString()+" "+ (a == b ? 1 : 0));
	}

	public static long gcd(long a, long b) {
		if(a < b) return gcd(b, a);
		if(b == 0) return a;
		return gcd(b, a % b);
	}

	public static long lcm(long a, long b) {
		return a / gcd(a, b) * b;
	}
}

class Pair<K, V> extends AbstractMap.SimpleEntry<K, V> {

    public Pair(K key, V value) {
        super(key, value);
    }

    public Pair<V, K> swap() {
    	return new Pair<V, K>(getValue(), getKey());
    }
 }

class FastScanner {
    private BufferedReader reader = null;
    private StringTokenizer tokenizer = null;

    public FastScanner(InputStream in) {
        reader = new BufferedReader(new InputStreamReader(in));
        tokenizer = null;
    }

    public String next() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    public String nextLine() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                return reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return tokenizer.nextToken("\n");
    }

    public long nextLong() {
        return Long.parseLong(next());
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }

    public double nextDouble() {
         return Double.parseDouble(next());
     }

    public int[] nextIntArray(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++)
            a[i] = nextInt();
        return a;
    }

    public long[] nextLongArray(int n) {
        long[] a = new long[n];
        for (int i = 0; i < n; i++)
            a[i] = nextLong();
        return a;
    }
}


import java.util.*;

public class Main {
	public static void main(String[] args) throws Exception{
		Scanner scn = new Scanner(System.in);
		int n = scn.nextInt();
      	int k = scn.nextInt();
      	int ans = n-k;
      	if(k==1) ans = 0;
      	System.out.println(ans);
	}
}

Score : 100 points

Problem Statement

Takahashi is distributing N balls to K persons.

If each person has to receive at least one ball, what is the maximum possible difference in the number of balls received between the person with the most balls and the person with the fewest balls?

Constraints

1 \leq K \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the maximum possible difference in the number of balls received.

Sample Input 1

3 2

Sample Output 1

1

The only way to distribute three balls to two persons so that each of them receives at least one ball is to give one ball to one person and give two balls to the other person.

Thus, the maximum possible difference in the number of balls received is 1.

Sample Input 2

3 1

Sample Output 2

0

We have no choice but to give three balls to the only person, in which case the difference in the number of balls received is 0.

Sample Input 3

8 5

Sample Output 3

3

For example, if we give 1, 4, 1, 1, 1 balls to the five persons, the number of balls received between the person with the most balls and the person with the fewest balls would be 3, which is the maximum result.


import java.util.*;

public class Main {
	public static void main(String[] args) throws Exception{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
        int k = sc.nextInt();
        if(k == 1){
        	System.out.println(0);
        }else{
        	System.out.println(n - k);
        }
	}
}


import java.util.Scanner;

public class Main{
  public static void main(String[]args){
    Scanner sc = new Scanner(System.in);

    int n = sc.nextInt();
    int k = sc.nextInt();
    int r = 0;

    if(1<=k && k<=n && n<=100){
      r = (n%k);
      System.out.println(r);
    }
  }
}


import java.util.*;

class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		Integer[] A = new Integer[N];
		int sum=0;
		int all_plus=0;
		int all_minus=0;
		for (int i=0;i<N;i++) {
			A[i]=sc.nextInt();
			sum+=Math.abs(A[i]);
		}
		Arrays.sort(A);

		Queue<Integer> plus = new ArrayDeque<Integer>();
		Queue<Integer> minus = new ArrayDeque<Integer>();
		List<Integer> list = new LinkedList<Integer>();
		for (int i=0;i<N;i++) {
			if (A[i]>0) {
				plus.add(A[i]);
				all_plus=1;
			} else {
				list.add(A[i]);
				all_minus=1;
			}
		}
		Collections.reverse(list);
		List<Integer> list_2 = new ArrayList<Integer>(list);
		for (int i=0;i<list.size();i++) {
			minus.add(list_2.get(i));
		}
		if (all_plus==0) {
			sum+=2*minus.peek();
		} else if (all_minus==0) {
			sum-=2*plus.peek();
		}
		System.out.println(sum);

		if (plus.isEmpty()) {
			int tmp=minus.remove();
			int tmp_2=minus.remove();
			System.out.print(tmp);
			System.out.print(" ");
			System.out.println(tmp_2);
			plus.add(tmp-tmp_2);
		}
		if (minus.isEmpty()) {
			int tmp=plus.remove();
			int tmp_2=plus.remove();
			System.out.print(tmp);
			System.out.print(" ");
			System.out.println(tmp_2);
			minus.add(tmp-tmp_2);
		}

		while (plus.size()>1) {
			int tmp=plus.remove();
			int tmp_2=minus.remove();
			System.out.print(tmp_2);
			System.out.print(" ");
			System.out.println(tmp);
			minus.add(tmp_2-tmp);
		}

		while (!minus.isEmpty()) {
			int tmp=plus.remove();
			int tmp_2=minus.remove();
			System.out.print(tmp);
			System.out.print(" ");
			System.out.println(tmp_2);
			plus.add(tmp-tmp_2);
		}
	}
}

Score : 500 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on a blackboard.

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0


import java.util.Scanner;

public class Main{
  static int pivot(int[] a,int i,int j){
    int k=i+1;
    while(k<=j && a[i]==a[k]) k++;
    if(k>j) return -1;
    if(a[i]>=a[k]) return i;
    return k;
  }

  static int partition(int[] a,int i,int j,int x){
    int l=i,r=j;

    while(l<=r){

      while(l<=j && a[l]<x)  l++;

      while(r>=i && a[r]>=x) r--;

      if(l>r) break;
      int t=a[l];
      a[l]=a[r];
      a[r]=t;
      l++; r--;
    }
    return l;
  }

  public static void quickSort(int[] a,int i,int j){
    if(i==j) return;
    int p=pivot(a,i,j);
    if(p!=-1){
      int k=partition(a,i,j,a[p]);
      quickSort(a,i,k-1);
      quickSort(a,k,j);
    }
  }

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n=scanner.nextInt();
    int a[]=new int[n];
    int flg=0;
    int cmd=0;
    long ans=0;
    //HashMap<Integer,Integer> num=new HashMap<Integer,Integer>();
    long x[]=new long[n];
    long y[]=new long[n];
    int cnt=0;

    for(int i=0;i<n;i++){
      a[i]=scanner.nextInt();
    }

    quickSort(a,0,a.length-1);

    for(int i=0;i<n-1;i++){
      if(a[i]<=0&&a[i+1]>0){
        flg=1;
        cmd=i;
      }
    }
    if(n==2&&a[0]==0){
      x[0]=a[1];
      y[0]=a[0];
      ans=a[1]-a[0];
    }
    else if(flg==1){
      x[cnt]=a[cmd];
      y[cnt]=a[cmd+1];
      cnt++;
      ans=a[cmd]-a[cmd+1];
      for(int i=cmd+2;i<n-1;i++){
        x[cnt]=ans;
        y[cnt]=a[i];
        cnt++;
        //System.out.println(ans+" "+a[i]);
        ans=ans-a[i];
      }
      //System.out.println(a[n-1]+" "+ans);
      x[cnt]=a[n-1];
      y[cnt]=ans;
      cnt++;
      ans=a[n-1]-ans;
      for(int i=0;i<cmd;i++){
        x[cnt]=ans;
        y[cnt]=a[i];
        cnt++;
        //System.out.println(ans+" "+a[i]);
        ans=ans-a[i];
      }
    }
    else{
      if(a[0]<0){
        for(int i=0;i<n/2;i++){
          int tmp=a[i];
          a[i]=a[n-1-i];
          a[n-1-i]=tmp;
        }

        ans=a[0];
        for(int i=1;i<n-1;i++){
          x[cnt]=ans;
          y[cnt]=a[i];
          cnt++;
          ans=ans-a[i];
        }
        x[cnt]=ans;
        y[cnt]=a[n-1];
        cnt++;
        ans=ans-a[n-1];

      }
      else{
        ans=a[0];
        for(int i=1;i<n-1;i++){
          x[cnt]=ans;
          y[cnt]=a[i];
          cnt++;
          ans=ans-a[i];
        }
        x[cnt]=a[n-1];
        y[cnt]=ans;
        cnt++;
        ans=a[n-1]-ans;
      }
    }

    System.out.println(ans);

    for(int i=0;i<n-1;i++){
      System.out.println(x[i]+" "+y[i]);
    }
  }
}


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

 class Main implements Runnable {
    long m = (int)1e9+7;
    PrintWriter w;
    InputReader c;
    final int MAXN = (int)1e6 + 100;

    public void run() {
        c = new InputReader(System.in);
        w = new PrintWriter(System.out);

        int n = c.nextInt();
        int a[] = scanArrayI(n);

        int pref[] = new int[n];
        int suf[] = new int[n];

        pref[0] = a[0];
        for(int i=1;i<n;i++)
            pref[i] = pref[i-1] + a[i];

        suf[n-1] = a[n-1];
        for(int i=n-2;i>=0;i--)
            suf[i] = suf[i+1] + a[i];

        int ma =Integer.MAX_VALUE;

        for(int i=0;i<n;i++){
            if(i!=n-1)
            ma = min(ma, abs(suf[i+1] - pref[i]));
        }

        w.println(ma);

        w.close();
    }
    class pair{
        int x,y;

        public pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    long gcd(long a, long b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
    public static void sortbyColumn(int arr[][], int col){
        Arrays.sort(arr, new Comparator<int[]>()
        {
            public int compare(int[] o1, int[] o2){
                return(Integer.valueOf(o1[col]).compareTo(o2[col]));
            }
        });

    }
    public static class DJSet {
        public int[] upper;

        public DJSet(int n) {
            upper = new int[n];
            Arrays.fill(upper, -1);
        }

        public int root(int x) {
            return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
        }

        public boolean equiv(int x, int y) {
            return root(x) == root(y);
        }

        public boolean union(int x, int y) {
            x = root(x);
            y = root(y);
            if (x != y) {
                if (upper[y] < upper[x]) {
                    int d = x;
                    x = y;
                    y = d;
                }
                upper[x] += upper[y];
                upper[y] = x;
            }
            return x == y;
        }
    }
    public static int[] radixSort(int[] f)    {
        int[] to = new int[f.length];
        {
            int[] b = new int[65537];
            for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
            for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
            for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
            int[] d = f; f = to;to = d;
        }
        {
            int[] b = new int[65537];
            for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
            for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
            for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
            int[] d = f; f = to;to = d;
        }
        return f;
    }
    public void printArray(int[] a, int d){
        for(int i=0;i<a.length;i++)
            w.print(a[i]+d+" ");
        w.println();
    }
    public int[] scanArrayI(int n){
        int a[] = new int[n];
        for(int i=0;i<n;i++)
            a[i] = c.nextInt();
        return a;
    }
    public long[] scanArrayL(int n){
        long a[] = new long[n];
        for(int i=0;i<n;i++)
            a[i] = c.nextLong();
        return a;
    }
    public void printArray(long[] a){
        for(int i=0;i<a.length;i++)
            w.print(a[i]+" ");
        w.println();
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt() {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new Main(),"Main",1<<26).start();
    }
}

Score : 200 points

Problem Statement

We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.

We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group.

Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2.

Constraints

2 \leq N \leq 100

1 \leq W_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
W_1 W_2 ... W_{N-1} W_N

Output

Print the minimum possible absolute difference of S_1 and S_2.

Sample Input 1

3
1 2 3

Sample Output 1

0

If T = 2, S_1 = 1 + 2 = 3 and S_2 = 3, with the absolute difference of 0.

Sample Input 2

4
1 3 1 1

Sample Output 2

2

If T = 2, S_1 = 1 + 3 = 4 and S_2 = 1 + 1 = 2, with the absolute difference of 2. We cannot have a smaller absolute difference.

Sample Input 3

8
27 23 76 2 3 5 62 52

Sample Output 3

2


import java.util.*;

class Main{
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int stepNum = sc.nextInt();
		int brokenNum = sc.nextInt();
		int[] brokenSteps = new int[brokenNum];
		for(int i = 0; i < brokenNum; i++)brokenSteps[i] = sc.nextInt();

        Dp dp = new Dp(stepNum+1);
        for(int index : brokenSteps) Dp.dp[index] = 0;
        int ans = dp.part(stepNum);

		System.out.println(ans);
    }
}

class Dp {
    public static int[] dp;
    public Dp (int num) {
        dp = new int[num];
        for(int i = 0; i < num; i++)dp[i] = -1;
    }

    public int part(int index) {
        if(dp[index] != -1)return dp[index];
        if(index == 0) dp[index] = 1;
        else if(index == 1) dp[index] = 1;
        else dp[index] = part(index-1) + part(index-2);
        while(dp[index] >= Mod.mod) dp[index] -= Mod.mod;
        return dp[index];
    }
}

class Mod{
    static int mod = 1000000007;
}

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.


import java.util.Scanner;
public class Main {
	public static boolean Esta(int k, int[]A) {
		for(int i=0;i<A.length;i++) {
			if (A[i]==k){
				return true;
			}
		}
		return false;
	}
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		String[] linea = s.nextLine().split(" ");
		int N=Integer.parseInt(linea[0]);
		int M=Integer.parseInt(linea[1]);
		int [] A= new int[(int)(M+1)];
		for(int i=1; i<=M;i++) {
			String[] linea2 = s.nextLine().split(" ");
			A[i]=Integer.parseInt(linea2[0]);

		}
		s.close();
		long []DP= new long[N+1];
		DP[1]=1;
		DP[2]=2;
		boolean a=true;
		for(int j=1;j<M;j++) {
			if(A[j+1]-A[j]==1 && j!=1) {
				System.out.print(0);
				a=false;
				break;
			}
			}
		if(Esta(1,A)) {
			DP[2]=1;
			DP[1]=0;
		}
		for(int k=3;k<=N;k++) {
			if(Esta(k,A)) {
				DP[k]=0;
			}
			else {
				DP[k]=DP[k-1]+DP[k-2];
			}
		}
		if(a) {
			System.out.print(DP[N]%1000000007);
		}
		}}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		boolean impo = false;
		long a[] = new long[m + 1];
		long b[] = new long[m + 2];
		a[0] = -9;
		for (int i = 1; i <= m; i++) {
			a[i] = sc.nextInt();
			b[i] = a[i] - a[i - 1] - 1;
			if (a[i] - a[i - 1] == 1) {
				impo = true;
			}
		}

		b[1] = a[1];
		b[m + 1] = n - a[m];

		if(impo) {
			System.out.println(0);
		} else {

			long pat = 0;
			long ans = 1;
			long nidan = 0;
			long idan = 0;

			long kni = 0;
			long kic = 0;
			for (int i = 1; i <= m + 1; i++) {
				nidan = (b[i] - 1) / 2;
				idan = (b[i] - 1) % 2;
				pat = 0;
				//System.out.println();
				for (long k = 0; k <= nidan; k++) {
					kni = nidan - k;// 二段をこれだけ
					kic = (b[i] - 1) - kni * 2;

				//	System.out.println(kni + " +" + kic);
				//System.out.println(con(kni + kic, Math.min(kni, kic)));
					pat = pat + con(kni + kic, kic) % 1000000007;
					pat = pat % 1000000007;
				}
				// System.out.println(b[i]);
				//System.out.println("!" + pat);
				//System.out.println((ans * pat) % 1000000007);
				ans = (ans * pat) % 1000000007;
			}

			System.out.println(ans);
		}

	}

	static public long con(long n, long r) {
		long num = 1;
		for (long i = 1; i <= r; i++) {
			num = num * (n - i + 1) / i;
		}
		return num;
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		String str[] = br.readLine().split(" ");

		int h = Integer.parseInt(str[0]);
		int w = Integer.parseInt(str[1]);

		char matrix[][] = new char[h][w];

		for (int i = 0; i < h; i++) {
			char c[] = br.readLine().toCharArray();
			for (int j = 0; j < w; j++) {
				matrix[i][j] = c[j];
			}
		}

		int left[][] = new int[h + 10][w + 10];
		int right[][] = new int[h + 10][w + 10];
		int top[][] = new int[h + 10][w + 10];
		int bottom[][] = new int[h + 10][w + 10];

		for (int i = 0; i < h; ++i) {
			int cur = 0;
			for (int j = 0; j < w; ++j) {
				if (matrix[i][j] == '#')
					cur = 0;
				else
					++cur;
				left[i][j] = cur;
			}
		}

		for (int i = 0; i < h; ++i) {
			int cur = 0;
			for (int j = w - 1; j >= 0; --j) {
				if (matrix[i][j] == '#')
					cur = 0;
				else
					++cur;
				right[i][j] = cur;
			}
		}

		for (int j = 0; j < w; ++j) {
			int cur = 0;
			for (int i = 0; i < h; ++i) {
				if (matrix[i][j] == '#')
					cur = 0;
				else
					++cur;
				top[i][j] = cur;
			}
		}

		for (int j = 0; j < w; ++j) {
			int cur = 0;
			for (int i = h - 1; i >= 0; --i) {
				if (matrix[i][j] == '#')
					cur = 0;
				else
					++cur;
				bottom[i][j] = cur;
			}
		}

		int max = 0;

		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				if (matrix[i][j] == '#')
					continue;
				max = Math.max(max, left[i][j] + right[i][j] + top[i][j] + bottom[i][j] - 3);
			}
		}

		System.out.println(max);
	}

}

Score : 400 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given H strings S_i (1 \leq i \leq H), each of length W. If the j-th character (1 \leq j \leq W) of S_i is #, there is an obstacle on the square at the i-th row from the top and the j-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

1 \leq H \leq 2,000

1 \leq W \leq 2,000

S_i is a string of length W consisting of # and ..

. occurs at least once in one of the strings S_i (1 \leq i \leq H).

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber , InputReader in , PrintWriter out){
            int h = in.nextInt();
            int w = in.nextInt();
            HashMap<Integer,ArrayList<Integer>> arr = new HashMap<>(h);
            HashMap<Integer,ArrayList<Integer>> arr1 = new HashMap<>(w);
            for (int i = 0; i <h ; i++) {
                arr.put(i , new ArrayList<>(h));
            }
            for (int i = 0; i <w ; i++) {
                arr1.put(i , new ArrayList<>(w));
            }
            int[][] count = new int[h][w];
            for (int i = 0; i <h ; i++) {
                String s = in.next();
                for (int j = 0; j <s.length() ; j++) {
                    if (s.charAt(j) == '#')
                    {
                        arr.get(i).add(j);
                        arr1.get(j).add(i);}
                }
            }
            for (int i = 0; i <h ; i++) {
                int k = -1 ;
                int v = 0 ;
                arr.get(i).add(w);
                for (int j = 0; j < w ; j++) {
                    if (j == arr.get(i).get(v)){
                        k = arr.get(i).get(v);
                        v++;
                        continue;
                    }
                    count[i][j] = arr.get(i).get(v) -k -1;
                }
            }
            for (int j = 0; j <w ; j++) {
                int k = -1 ;
                int v = 0 ;
                arr1.get(j).add(h);
                for (int i = 0; i < h ; i++) {
                    if (i == arr1.get(j).get(v)){
                        k = arr1.get(j).get(v);
                        v++;
                        continue;
                    }
                    count[i][j]+= arr1.get(j).get(v)-k -1;
                }
            }
            int max =-1;
            for (int i = 0; i <h ; i++) {
                for (int j = 0; j <w ; j++) {
                    max = Math.max(max , count[i][j]);
                }
            }
            out.println(max - 1);
        }
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }

}


import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 *  @author Ivan Pryvalov (ivan.pryvalov@gmail.com)
 */
public class Main implements Runnable {

    static EventType eventType = EventType.DEFAULT; //EventType.GOOGLE_CODE_JAM;
    static boolean interactive = false; //use outGlobal.println()   and   outGlobal.flush()
    static int T = 1; // T \in {0,1}. If T=0, it will be read from the input.
    static String inputFilename = null; // if 'null', it reads data from std-in.

    static boolean largeFakeTest = false; // Check if you generate data on fly
    static int largeFakeTest_T = 1;
    //--------------------------------------------------------------------

    public static class Solver extends  SolverAbstract{

        int H;
        int W; // 2k
        char[][] map;

        @Override
        public void readInput() throws IOException {
            H = scanner.nextInt();
            W = scanner.nextInt();
            map = new char[H][];
            for (int i = 0; i < H; i++) {
                String line = scanner.nextLine();
                map[i] = line.toCharArray();   // . or #
            }
        }

        @Override
        protected void solve() throws IOException {
            int[][] beam = new int[H][W];

            for (int i = 0; i < H; i++) {
                int cnt = 0;
                for (int j = 0; j < W; j++) {
                    if (map[i][j]=='#'){
                        cnt = 0;
                    }else{
                        cnt++;
                    }
                    beam[i][j] += cnt;
                }
                cnt = 0;
                for (int j = W-1; j >= 0; j--) {
                    if (map[i][j]=='#'){
                        cnt = 0;
                    }else{
                        cnt++;
                    }
                    beam[i][j] += cnt;
                }
            }

            for (int j = 0; j < W; j++) {
                int cnt = 0;
                for (int i = 0; i < H; i++) {
                    if (map[i][j]=='#'){
                        cnt = 0;
                    }else{
                        cnt++;
                    }
                    beam[i][j] += cnt;
                }
                cnt = 0;
                for (int i = H-1; i >=0; i--) {
                    if (map[i][j]=='#'){
                        cnt = 0;
                    }else{
                        cnt++;
                    }
                    beam[i][j] += cnt;
                }
            }

            int max = 0;
            for (int i = 0; i < H; i++) {
                for (int j = 0; j < W; j++) {
                    max = Math.max(max, beam[i][j]);
                }
            }
            out.println(max - 3);
        }

    }

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

    private void solveAll() throws IOException {
        long timeStart = System.currentTimeMillis();
        if (T==0) {
            if (largeFakeTest) {
                T = largeFakeTest_T;
            } else {
                T = scanner.nextInt();
            }
        }
        final String[] results = new String[T+1];
        for (int test = 0; test < T; test++) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream outLocal = new PrintStream(baos);
            Solver solver = new Solver(){
                @Override
                public void callback() {
                    results[testNo] = answer;
                }
            };
            solver.out = outLocal;
            solver.testNo = test+1;
            if (largeFakeTest) {
                solver.readFakeInput();
            }else{
                solver.readInput();
            }
            solver.solveWrapped(baos);
        }

        long timeEnd = System.currentTimeMillis();
        if (isInputFromFile())
            System.out.println("All tasks are solved! Elapsed time "+(timeEnd-timeStart)/1000.0+" sec.");

        // write all responses in the proper order
        if (!interactive) {
            for (int i = 1; i <= T; i++) {
                if (eventType == EventType.GOOGLE_CODE_JAM) {
                    outGlobal.printf("Case #%d: %s", i, results[i]);
                } else {
                    outGlobal.print(results[i]);
                }
            }
        }
    }

    enum EventType{
        DEFAULT,
        GOOGLE_CODE_JAM
    }

    static boolean isInputFromFile() {
        return inputFilename != null;
    }

    public static abstract class SolverAbstract {
        PrintStream out;
        int testNo;
        String answer = null;

        public void callback(){};

        public abstract void readInput() throws IOException;

        //generate a randomized test with the maximal input values
        public void readFakeInput() throws  IOException{
            throw new RuntimeException("not implemented");
        }

        protected abstract void solve() throws IOException;

        protected void solveWrapped(ByteArrayOutputStream baos) throws IOException {
            if (isInputFromFile())
                System.out.println("SOLVER: solving task #"+testNo+" out of "+ T+"...");
            solve();
            answer = baos.toString();
            if (isInputFromFile()) {
                System.out.println("\t"+answer);
            }
            callback();
        }
    }

    ////////////////////////////////////////////////////////
    // Link about multithreading: http://stackoverflow.com/questions/4521983/java-executorservice-that-blocks-on-submission-after-a-certain-queue-size

    // ------------- Some stardard tools that are currently not tested.
    //adopt for the lists of adjacent vertices
    static class Graph{

        int[][] G;
        int N;

        int[][] A;
        int[][] F;

        int[] path;
        int pathLen;
        boolean[] visited;
        int target;
        boolean flowFound;

        public Graph(int[][] g) {
            G = g;
            N = G.length;
        }

        public int[][] maxflow(int iSource, int iSink) {
            path = new int[N];
            visited = new boolean[N];

            A = new int[N][];
            for (int i = 0; i < N; i++) {
                A[i] = G[i].clone();
            }
            F = new int[N][N];

            target = iSink;
            //dfs from source to sink
            //increase path
            while(true){
                flowFound = false;
                visited[iSource] = true;
                pathLen = 0;
                path[pathLen++] = iSource;
                dfs(iSource);
                if (!flowFound)
                    break;
            }
            return F;
        }

        private void dfs(int u) {
            if (u==target){
                flowFound = true;
                for (int i = 0; i < pathLen-1; i++) {
                    int from = path[i];
                    int to  = path[i+1];
                    F[from][to]++;
                    F[to][from]--;
                }
            }else {
                for (int i = 0; i < N && !flowFound; i++) {
                    if (!visited[i] && A[u][i] > F[u][i]) {
                        visited[i] = true;
                        path[pathLen] = i;
                        pathLen++;
                        dfs(i);
                        visited[i] = false;
                        pathLen--;
                    }
                }
            }
        }
    }

    public static class Utilities{
        public static List<Integer> getPrimes(int limit) {
            boolean[] primes = new boolean[limit+1];
            Arrays.fill(primes, true);

            primes[1] = false;
            for(int i=2; i<=limit; i++){
                if (primes[i]){
                    for(int j=i+i; j<=limit; j+=i){
                        primes[j] = false;
                    }
                }
            }
            List<Integer> listPrimes = new ArrayList<>();
            for(int i=2; i<=limit; i++){
                if (primes[i]){
                    listPrimes.add(i);
                }
            }
            return listPrimes;
        }
    }

    public static class Modulo{
        long mod = (long)1e9+7;

        public Modulo(long mod) {
            super();
            this.mod = mod;
        }

        public long inv(long a) {
            long res =  pow(a, mod-2);
            return res;
        }

        public long pow(long a, long x) {
            if (x==0)
                return 1;
            long part = 1;
            if ((x&1)!=0)
                part = a;
            return (part * pow((a*a)%mod, x>>1)) % mod;
        }

        public long c(long n, long m){
            long res = 1;
            for(int i=1; i<=m; i++){
                res = (res * (n-m+i)) % mod;
                res = (res * inv(i)) % mod;
            }
            return res;
        }
    }

    /**
     * Added 26.04.2013.
     * See KROK 2013, Round 1, Problem D.
     */
    static class DisjointUnionSet implements Cloneable{
        int[] rank;
        int[] parent;

        protected DisjointUnionSet clone(){
            DisjointUnionSet cloned = new DisjointUnionSet(parent.length);
            for(int i=0; i<parent.length; i++){
                cloned.parent[i] = parent[i];
                cloned.rank[i] = rank[i];
            }
            return cloned;
        }

        public DisjointUnionSet(int n) {
            rank = new int[n];
            parent = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
            }
        }

        @Override
        public String toString() {
            return "disj [parents=" + Arrays.toString(parent) + "]";
        }

        /**
         * Problem specific or general?
         * O(N * alpha)
         */
        public void union(DisjointUnionSet set2){
            for(int i=0; i<parent.length; i++){
                parent[find(i)] = parent[find(set2.find(i))];
            }
        }

        /**
         * @param index1 range 0..n-1
         * @param index2
         */
        public void union(int index1, int index2){
            int p1 = find(index1);
            int p2 = find(index2);
            if (rank[p1] > rank[p2]){
                parent[p2] = p1;
            }else if (rank[p2] > rank[p1]){
                parent[p1] = p2;
            }else{
                parent[p2] = p1;
                rank[p1]++;
            }
        }

        // O(alpha(n))
        private int find(int index) {
            if (parent[index] != index)
                parent[index] =  find(parent[index]);
            return parent[index];
        }

        // O(N alpha(N)) ==> see find()
        public int getCountDisjointSets(){
            int[] used = new int[parent.length];
            for(int i=0; i<parent.length; i++){
                used[find(i)] = 1;
            }
            int res = 0;
            for(int i=0; i<parent.length; i++){
                res += used[i];
            }
            return res;
        }
    }

    private static Random rnd = new Random();
    public static class ArrayUtils{
        public static void shuffle(int[] a){
            for(int j=a.length-1; j>=1; j--){
                int i = rnd.nextInt(j+1);
                swap(a, i, j);
            }
        }

        public static void swap(int[] a, int i, int j){
            int tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }
    }

    static class GraphSupport{
        /*
        //Added 20.02.2017.
        //See Codeforces Round 398, Div.2, C.
        // Recoursive call to dfs function may result in either MTL or StackOverflow.
        // Codeforces provide stacksize 64M

        private void dfs_no_recursion(int root, IntConsumer dfs_post){
            int[] stack = new int[N];
            int[] stackInt = new int[N];
            int iStack = 0;
            stack[iStack] = root;
            stackInt[iStack++] = 0;
            while(true){
                Node node = nodes[stack[iStack-1]];
                int childIdx = stackInt[iStack-1];
                if (childIdx < node.children.size()){
                    stack[iStack] = node.children.get(childIdx).idx;
                    stackInt[iStack++] = 0;
                }else{
                    dfs_post.accept(node.idx);

                    iStack--;
                    if (iStack==0){
                        break;
                    }
                    stackInt[iStack-1]++;
                }
            }
        }
        */
    }

    ////////////////////////////////////////////////////////
    /// Typically, you don't want to edit anything below
    ///////////////////////////////////////////////////////
    final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly
    final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8;
    final int BUF_SIZE_INPUT = 1024;

    boolean useClassResourceTopDir = true;
    String outSuffix = ".out";

    static PrintStream outGlobal;
    static ByteScanner scanner;

    public void run() {
        try{
            InputStream bis;
            OutputStream bos;
            if (inputFilename !=null){
                File inputFile;
                File outputFile;
                if (useClassResourceTopDir) {
                    File baseFile = new File(getClass().getResource("/").getFile());
                    inputFile = new File(baseFile, inputFilename);
                    outputFile = new File(baseFile, inputFilename +outSuffix);
                }else{
                    inputFile = new File(inputFilename);
                    outputFile = new File(inputFilename +outSuffix);
                }
                System.out.println("Input file canonical path: "+inputFile.getCanonicalPath());
                bis = new BufferedInputStream(
                        new FileInputStream(inputFile),
                        INPUT_BUFFER_SIZE);
                bos = new BufferedOutputStream(new FileOutputStream(outputFile));
                outGlobal = new PrintStream(bos);
            }else{
                bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE);
                bos = new BufferedOutputStream(System.out);
                outGlobal = new PrintStream(bos);
            }
            scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE);

            solveAll();
            outGlobal.flush();
        }catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static class EofException extends IOException{
    }

    public static class ByteScanner{
        InputStream is;

        public ByteScanner(InputStream is, int bufSizeInput, int bufSize){
            this.is = is;
            this.bufSizeInput = bufSizeInput;
            this.bufSize = bufSize;

            byteBufInput = new byte[this.bufSizeInput];
            byteBuf = new byte[this.bufSize];
        }

        public ByteScanner(byte[] data){
            byteBufInput = data;
            bufSizeInput = data.length;
            bufSize = data.length;
            byteBuf = new byte[bufSize];
            byteRead = data.length;
            bytePos = 0;
        }

        private int bufSizeInput;
        private int bufSize;

        byte[] byteBufInput;
        byte by=-1;
        int byteRead=-1;
        int bytePos=-1;

        byte[] byteBuf;
        int totalBytes;

        boolean eofMet = false;

        private byte nextByte() throws IOException{
            if (bytePos<0 || bytePos>=byteRead){
                byteRead = is==null? -1: is.read(byteBufInput);
                bytePos=0;
                if (byteRead<0){
                    byteBufInput[bytePos]=-1;//!!!
                    if (eofMet)
                        throw new EofException();
                    eofMet = true;
                }
            }
            return byteBufInput[bytePos++];
        }

        public byte nextVisibleChar() throws IOException{
            while ((by=nextByte())<=0x20);
            return by;
        }

        public String nextLine() throws IOException {
            readToken((byte)0x20);
            return new String(byteBuf,0,totalBytes);
        }

        // Reads token. Spacebar is separator char.
        public String nextToken() throws IOException {
            readToken((byte)0x21);
            return new String(byteBuf,0,totalBytes);
        }

        // Spacebar is included as separator char
        private void readToken() throws IOException {
            readToken((byte)0x21);
        }

        private void readToken(byte acceptFrom) throws IOException {
            totalBytes = 0;
            while ((by=nextByte())<acceptFrom);
            byteBuf[totalBytes++] = by;
            while ((by=nextByte())>=acceptFrom){
                byteBuf[totalBytes++] = by;
            }
        }

        public int nextInt() throws IOException{
            readToken();
            int num=0, i=0;
            boolean sign=false;
            if (byteBuf[i]=='-'){
                sign = true;
                i++;
            }
            for (; i<totalBytes; i++){
                num*=10;
                num+=byteBuf[i]-'0';
            }
            return sign?-num:num;
        }

        public long nextLong() throws IOException{
            readToken();
            long num=0;
            int i=0;
            boolean sign=false;
            if (byteBuf[i]=='-'){
                sign = true;
                i++;
            }
            for (; i<totalBytes; i++){
                num*=10;
                num+=byteBuf[i]-'0';
            }
            return sign?-num:num;
        }

        public double nextDouble() throws IOException{
            readToken();
            char[] token = new char[totalBytes];
            for (int i = 0; i < totalBytes; i++) {
                token[i] = (char)byteBuf[i];
            }
            return Double.parseDouble(new String(token));
        }

        public int[] loadIntArray(int size) throws IOException{
            int[] a = new int[size];
            for (int i = 0; i < a.length; i++) {
                a[i] = nextInt();
            }
            return a;
        }

        public long[] loadLongArray(int size) throws IOException{
            long[] a = new long[size];
            for (int i = 0; i < a.length; i++) {
                a[i] = nextLong();
            }
            return a;
        }
    }

    public static void main(String[] args) {
        new Main().run();
    }
}


import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {
	final int N, A, B, C, D;
	final char[] S;
	final Set<String> checked = new HashSet<String>();

	Main(int n, int a, int b, int c, int d, char[] s) {
		N = n;
		A = a;
		B = b;
		C = c;
		D = d;
		S = s;
	}

	public static void main(String[] args) {
		Main m;
		try (Scanner s = new Scanner(System.in)) {
			m = new Main(s.nextInt(),
					s.nextInt(),
					s.nextInt(),
					s.nextInt(),
					s.nextInt(),
					s.next().toCharArray());
		}

		if (m.move(m.A, m.B)) {
			System.out.println("Yes");
		} else {
			System.out.println("No");
		}
	}

	boolean move(int a, int b) {
		if (a == C && b == D) {
			return true;
		}

		if (checked.contains(a + "," + b)) {
			return false;
		}

		if (a > C) {
			return false;
		}

		if (b > D) {
			return false;
		}

		if (a == b) {
			return false;
		}

		if (S[b - 1] == '#') {
			return false;
		}

		if (S[a - 1] == '#') {
			return false;
		}

		boolean x = move(a + 2, b);
		if (!x) {
			checked.contains((a + 2) + "," + b);
			x = move(a, b + 2);
		}
		if (!x) {
			checked.contains(a + "," + (b + 2));
			x = move(a + 1, b);
		}
		if (!x) {
			checked.contains((a + 1) + "," + b);
			x = move(a, b + 1);
		}
		if (!x) {
			checked.contains(a + "," + (b + 1));
		}
		return x;
	}
}

Score : 400 points

Problem Statement

There are N squares arranged in a row, numbered 1, 2, ..., N from left to right.
You are given a string S of length N consisting of . and #. If the i-th character of S is #, Square i contains a rock; if the i-th character of S is ., Square i is empty.

In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

S is a string of length N consisting of . and #.

1 \leq A, B, C, D \leq N

Square A, B, C and D do not contain a rock.

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

Yes


// https://atcoder.jp/contests/agc034/tasks/agc034_a

import java.util.Scanner;

class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int A = sc.nextInt();
        int B = sc.nextInt();
        int C = sc.nextInt();
        int D = sc.nextInt();
        String S = sc.next();
        sc.close();
        boolean pass = true;
        for (int i=B;i<Math.max(C,D)-1;i++){
            String s1 = String.valueOf(S.charAt(i-1));
            String s2 = String.valueOf(S.charAt(i));
            if (s1.equals("#") && s2.equals("#")){
                System.out.println("No");
                return;
            }
        }
        for (int i=B;i<Math.min(C, D);i++){
            String s1 = String.valueOf(S.charAt(i-1));
            String s2 = String.valueOf(S.charAt(i));
            String s3 = String.valueOf(S.charAt(i+1));
            if (C>D){
                if (i==D-1){
                    if (s1.equals("#") || s3.equals("#")){
                        pass = false;
                        break;
                    }
                }
                if (s1.equals(".") && s2.equals(".") && s3.equals(".")){
                    pass = true;
                    break;
                } else {
                    pass = false;
                }
            }
        }
        if (pass){
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		//n角形のnの取得
		int n = scan.nextInt();
        //n角形の内角の和
        int ans = (n-2) * 180;
        	System.out.println(ans);
	}

}

Score : 100 points

Problem Statement

Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.

Print the answer in degrees, but do not print units.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print an integer representing the sum of the interior angles of a regular polygon with N sides.

Sample Input 1

3

Sample Output 1

180

The sum of the interior angles of a regular triangle is 180 degrees.

Sample Input 2

100

Sample Output 2

17640


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        System.out.println(180 * (n - 2));
    }
}


import java.util.*;

public class Main {
  public static long MOD = (long)Math.pow(10, 6) + 3;
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    long[] kai = new long[(int)MOD];
    long[] inkai = new long[(int)MOD];
    long[] in = new long[(int)MOD];
    kai[0] = 1;
    kai[1] = 1;
    inkai[0] = 1;
    inkai[1] = 1;
    in[1] = 1;
    for(long i = 2; i < MOD; i++) {
      kai[(int)i] = (i * kai[(int)i - 1]) % MOD;
      inkai[(int)i] = func(kai[(int)i], MOD - 2);
      in[(int)i] = func(i, MOD - 2);
    }
    int q = sc.nextInt();
    for(int i = 0; i < q; i++) {
      long x = sc.nextLong();
      long d = sc.nextLong();
      long n = sc.nextLong();
      long ans = 0;
      if(d == 0) {
        if(x == 0) {
          ans = 0;
        } else {
          ans = func(x, n % (MOD - 1));
        }
      } else {
        x = (x * in[(int)d]) % MOD;
        if(x == 0) {
          ans = 0;
        } else {
          if((int)(x + n - 1) >= MOD) {
            ans = 0;
          } else {
            long t = func(d, n % (MOD - 1));
            ans = (((kai[(int)(x + n - 1)] * inkai[(int)(x - 1)]) % MOD) * t) % MOD;
          }
        }
      }
      System.out.println(ans);
    }
  }

  public static long func(long a, long x) {
    if(x == 0) return 1;
    if(x >= 1) {
      if(x % 2 == 0) {
        long t = func(a, x / 2);
        return (t * t) % MOD;
      } else {
        long t = func(a, x - 1);
        return (a * t) % MOD;
      }
    }
    return 0;
  }
}

Score : 600 points

Problem Statement

Consider the following arithmetic progression with n terms:

x, x + d, x + 2d, \ldots, x + (n-1)d

What is the product of all terms in this sequence?
Compute the answer modulo 1\ 000\ 003.

You are given Q queries of this form.
In the i-th query, compute the answer in case x = x_i, d = d_i, n = n_i.

Constraints

1 \leq Q \leq 10^5

0 \leq x_i, d_i \leq 1\ 000\ 002

1 \leq n_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

Q
x_1 d_1 n_1
:
x_Q d_Q n_Q

Output

Print Q lines.

In the i-th line, print the answer for the i-th query.

Sample Input 1

2
7 2 4
12345 67890 2019

Sample Output 1

9009
916936

For the first query, the answer is 7 \times 9 \times 11 \times 13 = 9009.
Don't forget to compute the answer modulo 1\ 000\ 003.


import java.util.Arrays;
import java.util.Scanner;

public class Main {

	static int n, m;
	static int[][] swi;

	static int[] p = new int[10];//m個
	static int count = 0;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = Integer.parseInt(sc.next());
		m = Integer.parseInt(sc.next());
		swi = new int[m][n + 1];
		for (int i = 0; i < m; i++) {
			int k = Integer.parseInt(sc.next());
			swi[i][0] = k;
			for (int j = 1; j < k + 1; j++) {
				swi[i][j] = Integer.parseInt(sc.next());
			}
		}
		for (int i = 0; i < m; i++) {
			p[i] = Integer.parseInt(sc.next());
		}

		dfs(0, new int[n]);
		System.out.println(count);

	}

	static void dfs(int i, int[] onOff) {
		if (i == n) {
			if (isLightAll(onOff))
				count++;
			return;
		}

		dfs(i + 1, rtnArr(onOff, i, true));
		dfs(i + 1, rtnArr(onOff, i, false));
	}

	static int[] rtnArr(int[] a1, int i, boolean b) {
		int[] a2 = Arrays.copyOf(a1, n);
		a2[i] = b ? 1 : 0;
		return a2;
	}

	static boolean isLightAll(int[] onOff) {
		int sum = 0;
		for (int i = 0; i < m; i++) {
			for (int j = 1; j < swi[i][0] + 1; j++) {
				sum += onOff[swi[i][j] - 1];
			}
			if (sum % 2 != p[i])
				return false;
		}
		return true;
	}

}

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

2 3
2 1 2
1 1
1 2
0 0 1

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);

		int r = sc.nextInt();

		int D = sc.nextInt();
		int x2000 = sc.nextInt();
      	int x = r*x2000 -D;

      for(int i=1;i<=10;i++){
        x = r*x2000 - D;
        System.out.print(x);
      }

	}
}

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);

		int card = sc.nextInt();
		int gate = sc.nextInt();
		int min = 100000;
		int max = 0;

		int[] L = new int[gate];
		int[] R = new int[gate];
		for(int i = 0; i<gate; i++) {
			L[i] = sc.nextInt();
			R[i] = sc.nextInt();
		}
		for(int i=0; i<gate; i++) {
				max = Math.max(L[i], max);
				min = Math.min(R[i], min);
		}
			int anser = Math.max((min-max)+1, 0);
			System.out.println(anser);
		}

	}

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        double bunbo = 0;
        int a = 1;
        while (a < k) {
            a *= 2;
            bunbo += 1;
        }
        double bunshi = 1;
        for (int i = 2; i < n + 1; i++) {
            int count = 0;
            int j = i;
            while (j < k) {
                j *= 2;
                count += 1;
            }
            bunshi += Math.pow(2, bunbo - count);
        }
        System.out.println(bunshi / (Math.pow(2, bunbo) * n));
    }
}

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


import java.util.Scanner;
import java.util.ArrayList;

public class Main {

	static ArrayList<Pair>[] adjList;
	static boolean[] vis;
	static int[] color;

	public static void dfs(int u) {
		vis[u] = true;

		for(Pair p : adjList[u]) {
			if(!vis[p.v]) {
				color[p.v] = p.w % 2 == 0 ? color[u] : 1 - color[u];
				dfs(p.v);
			}
		}
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		adjList = new ArrayList[n];
		for(int i = 0; i < adjList.length; i++)
			adjList[i] = new ArrayList<Pair>();

		for(int i = 0; i < n - 1; i++) {
			int u = sc.nextInt(), v = sc.nextInt(), w = sc.nextInt();
			adjList[u - 1].add(new Pair(v - 1, w));
			adjList[v - 1].add(new Pair(u - 1, w));
		}

		vis = new boolean[n];
		color = new int[n];

		dfs(0);
		for(int i = 0; i < color.length; i++)
			System.out.println(color[i]);
	}

	public static class Pair implements Comparable<Pair>{
		int v, w;

		public Pair(int v) {
			this.v = v;
		}

		public Pair(int v, int w) {
			this(v);
			this.w = w;
		}

		public int compareTo(Pair p) {
			if(this.w == p.w)
				return this.v - p.v;
			return this.w - p.w;
		}
	}
}

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

5
2 5 2
2 3 10
1 3 8
3 4 2

Sample Output 2

1
0
1
0
1


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);

        int numbers = sc.nextInt();
        int end = sc.nextInt();
        int count = 0;

        while(end<=numbers){
            count++;
            end++;
        }

        System.out.println(count);
    }
}

Score : 100 points

Problem Statement

Snuke has N integers: 1,2,\ldots,N.
He will choose K of them and give those to Takahashi.

How many ways are there to choose K consecutive integers?

Constraints

All values in input are integers.

1 \leq K \leq N \leq 50

Input

Input is given from Standard Input in the following format:

N K

Output

Print the answer.

Sample Input 1

3 2

Sample Output 1

2

There are two ways to choose two consecutive integers: (1,2) and (2,3).

Sample Input 2

13 3

Sample Output 2

11


import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@SuppressWarnings("unused")
public class Main {

	//final boolean isDebug = true;
	final boolean isDebug = false;
	String fileName = "input.txt";
	FastScanner sc;
	PrintWriter out;
	final int MOD = (int)1e9+7;
	final int INF = Integer.MAX_VALUE / 2;

	void solve() throws Exception{
		System.out.println((sc.nextInt() - sc.nextInt() + 1));
	}

	/* end solve */

	/* main */
	public static void main(String[] args) throws Exception {
		new Main().m();
	}

	void m() throws Exception {
		long S = System.currentTimeMillis();
		sc = (isDebug) ? new FastScanner(new FileInputStream(fileName)) : new FastScanner(System.in);
		out = new PrintWriter(System.out);
		solve();
		out.flush();
		long G = System.currentTimeMillis();
		if(isDebug){
			System.out.println("---Debug---");
			System.out.printf("%8d ms\n", (G-S));
		}
	}
	/* end main */
}
/* end Main */

class Pair{
	int x, y;
	public Pair(int y, int x){
		this.x = x; this.y = y;
	}
}

class FastScanner {
    private InputStream in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    public FastScanner(InputStream in) {
		this.in = in;
	}
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    private int readByte() {
    	if (hasNextByte()) return buffer[ptr++];
    	else return -1;
    }
    private static boolean isPrintableChar(int c){
    	return 33 <= c && c <= 126;
    }
    public boolean hasNext() {
    	while(hasNextByte() && !isPrintableChar(buffer[ptr]))
    		ptr++; return hasNextByte();
    }
    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    public String nextLine() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(b != 10) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    public long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b)){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }
    public double nextDouble() {
    	return Double.parseDouble(next());
    }
}


import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        String[] wordArr = new String[N];
        for (int i = 0; i < N; i++) {
            wordArr[i] = sc.next();
        }
        long lastA = Arrays.stream(wordArr).filter(s -> s.endsWith("A")).count(); // O(N)
        long startB = Arrays.stream(wordArr).filter(s -> s.startsWith("B")).count(); // O(N)
        long containsAB = Arrays.stream(wordArr).filter(s -> s.contains("AB")).count(); // O(N)

        long min = Math.min(lastA, startB);

        if (lastA < 1 || startB < 1) {
            System.out.println(containsAB);
        } else {
            System.out.println(containsAB + min);
        }
    }
}

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


import java.io.*;
import java.util.ArrayList;

class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();
        long N = Long.parseLong(str);
        ArrayList<Long> num = new ArrayList<>();
        long div;
        for (int i=1;i<Math.sqrt(N);i++){
            div = (long)(N-i)/i;
            if (N/div==N%div){
                num.add(div);
            }
        }
        long ans = 0;
        for (long n:num){
            ans += n;
        }
        System.out.println(ans);
    }
}

Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        long N = scan.nextLong();
        BigInteger answer = BigInteger.ZERO;
        long temp = (long) Math.sqrt(N);
        temp += 10;
        BigInteger x = new BigInteger(Long.toString(temp));
        BigInteger y = BigInteger.ZERO;
        do {
            x = x.subtract(BigInteger.ONE);
            y = (x.add(BigInteger.ONE)).multiply(x);
        }
        while ((new BigInteger(Long.toString(N)).compareTo(y)) < 1);
        for (int i = 1; i < x.longValue()+1; i++) {
            if (N % i != 0) {
                continue;
            }
            answer = answer.add(new BigInteger(Long.toString(N / i - 1)));
        }
        System.out.println(answer);
    }
}


import java.util.*;

class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int sec = sc.nextInt();
        int bisc = sc.nextInt();
        int limit = sc.nextInt();

        int ans = (int)(limit / sec) * bisc;
        System.out.println(ans);
    }
}

Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


import java.util.*;

public class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    int b = sc.nextInt();
    int t = sc.nextInt();
    int ans = 0;

    for(int i=1;i<=t;i++){
      if(t>=i*a){
        ans += b;
      }
    }
    System.out.println(ans);
  }
}


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int []v = new int [n];
		int []c = new int [n];
		int []a = new int [n];

		for(int i = 0; i < n;i++) {
			v[i] = sc.nextInt();
		}
		for(int j = 0; j < n; j++) {
			c[j] = sc.nextInt();
			a[j] = v[j] - c[j];
		}
		int ans = 0;
		for(int i = 0; i < n ; i++) {
			if (a[i] >= 0) {
				ans += a[i];
			}

		}
		System.out.println(ans);

	}

}

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.NoSuchElementException;

public class Main{
	static FastScanner sc = new FastScanner();
	static PrintWriter out = new PrintWriter(System.out);
	//static String S;
	//static int h;
	//static int w;
	static int n;

	public static void main(String[] args) {
		n = sc.nextInt();

		long a [] = sc.nextLongArray(n, false);

		if (n==2) {
			out.println(Math.min(a[0]+a[1], -a[0]-a[1]));
		}

		else {
			long ans = 0;

			Arrays.sort(a);

			long aa = 0;
			long bb = 0;
			int ind = 0;

			for (int i=0; i<n-2; i+=2) {
				aa = a[i];
				bb = a[i+1];

				if (aa<=0 && bb<=0) {
					ans-=(aa+bb);
					ind = i+2;
				}

				else {
					ans+=Math.max(aa+bb, -aa-bb);
					ind = i+2;
					break;
				}
			}

			for (int i=ind; i<n; i++)
				ans+=a[i];

			out.println(ans);
		}

		out.flush();
	}

		static class FastScanner {
		    private final InputStream in = System.in;
		    private final byte[] buffer = new byte[1024];
		    private int ptr = 0;
		    private int buflen = 0;

		    private boolean hasNextByte() {
		      if (ptr < buflen) {
		        return true;
		      } else {
		        ptr = 0;
		        try {
		          buflen = in.read(buffer);
		        } catch (IOException e) {
		          e.printStackTrace();
		        }
		        if (buflen <= 0) {
		          return false;
		        }
		      }
		      return true;
		    }

		    private int readByte() {
		      if (hasNextByte()) return buffer[ptr++];
		      else return -1;
		    }

		    private static boolean isPrintableChar(int c) {
		      return 33 <= c && c <= 126;
		    }

		    private void skipUnprintable() {
		      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
		    }

		    public boolean hasNext() {
		      skipUnprintable();
		      return hasNextByte();
		    }

		    public String next() {
		      if (!hasNext()) throw new NoSuchElementException();
		      StringBuilder sb = new StringBuilder();
		      int b = readByte();
		      while (isPrintableChar(b)) {
		        sb.appendCodePoint(b);
		        b = readByte();
		      }
		      return sb.toString();
		    }

		    public long nextLong() {
		      if (!hasNext()) throw new NoSuchElementException();
		      long n = 0;
		      boolean minus = false;
		      int b = readByte();
		      if (b == '-') {
		        minus = true;
		        b = readByte();
		      }
		      if (b < '0' || '9' < b) {
		        throw new NumberFormatException();
		      }
		      while (true) {
		        if ('0' <= b && b <= '9') {
		          n *= 10;
		          n += b - '0';
		        } else if (b == -1 || !isPrintableChar(b)) {
		          return minus ? -n : n;
		        } else {
		          throw new NumberFormatException();
		        }
		        b = readByte();
		      }
		    }

		    public int nextInt() {
		      return (int) nextLong();
		    }

		    public int[] nextIntArray(int N, boolean oneBased) {
		      if (oneBased) {
		        int[] array = new int[N + 1];
		        for (int i = 1; i <= N; i++) {
		          array[i] = sc.nextInt();
		        }
		        return array;
		      } else {
		        int[] array = new int[N];
		        for (int i = 0; i < N; i++) {
		          array[i] = sc.nextInt();
		        }
		        return array;
		      }
		    }

		    public long[] nextLongArray(int N, boolean oneBased) {
		      if (oneBased) {
		        long[] array = new long[N + 1];
		        for (int i = 1; i <= N; i++) {
		          array[i] = sc.nextLong();
		        }
		        return array;
		      } else {
		        long[] array = new long[N];
		        for (int i = 0; i < N; i++) {
		          array[i] = sc.nextLong();
		        }
		        return array;
		      }
		    }
		  }

		}

Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

The output may not fit into a 32-bit integer type.