src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class OlyaAndMagicalSquare { void solve() { long[] dp = new long[32]; dp[0] = 0; for (int i = 1; i < 32; i++) { dp[i] = 4 * dp[i - 1] + 1; } int T = in.nextInt(); L: while (T-- > 0) { int n = in.nextInt(); long k = in.nextLong(); if (n > 31) { out.println("YES " + (n - 1)); continue; } long tot = 0; for (int a = n - 1; a >= 0; a--) { k -= (1L << (n - a)) - 1; if (k < 0) break; if (k == 0) { out.println("YES " + a); continue L; } long limit = (1L << (n + 1 - a)) - 3; if (k <= tot || dp[a] > 0 && (k - tot + dp[a] - 1) / dp[a] <= limit) { out.println("YES " + a); continue L; } tot += dp[a] * limit; } out.println("NO"); } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new OlyaAndMagicalSquare().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args){ Scanner s= new Scanner(System.in); int n=s.nextInt();StringBuilder sb=new StringBuilder(); long[] a=new long[n/2]; for(int i=0;i<n/2;i++){ a[i]=s.nextLong(); }int j=0;long[] a2=new long[n/2];long[] a1=new long[n/2]; a1[j]=a[a.length-1]/2; a2[j]=a[a.length-1]-a[a.length-1]/2; for(int i=(n-1)/2-1;i>=0;i--){ // a1[j]=a[i]/2;a2[j++]=a[i]-a[i]/2; long n1=a1[j]; if((a[i]-n1)<a2[j]){ a2[j+1]=a2[j++];a1[j]=a[i]-a2[j]; }else{a1[++j]=n1;a2[j]=a[i]-n1;} }int k=0;//int[] ans=new int[2*n]; for(int i=(n-1)/2;i>=0;i--) sb.append(a1[i]+" "); for(int i=0;i<n/2;i++) sb.append(a2[i]+" "); System.out.println(sb.toString()); } }
linear
1093_C. Mishka and the Last Exam
CODEFORCES
import java.util.*; public class Pizza { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long num = sc.nextLong() + 1; sc.close(); System.out.println(num % 2 == 0 || num == 1 ? num / 2 : num); } }
constant
979_A. Pizza, Pizza, Pizza!!!
CODEFORCES
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Solution { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.solve()); } private int solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[m]; for (int i = 0; i < m; ++i) a[i] = in.nextInt(); if (n > m) return 0; Map<Integer, Integer> map = new HashMap<>(); for (int k: a) map.put(k, map.getOrDefault(k, 0) + 1); List<Integer> keySet = new ArrayList<>(map.keySet()); int end = m / n; keySet.sort((u, v) -> -Integer.compare(u, v)); do { int count = 0; for (int k: keySet) { count += map.get(k) / end; if (count >= n) return end; } } while (--end > 0); return 0; } }
nlogn
1011_B. Planning The Expedition
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Cf1017A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int result = 1; int thomasSum = 0; StringTokenizer stk; stk = new StringTokenizer(br.readLine()); int first = Integer.parseInt(stk.nextToken()); int second = Integer.parseInt(stk.nextToken()); int third = Integer.parseInt(stk.nextToken()); int fourth = Integer.parseInt(stk.nextToken()); thomasSum = first + second + third + fourth; int tmp; for (int i = 1; i < n; i++) { stk = new StringTokenizer(br.readLine()); first = Integer.parseInt(stk.nextToken()); second = Integer.parseInt(stk.nextToken()); third = Integer.parseInt(stk.nextToken()); fourth = Integer.parseInt(stk.nextToken()); tmp = first + second + third + fourth; if (tmp > thomasSum) result++; } System.out.println(result); } }
linear
1017_A. The Rank
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long k = sc.nextLong(); System.out.println(solve(n, k)); sc.close(); } static long solve(long n, long k) { return Math.max(0, Math.min(n, k - 1) - ((k + 2) / 2) + 1); } }
constant
1023_B. Pair of Toys
CODEFORCES
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; public class C { static StringBuilder st = new StringBuilder(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Point [] square = new Point [4] ; Point [] rotSquare = new Point[4] ; for(int i = 0 ; i < 4 ;i++) square[i] = new Point(sc.nextInt() , sc.nextInt()); for(int i = 0 ; i < 4 ;i++) rotSquare[i] = new Point(sc.nextInt() , sc.nextInt()); boolean can = false ; for(int x = -100 ; x <= 100 ; x++) for(int y = -100 ; y <= 100 ; y++) can |= inside(new Point(x , y), square) & inside(new Point (x , y), rotSquare); out.println(can ? "YES" : "NO"); out.flush(); out.close(); } static int crossProduct(Point a , Point b) { int ans = a.x * b.y - a.y * b.x ; if(ans < 0)return -1 ; if(ans == 0) return 0 ; return 1 ; } static boolean inside(Point a , Point [] points) { boolean allPos = true ; boolean allNeg = true ; for(int i = 0 ; i < 4 ; i++) { Point v1 = new Point (points[i].x - a.x , points[i].y - a.y) ; Point v2 = new Point (points[(i + 1) % 4].x - a.x , points[(i + 1) % 4].y - a.y) ; allPos &= crossProduct(v1, v2) >= 0; allNeg &= crossProduct(v1, v2) <= 0; } return allPos | allNeg ; } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
constant
994_C. Two Squares
CODEFORCES
import jdk.nashorn.internal.objects.NativeArray; import javax.swing.JOptionPane ; import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import java.sql.SQLSyntaxErrorException; import java.util.Arrays; import java.util.Scanner; import java.util.Vector; import static jdk.nashorn.internal.objects.NativeArray.sort; import static jdk.nashorn.internal.runtime.ScriptObject.toPropertyDescriptor; public class Dialog1 { private static int n ; private static String s ; private static char[] a; public static void main(String[] args) { Scanner input = new Scanner(System.in); n = input.nextInt() ; s = input.next() ; a = s.toCharArray(); for(int i = 0 ; i < 200 ; ++i) { int cur = i ; boolean fl = true ; for(int j = 0 ; j < n ; ++j) { if(a[j] == '+') ++cur ; else --cur ; if(cur < 0) fl = false ; } if(fl) { System.out.print(cur); return ; } } } }
linear
1159_A. A pile of stones
CODEFORCES
import java.io.*; import java.util.*; public class Solution { static class Data{ int x,i; Data(int x,int i){ this.x = x; this.i = i; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s = br.readLine().split("\\s"); int N = Integer.parseInt(s[0]); int K = Integer.parseInt(s[1]); s = br.readLine().split("\\s"); int[] arr = new int[N]; for(int i=0;i<N;++i) arr[i] = Integer.parseInt(s[i]); solve(N,K,arr); } private static void solve(int N,int K,int[] arr){ PriorityQueue<Data> pq = new PriorityQueue<Data>(2000,(a,b) -> a.x - b.x == 0 ? b.i - a.i : b.x - a.x); for(int i=0;i<arr.length;++i){ pq.offer(new Data(arr[i],i)); } int tot_sum = 0; List<Integer> ls = new ArrayList<>(); Set<Integer> set = new HashSet<>(); for(int i=1;i<=K;++i){ Data t = pq.poll(); tot_sum += t.x; set.add(t.i); } int last = -1; for(int i =0;i<arr.length;++i){ if(set.contains(i)){ K--; //System.out.println(i); if(K == 0) ls.add(arr.length-last-1); else ls.add(i-last); last = i; } } System.out.println(tot_sum); int size = ls.size(); for(int i=0;i<size;++i){ System.out.print(ls.get(i) + " "); } } }
nlogn
1006_B. Polycarp's Practice
CODEFORCES
import java.io.*; import java.util.*; public class MainG { static StdIn in = new StdIn(); static PrintWriter out = new PrintWriter(System.out); static long M=(long)1e9+7; public static void main(String[] args) { char[] cs = in.next().toCharArray(); int n=cs.length; int[] x = new int[n]; for(int i=0; i<n; ++i) x[i]=cs[i]-'0'; long[] dp1 = new long[n+1]; for(int i=0; i<n; ++i) dp1[i+1]=(x[i]+dp1[i]*10)%M; long ans=0; for(int d1=1; d1<=9; ++d1) { long[][] dp2 = new long[2][n+1]; for(int i=0; i<n; ++i) { dp2[0][i+1]=x[i]>=d1?(10*dp2[0][i]+1)%M:dp2[0][i]; for(int d2=0; d2<x[i]; ++d2) dp2[1][i+1]=((d2>=d1?10*(dp2[0][i]+dp2[1][i])+dp1[i]+1:dp2[0][i]+dp2[1][i])+dp2[1][i+1])%M; for(int d2=x[i]; d2<=9; ++d2) dp2[1][i+1]=((d2>=d1?10*dp2[1][i]+dp1[i]:dp2[1][i])+dp2[1][i+1])%M; } ans+=dp2[0][n]+dp2[1][n]; } out.println(ans%M); out.close(); } interface Input { public String next(); public String nextLine(); public int nextInt(); public long nextLong(); public double nextDouble(); } static class StdIn implements Input { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public StdIn() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public StdIn(InputStream in) { try{ din = new DataInputStream(in); } catch(Exception e) { throw new RuntimeException(); } buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == ' ' || c == '\n'||c=='\r') break; s.append((char)c); c=read(); } return s.toString(); } public String nextLine() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == '\n'||c=='\r') break; s.append((char)c); c = read(); } return s.toString(); } public int nextInt() { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public int[] readIntArray(int n) { int[] ar = new int[n]; for(int i=0; i<n; ++i) ar[i]=nextInt(); return ar; } public long nextLong() { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long[] readLongArray(int n) { long[] ar = new long[n]; for(int i=0; i<n; ++i) ar[i]=nextLong(); return ar; } public double nextDouble() { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() { try{ if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } catch(IOException e) { throw new RuntimeException(); } } public void close() throws IOException { if (din == null) return; din.close(); } } }
quadratic
908_G. New Year and Original Order
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import java.util.HashMap; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){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 long l(){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 int i(){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 double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String args[]) { Reader sc=new Reader(); PrintWriter out=new PrintWriter(System.out); int n=sc.i(); String s1=sc.s(); String s2=sc.s(); int pos1=-1; int pos2=-1; int arr[][][]=new int[100][100][2]; for(int i=0;i<n;i++) { if(s1.charAt(i)!=s2.charAt(i)) { if(arr[s2.charAt(i)-97][s1.charAt(i)-97][0]==1) { pos2=i; pos1=arr[s2.charAt(i)-97][s1.charAt(i)-97][1]; break; } arr[s1.charAt(i)-97][s2.charAt(i)-97][0]=1; arr[s1.charAt(i)-97][s2.charAt(i)-97][1]=i; } } int ham=0; for(int i=0;i<n;i++) { if(s1.charAt(i)!=s2.charAt(i)) ham++; } if(pos1!=-1&&pos2!=-1) { System.out.println(ham-2); System.out.println(pos1+1+" "+(pos2+1)); System.exit(0); } int arr1[][]=new int[100][2]; int arr2[][]=new int[100][2]; for(int i=0;i<n;i++) { if(s1.charAt(i)!=s2.charAt(i)) { if(arr1[s1.charAt(i)-97][0]==1) { pos2=i; pos1=arr1[s1.charAt(i)-97][1]; break; } if(arr2[s2.charAt(i)-97][0]==1) { pos2=i; pos1=arr2[s2.charAt(i)-97][1]; break; } arr1[s2.charAt(i)-97][0]=1; arr1[s2.charAt(i)-97][1]=i; arr2[s1.charAt(i)-97][0]=1; arr2[s1.charAt(i)-97][1]=i; } } if(pos1!=-1&&pos2!=-1) { System.out.println(ham-1); System.out.println(pos1+1+" "+(pos2+1)); System.exit(0); } System.out.println(ham); System.out.println(pos1+" "+pos2); } }
linear
527_B. Error Correct System
CODEFORCES
import java.util.*; import java.math.*; import java.io.*; public class CF1068A { public CF1068A() { FS scan = new FS(); long n = scan.nextLong(), m = scan.nextLong(), k = scan.nextLong(), l = scan.nextLong(); long ceil = (k + l + m - 1) / m; if(k + l <= n && ceil * m <= n) System.out.println(ceil); else System.out.println(-1); } class FS { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while(!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch(Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { new CF1068A(); } }
constant
1068_A. Birthday
CODEFORCES
import java.util.*; import java.io.*; public class A { public static void main(String ar[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s1[]=br.readLine().split(" "); int n=Integer.parseInt(s1[0]); int S=Integer.parseInt(s1[1]); if(S%n==0) System.out.println(S/n); else System.out.println(S/n+1); } }
constant
1061_A. Coins
CODEFORCES
import java.util.*; public class helloWorld { public static void main(String[] args) { Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); int n = in.nextInt(); int ans = n - (a + b - c); if(ans < 1 || a >= n || b >= n || c > a || c > b) ans = -1; System.out.println(ans); in.close(); } }
constant
991_A. If at first you don't succeed...
CODEFORCES
import java.io.*; import java.util.*; public class Main { class node{ int data; node next; public node(int val){ data=val; next=null; } } class linkedlist{ node start; node end; int size; int turn; public linkedlist(){ start=null; end=null; size=0; } void add(int val){ if(size==0){ node t=new node(val); start=t; end=t; size++; } else{ node t=new node(val); end.next=t; end=end.next; size++; } } void myfunc(){ if(start.data>start.next.data){ // System.out.println("me ni hu"); node t=new node(start.next.data); start.next=start.next.next; end.next=t; end=end.next; } else{ // System.out.println("me hu"); int t=start.data; start=start.next; add(t); size--; } } int findmax(){ int m=0; node temp=start; for(int i=0;i<size;i++){ if(temp.data>m){ m=temp.data; } temp=temp.next; } return m; } void display(){ node temp=start; for(int i=0;i<size;i++){ System.out.print(temp.data+" "); temp=temp.next; } System.out.println(""); } } linkedlist l; public Main(){ l=new linkedlist(); } public static void main(String [] argv) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); Main ma=new Main(); String[] l1=in.readLine().split(" "); int n=Integer.parseInt(l1[0]); int q=Integer.parseInt(l1[1]); String[] ar=in.readLine().split(" "); int a1=Integer.parseInt(ar[0]); int b1=Integer.parseInt(ar[1]); for(int i=0;i<n;i++){ ma.l.add(Integer.parseInt(ar[i])); } int m=ma.l.findmax(); int[][] pair=new int[n][2]; int t=0; for(int i=0;i<n;i++){ if(ma.l.start.data==m) break; ma.l.myfunc(); pair[t][0]=ma.l.start.data; pair[t][1]=ma.l.start.next.data; t++; } int rl[]=new int[n]; node temp=ma.l.start; for(int i=0;i<n;i++){ rl[i]=temp.data; temp=temp.next; } for(int i=0;i<q;i++){ long a=Long.parseLong(in.readLine()); if(a==1){ System.out.println(a1 + " " + b1); } else{ if(a<=t+1){ System.out.println(pair[(int)(a-2)][0]+" "+pair[(int)(a-2)][1]); } else{ if((a-t)%(n-1)==0){ System.out.println(rl[0]+" "+rl[n-1]); } else{ System.out.println(rl[0]+" "+rl[(int)((a-t)%(n-1))]); } } } } } }
linear
1179_A. Valeriy and Deque
CODEFORCES
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Scanner; import java.util.Set; import java.util.StringJoiner; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Test { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] line = reader.readLine().split(" "); int w = Integer.valueOf(line[0]); int h = Integer.valueOf(line[1]); int n = Integer.valueOf(line[2]); Request[] requests = new Request[n]; for (int i = 0; i < n; i++) { line = reader.readLine().split(" "); requests[i] = new Request(line[0], Integer.valueOf(line[1])); } for (long e : solve(h, w, requests)) System.out.println(e); // int w = 200000, h = 200000, n = 400000; // Request[] requests = generate(w, h, n); // // long start = System.currentTimeMillis(); // solve(h, w, requests); // long end = System.currentTimeMillis(); // // System.out.println("Time: " + (end - start) + " ms"); } private static Request[] generate(int w, int h, int n) { Request[] requests = new Request[n]; Random rnd = new Random(); for (int i = 0; i < n; i++) { requests[i] = rnd.nextBoolean() ? new Request("V", rnd.nextInt(w)) : new Request("H", rnd.nextInt(h)); } return requests; } private static long[] solve(int h, int w, Request[] requests) { TreeSet<Integer> hTree = new TreeSet<>(); TreeSet<Integer> wTree = new TreeSet<>(); Queue<CoordinateWithSize> hHeap = new PriorityQueue<>(); Queue<CoordinateWithSize> wHeap = new PriorityQueue<>(); hTree.add(0); hTree.add(h); wTree.add(0); wTree.add(w); hHeap.add(new CoordinateWithSize(0, h)); wHeap.add(new CoordinateWithSize(0, w)); long[] res = new long[requests.length]; for (int i = 0; i < requests.length; i++) { Request request = requests[i]; switch (request.type) { case "H": { if (!hTree.contains(request.coordinate)) { int higher = hTree.higher(request.coordinate); int lower = hTree.lower(request.coordinate); hHeap.add(new CoordinateWithSize(lower, request.coordinate - lower)); hHeap.add(new CoordinateWithSize(request.coordinate, higher - request.coordinate)); hTree.add(request.coordinate); } break; } case "V": { if (!wTree.contains(request.coordinate)) { int higher = wTree.higher(request.coordinate); int lower = wTree.lower(request.coordinate); wHeap.add(new CoordinateWithSize(lower, request.coordinate - lower)); wHeap.add(new CoordinateWithSize(request.coordinate, higher - request.coordinate)); wTree.add(request.coordinate); } break; } default: throw new IllegalStateException("Unknown type [type=" + request.type + "]"); } while (true) { CoordinateWithSize c = hHeap.peek(); if (hTree.higher(c.coordinate) - c.coordinate == c.size) break; hHeap.remove(); } while (true) { CoordinateWithSize c = wHeap.peek(); if (wTree.higher(c.coordinate) - c.coordinate == c.size) break; wHeap.remove(); } res[i] = 1L * hHeap.peek().size * wHeap.peek().size; } return res; } private static class CoordinateWithSize implements Comparable<CoordinateWithSize> { private final int coordinate; private final int size; public CoordinateWithSize(int coordinate, int size) { this.coordinate = coordinate; this.size = size; } @Override public int compareTo(CoordinateWithSize o) { return Integer.compare(o.size, size); } } private static class Request { private final String type; private final int coordinate; public Request(String type, int coordinate) { this.type = type; this.coordinate = coordinate; } } }
nlogn
527_C. Glass Carving
CODEFORCES
import java.util.*; import java.io.*; public class Three{ public static void main(String[] args) { Scanner in = new Scanner (System.in); PrintWriter out = new PrintWriter(System.out); pair[] points = new pair [3]; for (int i = 0; i < 3; ++i) { int x = in.nextInt(); int y = in.nextInt(); points[i] = new pair (x, y); } Arrays.sort(points); int MaxY = Math.max(Math.max(points[0].y, points[1].y), points[2].y); int MinY = Math.min(Math.min(points[0].y, points[1].y), points[2].y); out.println(MaxY - MinY + points[2].x - points[0].x + 1); for (int i = MinY; i <= MaxY; ++i) out.println(points[1].x + " " + i); for (int i = points[0].x; i < points[1].x; ++i) out.println(i + " " + points[0].y); for (int i = points[1].x + 1; i <= points[2].x; ++i) out.println(i + " " + points[2].y); out.close(); } public static class pair implements Comparable<pair> { int x, y; public pair (int x_, int y_) { x = x_; y = y_; } @Override public int compareTo(pair o) { return x - o.x; } } }
nlogn
1086_A. Connect Three
CODEFORCES
import java.util.Scanner; public class Sasha1113A { static int solution(int n, int v){ int count; if(v>=n) return n-1; else{ count = (v-1) + ((n-v)*(n-v+1))/2; } return count; } public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int v = scan.nextInt(); System.out.print(solution(n, v)); } }
constant
1113_A. Sasha and His Trip
CODEFORCES
import java.io.*; import java.lang.*; public class CF1003E{ public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s = br.readLine().split(" "); int n = Integer.parseInt(s[0]); int d = Integer.parseInt(s[1]); int k = Integer.parseInt(s[2]); StringBuffer sb = new StringBuffer(); int[] rem = new int[n]; int[] deg = new int[n]; int i = 0; if(k == 1){ if(n <= 2){ }else{ System.out.println("NO"); return; } } for(i=0;i<d;i++){ if(i>=n-1){ System.out.println("NO"); return; } sb.append((i+1) +" " + (i+2)+"\n"); rem[i] = Math.min(i, d-i); deg[i]++; if(i+1<n) deg[i+1]++; } if(i<n){ rem[i] = 0; deg[i] = 1; } i++; int j = 0; for(;i<n;i++){ //For all remaining Nodes while(true){ if(j>=n){ System.out.println("NO"); return; } if(rem[j] > 0 && deg[j]<k){ deg[j]++; rem[i] = rem[j] - 1; sb.append((j+1)+" "+(i+1)+"\n"); deg[i]++; break; }else{ j++; } } } System.out.println("YES"); System.out.println(sb); } }
quadratic
1003_E. Tree Constructing
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] wide = new int[n], sta = new int[n]; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { wide[i] = sc.nextInt(); hm.put(wide[i], i + 1); } Util.sort(wide); sc.nextLine(); String s = sc.nextLine(); int tp = 0, pos = 0; StringBuilder out = new StringBuilder(); for (int i = 0; i < s.length(); i++) { int t; if (s.charAt(i) == '0') { t = wide[pos++]; sta[tp++] = t; } else t = sta[--tp]; out.append(hm.get(t) + " "); } System.out.println(out.toString()); sc.close(); } public static class Util { public static <T extends Comparable<T> > void merge_sort(T[] a) { Object[] aux = new Object[a.length]; merge_sort0(a, aux, 0, a.length); } public static <T extends Comparable<T> > void merge_sort(T[] a, int l, int r) { Object[] aux = new Object[a.length]; merge_sort0(a, aux, l, r); } @SuppressWarnings("unchecked") private static <T extends Comparable<T> > void merge_sort0(T[] a, Object[] temp, int l, int r) { if (l + 1 == r) return; int mid = (l + r) >> 1; merge_sort0(a, temp, l, mid); merge_sort0(a, temp, mid, r); int x = l, y = mid, c = l; while (x < mid || y < r) { if (y == r || (x < mid && a[x].compareTo(a[y]) <= 0)) temp[c++] = a[x++]; else temp[c++] = a[y++]; } for (int i = l; i < r; i++) a[i] = (T)temp[i]; } static final Random RAN = new Random(); public static <T extends Comparable<T> > void quick_sort(T[] a) { quick_sort0(a, 0, a.length); } public static <T extends Comparable<T> > void quick_sort(T[] a, int l, int r) { quick_sort0(a, l, r); } private static <T extends Comparable<T> > void quick_sort0(T[] a, int l, int r) { if (l + 1 >= r) return; int p = l + RAN.nextInt(r - l); T t = a[p]; a[p] = a[l]; a[l] = t; int x = l, y = r - 1; while (x < y) { while (x < y && a[y].compareTo(t) > 0) --y; while (x < y && a[x].compareTo(t) < 0) ++x; if (x < y) { T b = a[x]; a[x] = a[y]; a[y] = b; ++x; --y; } } quick_sort0(a, l, y + 1); quick_sort0(a, x, r); } static final int BOUND = 8; public static void bucket_sort(int[] a) { bucket_sort(a, 0, a.length); } public static void bucket_sort(int[] a, int l, int r) { int[] cnt = new int[1 << BOUND], b = new int[r - l + 1]; int y = 0; for (int i = l; i < r; i++) ++cnt[a[i] & (1 << BOUND) - 1]; while (y < Integer.SIZE) { for (int i = 1; i < 1 << BOUND; i++) cnt[i] += cnt[i - 1]; for (int i = r - 1; i >= l; i--) b[--cnt[a[i] >> y & (1 << BOUND) - 1]] = a[i]; y += BOUND; Arrays.fill(cnt, 0); for (int i = l; i < r; i++) { a[i] = b[i - l]; ++cnt[a[i] >> y & (1 << BOUND) - 1]; } } } public static void bucket_sort(long[] a) { bucket_sort(a, 0, a.length); } public static void bucket_sort(long[] a, int l, int r) { int[] cnt = new int[1 << BOUND]; long[] b = new long[r - l + 1]; int y = 0; while (y < Long.SIZE) { Arrays.fill(cnt, 0); for (int i = l; i < r; i++) ++cnt[(int) (a[i] >> y & (1 << BOUND) - 1)]; for (int i = 1; i < 1 << BOUND; i++) cnt[i] += cnt[i - 1]; for (int i = r - 1; i >= l; i--) b[--cnt[(int) (a[i] >> y & (1 << BOUND) - 1)]] = a[i]; for (int i = l; i < r; i++) a[i] = b[i - l]; y += BOUND; } } public static void sort(int[] a) { if (a.length <= 1 << BOUND) { Integer[] b = new Integer[a.length]; for (int i = 0; i < a.length; i++) b[i] = a[i]; quick_sort(b); for (int i = 0; i < a.length; i++) a[i] = b[i]; } else bucket_sort(a); } public static void sort(long[] a) { if (a.length <= 1 << BOUND) { Long[] b = new Long[a.length]; for (int i = 0; i < a.length; i++) b[i] = a[i]; quick_sort(b); for (int i = 0; i < a.length; i++) a[i] = b[i]; } else bucket_sort(a); } public static <T extends Comparable<T> > void sort(T[] a) { quick_sort(a); } public static void shuffle(int[] a) { Random ran = new Random(); for (int i = 0; i < a.length; i++) { int p = ran.nextInt(i + 1); int q = a[p]; a[p] = a[i]; a[i] = q; } } public static void shuffle(long[] a) { Random ran = new Random(); for (int i = 0; i < a.length; i++) { int p = ran.nextInt(i + 1); long q = a[p]; a[p] = a[i]; a[i] = q; } } public static <T> void shuffle(T[] a) { Random ran = new Random(); for (int i = 0; i < a.length; i++) { int p = ran.nextInt(i + 1); T q = a[p]; a[p] = a[i]; a[i] = q; } } } }
nlogn
982_B. Bus of Characters
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author @Ziklon */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); ABirthday solver = new ABirthday(); solver.solve(1, in, out); out.close(); } static class ABirthday { public void solve(int testNumber, InputReader in, OutputWriter out) { long N = in.readLong(), M = in.readLong(), K = in.readLong(), L = in.readLong(); long ans = ((L + K) - 1) / M + 1; if (ans * M > N || ans * M - K < L) out.printLine(-1); else out.printLine(ans); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } public void printLine(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; 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 long readLong() { 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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
constant
1068_A. Birthday
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[][] x = new int [200010][10]; String a = sc.nextLine(); String b = sc.nextLine(); int n = a.length(); int m = b.length(); for (int i = 1; i <= m; i++) { for (int j = 0; j < 2; j++) { x[i][j] = x[i - 1][j]; } ++x[i][b.charAt(i - 1) - '0']; } long res = 0; for (int i = 0, c; i < n; i++) { c = a.charAt(i) - '0'; for (int j = 0; j < 2; j++) { res += Math.abs(c - j) * (x[m - n + i + 1][j] - x[i][j]); } } System.out.println(res); } }
linear
608_B. Hamming Distance Sum
CODEFORCES
//Author: Patel Rag //Java version "1.8.0_211" import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long modExp(long x, long n, long mod) //binary Modular exponentiation { long result = 1; while(n > 0) { if(n % 2 == 1) result = (result%mod * x%mod)%mod; x = (x%mod * x%mod)%mod; n=n/2; } return result; } static long gcd(long a, long b) { if(a==0) return b; return gcd(b%a,a); } public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); long n = fr.nextLong(); long x = fr.nextLong(); long y = fr.nextLong(); long w = Long.min(x,y) - 1 + (x - Long.min(x,y)) + (y - Long.min(x,y)); long b = n - Long.max(x,y) + (Long.max(x,y) - x) + (Long.max(x,y) - y); if(w <= b) System.out.println("White"); else System.out.println("Black"); } } class Pair<U, V> // Pair class { public final U first; // first field of a Pair public final V second; // second field of a Pair private Pair(U first, V second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (!first.equals(pair.first)) return false; return second.equals(pair.second); } @Override public int hashCode() { return 31 * first.hashCode() + second.hashCode(); } public static <U, V> Pair <U, V> of(U a, V b) { return new Pair<>(a, b); } } class myComp implements Comparator<Pair> { public int compare(Pair a,Pair b) { if(a.first != b.first) return ((int)a.first - (int)b.first); if(a.second != b.second) return ((int)a.second - (int)b.second); return 0; } } class BIT //Binary Indexed Tree aka Fenwick Tree { public long[] m_array; public BIT(long[] dat) { m_array = new long[dat.length + 1]; Arrays.fill(m_array,0); for(int i = 0; i < dat.length; i++) { m_array[i + 1] = dat[i]; } for(int i = 1; i < m_array.length; i++) { int j = i + (i & -i); if(j < m_array.length) { m_array[j] = m_array[j] + m_array[i]; } } } public final long prefix_query(int i) { long result = 0; for(++i; i > 0; i = i - (i & -i)) { result = result + m_array[i]; } return result; } public final long range_query(int fro, int to) { if(fro == 0) { return prefix_query(to); } else { return (prefix_query(to) - prefix_query(fro - 1)); } } public void update(int i, long add) { for(++i; i < m_array.length; i = i + (i & -i)) { m_array[i] = m_array[i] + add; } } }
constant
1075_A. The King's Race
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author MaxHeap */ 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); CBanhMi solver = new CBanhMi(); solver.solve(1, in, out); out.close(); } static class CBanhMi { long mod = (long) (1e9 + 7); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int q = in.nextInt(); long[] two = new long[n + 1]; two[0] = 1; for (int i = 1; i <= n; ++i) { two[i] = (two[i - 1] * 2L); two[i] %= mod; } char[] s = in.nextCharArray(); int[] acc = new int[n + 1]; for (int i = 1; i <= n; ++i) { acc[i] = s[i - 1] == '0' ? 0 : 1; acc[i] += acc[i - 1]; } // 0 0 1 1 | 1: 1 1 2| 2: 2 3| 4: 5| 9 // 0 1 1 1| 1: 1 2 2| 2: 3 3| 5: 6| 11 // 0 1 1 wwqwq| 1: 1 2 2| 3: 5 3| 8: 8| 16 // 0 0 1 1| 1: 1 1 2| 3: 3 3| 6: 6| 12 // 0 0 0 1| 1: 1 1 1| 2: 2 2| 4: 4| 8 while (q-- > 0) { int f = in.nextInt(); int t = in.nextInt(); int ones = acc[t] - acc[f - 1]; int zeros = (t - f + 1) - ones; if (ones == 0) { out.println(0); } else { long ans = two[t - f + 1] - (zeros > 0 ? two[zeros] : 0); if (zeros == 0) { --ans; } ans = (ans + mod) % mod; out.println(ans); } } } } static class InputReader implements FastIO { private InputStream stream; private static final int DEFAULT_BUFFER_SIZE = 1 << 16; private static final int EOF = -1; private byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == EOF) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return EOF; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public String next() { int c; while (isSpaceChar(c = this.read())) { } StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = this.read())) { result.appendCodePoint(c); } return result.toString(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF; } public char[] nextCharArray() { return next().toCharArray(); } } static interface FastIO { } }
linear
1062_C. Banh-mi
CODEFORCES
import java.awt.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(), m = scanner.nextInt(); int[] vertical = new int[n]; for (int i = 0; i < n; i++) { vertical[i] = scanner.nextInt(); } Arrays.sort(vertical); ArrayList<Integer> horisontal = new ArrayList<>(); int amount = 0; for (int i = 0; i < m; i++) { int x1 = scanner.nextInt(), x2 = scanner.nextInt(), y = scanner.nextInt(); if (x1 == 1) { amount++; horisontal.add(x2); } } Collections.sort(horisontal); if (amount == 0) { System.out.println(0); return; } int minVal = amount, horSize = horisontal.size(), verLen = vertical.length; int h = 0, v = 0; for (; v < verLen && h < horSize; ) { while (h < horSize && horisontal.get(h) < vertical[v]){ h++; amount--; } minVal = Math.min(minVal, amount + v); while (h < horSize && v < verLen && horisontal.get(h) >= vertical[v]){ minVal = Math.min(minVal, amount + v); v++; } } if(horisontal.get(horSize - 1) < 1E9){ minVal = Math.min(minVal, v); } System.out.println(minVal); } }
nlogn
1075_C. The Tower is Going Home
CODEFORCES
import java.io.*; import java.util.*; public class Codechef{ public static void main(String []args){ Scanner in = new Scanner(System.in); long n=in.nextLong(); long m=in.nextLong(); long k=in.nextLong(); long l=in.nextLong(); long j=((k+l)/m); if((k+l)%m!=0)j++; if((k+l>n) || j*m>n) { System.out.println(-1); }else { System.out.println(j); } } }
constant
1068_A. Birthday
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; public class RENAMETHISBITCH { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { int n = sc.nextInt(); BigInteger m = sc.nextBigInteger(); System.out.println(m.mod(BigInteger.valueOf(2).pow(n))); } catch (Exception e) { e.printStackTrace(); } } }
constant
913_A. Modular Exponentiation
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] arr = new int[n]; HashMap<Integer, Integer> map = new HashMap<>(); StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { int x = Integer.parseInt(st.nextToken()); arr[i] = x; if (!map.containsKey(x)) { map.put(x, 1); } else { map.replace(x, map.get(x) + 1); } } int[] power = new int[31]; for (int i = 0; i < 31; i++) { power[i] = 1 << i; // 0 100=4 1000=8 10000=16 } int c = 0; for (int i = 0; i < n; i++) { boolean f = false; for (int j = 0; j <= 30; j++) { int check = power[j] - arr[i]; if ((map.containsKey(check) && check != arr[i])) { f = true; break;} if((map.containsKey(check) && check == arr[i] && map.get(check) >=2)) { f = true; break; } } if (!f) { c++; } } System.out.println(c); } }
nlogn
1005_C. Summarize to the Power of Two
CODEFORCES
import java.util.*; import java.io.*; public class C994{ static double area(double x1,double y1,double x2,double y2,double x3,double y3){ return Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } public static void main(String args[])throws IOException{ Scanner sc=new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter pw=new PrintWriter(System.out); int x11=sc.nextInt(); int y11=sc.nextInt(); int x12=sc.nextInt(); int y12=sc.nextInt(); int x13=sc.nextInt(); int y13=sc.nextInt(); int x14=sc.nextInt(); int y14=sc.nextInt(); double x1c=(x11+x12+x13+x14)/4.0; double y1c=(y11+y12+y13+y14)/4.0; int x21=sc.nextInt(); int y21=sc.nextInt(); int x22=sc.nextInt(); int y22=sc.nextInt(); int x23=sc.nextInt(); int y23=sc.nextInt(); int x24=sc.nextInt(); int y24=sc.nextInt(); double x2c=(x21+x22+x23+x24)/4.0; double y2c=(y21+y22+y23+y24)/4.0; double a1=area(x11,y11,x12,y12,x13,y13)+area(x11,y11,x13,y13,x14,y14); double a2=area(x21,y21,x22,y22,x23,y23)+area(x21,y21,x23,y23,x24,y24); if(a1==area(x11,y11,x12,y12,x21,y21)+area(x11,y11,x21,y21,x14,y14)+area(x21,y21,x12,y12,x13,y13)+area(x21,y21,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x22,y22)+area(x11,y11,x22,y22,x14,y14)+area(x22,y22,x12,y12,x13,y13)+area(x22,y22,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x23,y23)+area(x11,y11,x23,y23,x14,y14)+area(x23,y23,x12,y12,x13,y13)+area(x23,y23,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x24,y24)+area(x11,y11,x24,y24,x14,y14)+area(x24,y24,x12,y12,x13,y13)+area(x24,y24,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x2c,y2c)+area(x11,y11,x2c,y2c,x14,y14)+area(x2c,y2c,x12,y12,x13,y13)+area(x2c,y2c,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x11,y11)+area(x21,y21,x11,y11,x24,y24)+area(x11,y11,x22,y22,x23,y23)+area(x11,y11,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x12,y12)+area(x21,y21,x12,y12,x24,y24)+area(x12,y12,x22,y22,x23,y23)+area(x12,y12,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x13,y13)+area(x21,y21,x13,y13,x24,y24)+area(x13,y13,x22,y22,x23,y23)+area(x13,y13,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x14,y14)+area(x21,y21,x14,y14,x24,y24)+area(x14,y14,x22,y22,x23,y23)+area(x14,y14,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x1c,y1c)+area(x21,y21,x14,y14,x2c,y2c)+area(x1c,y1c,x22,y22,x23,y23)+area(x1c,y1c,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } pw.println("NO"); pw.close(); } }
constant
994_C. Two Squares
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); TaskD.Pair[] p = new TaskD.Pair[n]; for (int i = 0; i < n; ++i) { p[i] = new TaskD.Pair(in.nextLong(), in.nextLong()); } Arrays.sort(p); int last = 0; int ans = 1; for (int i = 1; i < n; ++i) { if (p[i].x - p[i].w >= p[last].x + p[last].w) { last = i; ++ans; } } out.println(ans); } static class Pair implements Comparable<TaskD.Pair> { long x; long w; public Pair(long x, long w) { this.x = x; this.w = w; } public int compareTo(TaskD.Pair o) { return Long.compare(x + w, o.x + o.w); } public String toString() { return x + " " + w; } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
nlogn
528_B. Clique Problem
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class pr988B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); ArrayList<String> a = new ArrayList<>(); for (int i = 0; i < n; i++) { a.add(br.readLine()); } if(solve(n, a)){ out.println("YES"); for (String s : a) { out.println(s); } } else out.println("NO"); out.flush(); out.close(); } private static boolean solve(int n, ArrayList<String> a) { a.sort(Comparator.comparingInt(String::length)); for (int i = 0; i < n - 1; i++) { if(!a.get(i+1).contains(a.get(i))) return false; } return true; } }
nlogn
988_B. Substrings Sort
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class TwoSquares { int INF = 1000; void solve() { int[][] s1 = new int[4][2]; for (int i = 0; i < 4; i++) { s1[i][0] = in.nextInt(); s1[i][1] = in.nextInt(); } int[][] s2 = new int[4][2]; for (int i = 0; i < 4; i++) { s2[i][0] = in.nextInt(); s2[i][1] = in.nextInt(); } if (ok(s1, s2)) { out.println("Yes"); return; } rotate(s1); rotate(s2); if (ok(s2, s1)) { out.println("Yes"); return; } out.println("No"); } void rotate(int[][] s) { for (int i = 0; i < 4; i++) { int x = s[i][0], y = s[i][1]; s[i][0] = x - y; s[i][1] = x + y; } } boolean ok(int[][] s1, int[][] s2) { int xmin = INF, xmax = -INF, ymin = INF, ymax = -INF; for (int i = 0; i < 4; i++) { xmin = Math.min(xmin, s1[i][0]); xmax = Math.max(xmax, s1[i][0]); ymin = Math.min(ymin, s1[i][1]); ymax = Math.max(ymax, s1[i][1]); } for (int i = 0; i < 4; i++) { if (s2[i][0] >= xmin && s2[i][0] <= xmax && s2[i][1] >= ymin && s2[i][1] <= ymax) return true; } int[] mid2 = new int[]{s2[0][0] + s2[2][0], s2[0][1] + s2[2][1]}; return mid2[0] >= xmin * 2 && mid2[0] <= xmax * 2 && mid2[1] >= ymin * 2 && mid2[1] <= ymax * 2; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new TwoSquares().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
constant
994_C. Two Squares
CODEFORCES
import java.util.*; //201920181 public class Polycarp{ public static void main(String args[]){ Scanner s = new Scanner(System.in); int rem[] = new int[3]; Arrays.fill(rem,-1); rem[0] = 0; char ch[] = s.next().toCharArray(); int n = ch.length; long dp[] = new long[n]; int sum = 0; for(int i=0;i<ch.length;i++){ sum = sum + (ch[i]-48); if(rem[sum%3] != -1) if(i>0){ dp[i] = Math.max(dp[i-1],dp[rem[sum%3]]+1);} else dp[i] = 1; else if(i>0) dp[i] = dp[i-1]; rem[sum%3] = i; sum = sum%3; } System.out.println(dp[n-1]); } }
linear
1005_D. Polycarp and Div 3
CODEFORCES
import java.awt.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long n = scanner.nextLong(); long x = scanner.nextLong(), y = scanner.nextLong(); long whiteSteps, blackSteps; if(x == 1 || y == 1){ whiteSteps = (x - 1) + (y - 1); } else { whiteSteps = Math.min((x - 1) + Math.abs(y - x), (y - 1) + Math.abs(y - x)); } if(x == n || y == n){ blackSteps = (n - x) + (n - y); } else { blackSteps = Math.min((n - x) + Math.abs(y - x), (n - y) + Math.abs(y - x)); } if (whiteSteps <= blackSteps){ System.out.println("White"); } else { System.out.println("Black"); } } }
constant
1075_A. The King's Race
CODEFORCES
//package com.krakn.CF.D1159; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n, k; n = sc.nextInt(); k = sc.nextInt(); int a = (n - k) / 2; StringBuilder s = new StringBuilder(); int i; while (s.length() < n) { i = 0; while (i < a && s.length() < n) { s.append("0"); i++; } if (s.length() < n) s.append("1"); } System.out.println(s); } }
linear
1159_D. The minimal unique substring
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicReferenceArray; public class NastyaWardrobe { static long modulo = 1000000007; static long ans = 0; public static void main(String[] args) throws IOException { BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); String[] s1 = inp.readLine().split(" "); long clothes = Long.parseLong(s1[0]); long months = Long.parseLong(s1[1]); //formula 2^k(2x-1)+1; calc(clothes,months); System.out.print(ans); } static void calc(long clothes,long months){ if(clothes!=0) { long a; long count = 0; ArrayList<Long> list = new ArrayList<>(); if (months >= 2) { a = 2; long c = months; while (c > 1) { if (c % 2 == 1) { count++; list.add(a); } c = c / 2; a = (a * a) % modulo; } while (count > 0) { long b = list.get(0); list.remove(0); a = (a * b) % modulo; count--; } } else { a = (long) Math.pow(2, months); } long b = clothes; //System.out.println(b); b = (2 * b - 1) % modulo; ans = (a * b) % modulo; ans = (ans + 1) % modulo; }else{ ans = 0; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.*; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n= sc.nextInt(); int x= (int)Math.sqrt(n) ; int a[] = new int[n+5]; for(int i=1,o=n,j;i<=n;i+=x) for(j=(int)Math.min(i+x-1,n);j>=i;a[j--]=o--); for(int i=1;i<=n;i++)System.out.print(a[i]+" "); System.out.println(); } }
linear
1017_C. The Phone Number
CODEFORCES
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static Reader scan; static PrintWriter pw; static int n,k,left[],right[],arr[]; static long MOD = 1000000007,count[],dp[]; public static void main(String[] args) { new Thread(null,null,"BaZ",1<<25) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { scan = new Reader(); pw = new PrintWriter(System.out,true); StringBuilder sb = new StringBuilder(); n = ni(); k = ni(); int stack[] = new int[1000001]; int top = -1; arr = new int[n]; left = new int[n]; right = new int[n]; for(int i=0;i<n;++i) { arr[i] = ni(); while(top>=0 && arr[stack[top]]<=arr[i]) top--; if(top==-1) left[i] = 0; else left[i] = stack[top]+1; stack[++top] = i; } top = -1; for(int i=n-1;i>=0;--i) { while(top>=0 && arr[stack[top]]<arr[i]) top--; if(top==-1) right[i] = n-1; else right[i] = stack[top]-1; stack[++top] = i; } //pa("left", left); //pa("right", right); dp = new long[n+1]; for(int i=0;i<=n;++i) { if(i<k) continue; dp[i] = dp[i-k+1] + (i-k+1); } count = new long[n]; long ans = 0; for(int i=0;i<n;++i) { int len = right[i]-left[i]+1; int lef = i-left[i]; int rig = right[i]-i; long count = dp[len] - dp[lef] - dp[rig]; if(count>=MOD) count%=MOD; ans += count*arr[i]; if(ans>=MOD) ans%=MOD; } pl(ans); pw.flush(); pw.close(); } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
linear
1037_F. Maximum Reduction
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); long dest = sc.nextLong(); long max = (long)N * ((long)N + 1L) / 2L; if (dest < 2 * N - 1 || dest > max) { out.println("No"); out.close(); return; } int[] d = new int[N + 1]; int[] f = new int[N + 1]; int K = 1; for (; K <= N; K++) { long dep = 1L, cnt = 1L, c = 1L; long t = 1L; while (cnt < N) { c = c * K; dep++; t += (dep * Math.min(c, N - cnt)); cnt += c; } if (t <= dest) break; } out.println("Yes"); int dep = 1; long cnt = 1L, c = 1L; long t = 1L; d[1] = 1; while (cnt < N) { dep++; c = c * K; long x = (long)N - cnt; int min; if (c >= x) min = (int)x; else min = (int)c; d[dep] = min; t += (dep * Math.min(c, (long)N - cnt)); cnt += c; } dest -= t; int curDep = dep; int nextDep = dep + 1; while (dest > 0) { if (d[curDep] <= 1) curDep--; d[curDep]--; long next = Math.min(nextDep++, dest + curDep); dest -= ((int)next - curDep); d[(int)next]++; } int first = 1; for (int i = 2; i < nextDep; i++) { int p = 0, fn = first - d[i - 1] + 1; for (int j = first + 1; j <= first + d[i]; j++) { if (p == K) { fn++; p = 0; } p++; f[j] = fn; } first += d[i]; } for (int i = 2; i <= N; i++) out.format("%d ", f[i]); out.close(); } static 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; }*/ } }
nlogn
1098_C. Construct a tree
CODEFORCES
import java.util.*; import java.io.*; import java.text.*; import java.math.*; import static java.lang.Integer.*; import static java.lang.Double.*; import java.lang.Math.*; public class two_squares { public static void main(String[] args) throws Exception { new two_squares().run(); } public void run() throws Exception { FastIO file = new FastIO(); double x1 = file.nextInt(); double y1 = file.nextInt(); double x2 = file.nextInt(); double y2 = file.nextInt(); double x3 = file.nextInt(); double y3 = file.nextInt(); double x4 = file.nextInt(); double y4 = file.nextInt(); double minx1, maxx1, miny1, maxy1; minx1 = Math.min(x1, Math.min(x2, Math.min(x3, x4))); maxx1 = Math.max(x1, Math.max(x2, Math.max(x3, x4))); miny1 = Math.min(y1, Math.min(y2, Math.min(y3, y4))); maxy1 = Math.max(y1, Math.max(y2, Math.max(y3, y4))); double x5 = file.nextInt(); double y5 = file.nextInt(); double x6 = file.nextInt(); double y6 = file.nextInt(); double x7 = file.nextInt(); double y7 = file.nextInt(); double x8 = file.nextInt(); double y8 = file.nextInt(); double minx2, maxx2, miny2, maxy2; minx2 = Math.min(x5, Math.min(x6, Math.min(x7, x8))); maxx2 = Math.max(x5, Math.max(x6, Math.max(x7, x8))); miny2 = Math.min(y5, Math.min(y6, Math.min(y7, y8))); maxy2 = Math.max(y5, Math.max(y6, Math.max(y7, y8))); Point _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16; _1 = new Point(x1, y1); _2 = new Point(x2, y2); _3 = new Point(x3, y3); _4 = new Point(x4, y4); _5 = new Point(x5, y5); _6 = new Point(x6, y6); _7 = new Point(x7, y7); _8 = new Point(x8, y8); _9 = new Point(minx1, maxy1); _10 = new Point(minx1, miny1); _11 = new Point(maxx1, maxy1); _12 = new Point(maxx1, miny1); double m1 = (minx2 + maxx2) / 2; double m2 = (miny2 + maxy2) / 2; _13 = new Point(minx2, m2); _14 = new Point(m1, miny2); _15 = new Point(maxx2, m2); _16 = new Point(m1, maxy2); Point[] a = {_1, _2, _3, _4}; Point[] b = {_5, _6, _7, _8}; boolean works = false; Line[] aa = {new Line(_9,_10), new Line(_10, _12), new Line(_12, _11), new Line(_11, _9)}; Line[] bb = {new Line(_13, _14), new Line(_14, _15), new Line(_15, _16), new Line(_16, _13)}; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (aa[i].intersection(bb[i]) != null) { works = true; } } } for (Point p : b) { if (p.x >= minx1 && p.x <= maxx1 && p.y >= miny1 && p.y <= maxy1) { works = true; } } for (Point p : a) { boolean result = false; for (int i = 0, j = b.length - 1; i < b.length; j = i++) { if ((b[i].y > p.y) != (b[j].y > p.y) && (p.x < (b[j].x - b[i].x) * (p.y - b[i].y) / (b[j].y-b[i].y) + b[i].x)) { result = !result; } } if (result) works = true; } System.out.println(works ? "YES" : "NO"); } public static class Point { double x, y; public Point(double a, double b) { x = a; y = b; } } public static class Line { Point a, b; public Line(Point x, Point y) { a = x; b = y; } public Point intersection(Line o) { double x1 = a.x; double y1 = a.y; double x2 = b.x; double y2 = b.y; double x3 = o.a.x; double y3 = o.a.y; double x4 = o.b.x; double y4 = o.b.y; double denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))/denom; double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))/denom; if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) { return new Point((int) (x1 + ua*(x2 - x1)), (int) (y1 + ua*(y2 - y1))); } return null; } } public static class FastIO { BufferedReader br; StringTokenizer st; public FastIO() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static long pow(long n, long p, long mod) { if (p == 0) return 1; if (p == 1) return n % mod; if (p % 2 == 0) { long temp = pow(n, p / 2, mod); return (temp * temp) % mod; } else { long temp = pow(n, p / 2, mod); temp = (temp * temp) % mod; return (temp * n) % mod; } } public static long pow(long n, long p) { if (p == 0) return 1; if (p == 1) return n; if (p % 2 == 0) { long temp = pow(n, p / 2); return (temp * temp); } else { long temp = pow(n, p / 2); temp = (temp * temp); return (temp * n); } } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } }
constant
994_C. Two Squares
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; public class java2 { public static void main(String[] args) { Scanner r = new Scanner(System.in); int n=r.nextInt(); int []l=new int[1005]; int []ri=new int[1005]; int []candy=new int[1005]; for(int i=1;i<=n;++i) { l[i]=r.nextInt(); } for(int i=1;i<=n;++i) { ri[i]=r.nextInt(); } for(int i=1;i<=n;++i) { if(l[i]>i-1||ri[i]>n-i) { System.out.println("NO"); System.exit(0); } candy[i]=n-l[i]-ri[i]; } for(int i=1;i<=n;++i) { int left=0,right=0; for(int j=1;j<=i-1;++j) { if(candy[j]>candy[i]) { ++left; } } for(int j=i+1;j<=n;++j) { if(candy[j]>candy[i]) { ++right; } } if(left!=l[i]||right!=ri[i]) { System.out.println("NO"); System.exit(0); } } System.out.println("YES"); for(int i=1;i<=n;++i) { System.out.print(candy[i]+" "); } } }
quadratic
1054_C. Candies Distribution
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import java.util.PriorityQueue; import static java.lang.Math.*; public class solution implements Runnable { 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); } } static int mod = (int)1e9+7; public static long fastexpo(long pow) { long expo = 2; long ans = 1; while(pow!=0) { if((pow&1)==1) { ans = (ans*expo)%mod; } expo = (expo*expo)%mod; pow = pow>>1; } return ans; } public static void main(String args[]) throws Exception { new Thread(null, new solution(),"Main",1<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); long x = sc.nextLong(); if(x==0) { out.println(0); out.close(); return; } long k = sc.nextLong(); long a = ((fastexpo(k+1)%mod)*(x%mod))%mod; long b = (-1*fastexpo(k)%mod+mod)%mod; long ans = (a+b+1)%mod; out.println(ans); out.close(); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.*; import java.io.*; public class C{ static PrintWriter out; static InputReader in; public static void main(String args[]){ out = new PrintWriter(System.out); in = new InputReader(); new C(); out.flush(); out.close(); } C(){ int w = solve(); out.print(w == 0 ? "sjfnb" : "cslnb"); } int n; long a[]; int solve(){ n = in.nextInt(); a = new long[n]; long sum = 0; for(int i = 0; i < n; i++)sum += a[i] = in.nextLong(); if(sum == 0){ return 1; } Arrays.sort(a); int c = 0, c0 = 0; long p = -1, max = 0; int f = 0; long t = -1; int pp = -1; for(int i = 0; i < n; i++){ if(a[i] == p){ c++; }else{ if(p == 0)c0 = c; if(c >= 2){f++; t = p; pp = i - 2;} max = Math.max(max, c); p = a[i]; c = 1; } } max = Math.max(max, c); sum = 0; if(c >= 2){f++; t = p; pp = n - 2;} if(max > 2 || c0 > 1 || f > 1)return 1; if(f == 1){ long v = Arrays.binarySearch(a, t - 1); if(v >= 0)return 1; a[pp]--; sum = 1; } p = -1; for(int i = 0; i < n; i++){ sum += a[i] - (p + 1); a[i] = p + 1; p = a[i]; } return 1 - (int)(sum % 2); } public static class InputReader{ BufferedReader br; StringTokenizer st; InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){} } return st.nextToken(); } } }
linear
1190_B. Tokitsukaze, CSL and Stone Game
CODEFORCES
//q4 import java.io.*; import java.util.*; import java.math.*; public class q4 { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); int query = in.nextInt(); while (query -- > 0) { int n = in.nextInt(); int k = in.nextInt(); char[] arr = new char[n]; //slot all n into char array String code = in.next(); for (int i = 0; i < n; i++) { arr[i] = code.charAt(i); } //R, G, B cycle int r = 0; int g = 0; int b = 0; for (int i = 0; i < k; i++) { if (i % 3 == 0) { if (arr[i] == 'R') {g++; b++;} else if (arr[i] == 'G') {r++; b++;} else {r++; g++;} //if is 'B' } else if (i % 3 == 1) { if (arr[i] == 'G') {g++; b++;} else if (arr[i] == 'B') {r++; b++;} else {r++; g++;} //if is 'R' } else { //if mod 3 is 2 if (arr[i] == 'B') {g++; b++;} else if (arr[i] == 'R') {r++; b++;} else {r++; g++;} //if is 'G' } } //starting from kth position, if different then add 1, and check (j-k)th position int rMin = r; int gMin = g; int bMin = b; for (int j = k; j < n; j++) { //R cycle if ((j % 3 == 0 && arr[j] != 'R') || (j % 3 == 1 && arr[j] != 'G') || (j % 3 == 2 && arr[j] != 'B')) { r++; } //R cycle if (((j - k) % 3 == 0 && arr[j - k] != 'R') || ((j - k) % 3 == 1 && arr[j - k] != 'G') || ((j - k) % 3 == 2 && arr[j - k] != 'B')) { r--; } rMin = Math.min(r, rMin); //G cycle if ((j % 3 == 0 && arr[j] != 'G') || (j % 3 == 1 && arr[j] != 'B') || (j % 3 == 2 && arr[j] != 'R')) { g++; } if (((j - k) % 3 == 0 && arr[j - k] != 'G') || ((j - k) % 3 == 1 && arr[j - k] != 'B') || ((j - k) % 3 == 2 && arr[j - k] != 'R')) { g--; } gMin = Math.min(gMin, g); //B cycle if ((j % 3 == 0 && arr[j] != 'B') || (j % 3 == 1 && arr[j] != 'R') || (j % 3 == 2 && arr[j] != 'G')) { b++; } if (((j - k) % 3 == 0 && arr[j - k] != 'B') || ((j - k) % 3 == 1 && arr[j - k] != 'R') || ((j - k) % 3 == 2 && arr[j - k] != 'G')) { b--; } bMin = Math.min(bMin, b); } out.println(Math.min(Math.min(rMin, gMin), bMin)); } out.flush(); } }
quadratic
1196_D2. RGB Substring (hard version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.TreeMap; import java.util.Map; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Ribhav */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CGlassCarving solver = new CGlassCarving(); solver.solve(1, in, out); out.close(); } static class CGlassCarving { public void solve(int testNumber, FastReader s, PrintWriter out) { TreeMap<Long, Integer> mapH = new TreeMap<>(); TreeMap<Long, Integer> mapV = new TreeMap<>(); TreeMap<Long, Integer> hDiff = new TreeMap<>(); TreeMap<Long, Integer> vDiff = new TreeMap<>(); long width = s.nextInt(); long height = s.nextInt(); mapH.put(0L, 1); mapV.put(0L, 1); mapV.put(width, 1); mapH.put(height, 1); vDiff.put(width, 1); hDiff.put(height, 1); long maxV = height; long maxH = width; int n = s.nextInt(); for (int i = 0; i < n; i++) { char ch = s.nextCharacter(); long cut = s.nextInt(); if (ch == 'H') { Long next = mapH.higherKey(cut); Long prev = mapH.lowerKey(cut); Long diff = next - prev; int freq = hDiff.get(diff); if (freq == 1) { hDiff.remove(diff); } else { hDiff.put(diff, freq - 1); } hDiff.put(next - cut, hDiff.getOrDefault(next - cut, 0) + 1); hDiff.put(cut - prev, hDiff.getOrDefault(cut - prev, 0) + 1); mapH.put(cut, mapH.getOrDefault(cut, 0) + 1); } else { Long next = mapV.higherKey(cut); Long prev = mapV.lowerKey(cut); Long diff = next - prev; int freq = vDiff.get(diff); if (freq == 1) { vDiff.remove(diff); } else { vDiff.put(diff, freq - 1); } vDiff.put(next - cut, vDiff.getOrDefault(next - cut, 0) + 1); vDiff.put(cut - prev, vDiff.getOrDefault(cut - prev, 0) + 1); mapV.put(cut, mapV.getOrDefault(cut, 0) + 1); } out.println(hDiff.lastKey() * vDiff.lastKey()); } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(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 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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
nlogn
527_C. Glass Carving
CODEFORCES
import java.io.*; public class First { StreamTokenizer in; PrintWriter out; int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } String nextString() throws IOException { in.nextToken(); return in.sval; } void run() throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); solve(); out.flush(); } void solve() throws IOException { int n = nextInt(), k = nextInt(), sum = 0, count = 0; String str = nextString(); char[] arr = str.toCharArray(); boolean[] bool = new boolean[26]; for(char ch: arr){ bool[((int)ch)-97] = true; } for(int i = 0; i < 26; i++){ if(bool[i]){ sum += i+1; count++; i += 1; } if(count == k) break; } if(count == k) out.println(sum); else out.println(-1); } public static void main(String[] args) throws IOException { new First().run(); } }
linear
1011_A. Stages
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.System.out; public class Main { private FastScanner scanner = new FastScanner(); public static void main(String[] args) { new Main().solve(); } private List<Integer>[] gr = new ArrayList[1000_000+5]; private int dp[][] = new int[21][1000_000+5]; private boolean used[] = new boolean[1000_000+5]; void init(int v, int p) { Stack<Integer> st = new Stack<>(); st.push(v); st.push(p); while (!st.isEmpty()) { p = st.pop(); v = st.pop(); used[v] = true; dp[0][v] = p; for (int i = 1; i <= 20; i++) { if (dp[i - 1][v] != -1) { dp[i][v] = dp[i - 1][dp[i - 1][v]]; } } for (int next : gr[v]) { if (!used[next]) { st.push(next); st.push(v); } } } } private void solve() { int n = scanner.nextInt(), k = scanner.nextInt(); boolean[] ans = new boolean[1000_000 + 5]; for (int i = 0; i < n; i++) { gr[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i ++) { int u = scanner.nextInt() - 1, v = scanner.nextInt() - 1; gr[u].add(v); gr[v].add(u); } k = n - k - 1; ans[n - 1] = true; init(n - 1 , n - 1); int t, d, next; for (int i = n - 2; i >= 0; i--) { t = i; d = 1; if (ans[i]) { continue; } for (int j = 20; j >= 0; j--){ next = dp[j][t]; if (next != -1 && !ans[next]) { t = next; d += 1 << j; } } if (d <= k) { k -=d; t = i; while (!ans[t]) { ans[t] = true; t = dp[0][t]; } } if (k == 0) { break; } } StringBuilder sb = new StringBuilder(""); for (int i = 0; i < n; i++) { if (!ans[i]) { sb.append(i + 1).append(" "); } } System.out.println(sb.toString()); } class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 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()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } }
nlogn
980_E. The Number Games
CODEFORCES
import java.util.*; public class Main{ private static final int MAX_SIZE = 100005; public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); if(((m + 1) / 60 < a) || ((m + 1) / 60 == a && (m + 1) % 60 <= b)) { out(0, 0); System.exit(0); } for(int i = 2; i <= n; i++) { int x = sc.nextInt(); int y = sc.nextInt(); int bb = b + 2 * m + 2; int aa = a + bb / 60; bb %= 60; if((aa < x) || (aa == x && bb <= y)) { b = b + m + 1; a = a + b / 60; b %= 60; out(a, b); System.exit(0); } a = x; b = y; } b = b + m + 1; a = a + b / 60; b = b % 60; out(a, b); } private static void out(int a, int b) { cout(a); cout(" "); cout(b); } private static void cout(Object a) { System.out.print(a); } }
linear
967_A. Mind the Gap
CODEFORCES
import java.util.Scanner; public class Solution { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); String s = sc.next(); StringBuilder ans = new StringBuilder(); int count = 0; int open = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { ans.append("("); count++; open++; } else { ans.append(")"); open--; } if (count == k / 2) { break; } } while (open > 0) { ans.append(")"); open--; } System.out.println(ans.toString()); } }
linear
1023_C. Bracket Subsequence
CODEFORCES
import java.io.*; import java.util.StringTokenizer; import static java.lang.Math.max; import static java.lang.Math.min; public class Main { FastScanner in; PrintWriter out; void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new Main().run(); } void solve() { int t = in.nextInt(); for (int sdfsdf = 0; sdfsdf < t; sdfsdf++) { long n = in.nextLong(); long k = in.nextLong(); if (n == 1) { if (k == 1) { out.println("YES 0"); } else { out.println("NO"); } continue; } if (k == 3) { if (n == 2) { out.println("NO"); } else { out.println("YES " + (n - 1)); } continue; } long cuts = 1; long squares = 4; int zoom = 1; while (k > cuts + squares) { cuts += squares; squares *= 4; zoom++; } if (zoom > n) { out.println("NO"); continue; } if (zoom == n && k > cuts) { out.println("NO"); continue; } long current_cuts = k - cuts; if (current_cuts > squares - (2L * Math.sqrt(squares) - 1L)) { out.println("YES " + (n - zoom - 1L)); } else { out.println("YES " + (n - zoom)); } } } }
logn
1080_D. Olya and magical square
CODEFORCES
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package newpackage; import java.util.*; /** * * @author parpaorsa */ public class NewClass { static Scanner in=new Scanner(System.in); public static void main(String[] args) { int n = in.nextInt(),ans=Integer.MAX_VALUE,t=0; String x = in.next(); for (int i = 0; i < n; i++) { if(x.charAt(i)=='-')t--; else t++; ans=Math.min(ans,t); } if(ans <= 0) System.out.println(Math.abs(ans)+t); else System.out.println(t); } }
linear
1159_A. A pile of stones
CODEFORCES
import java.util.*; import java.io.*; import java.math.BigInteger; public class Problem { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static int[] rt; static int[] size; static void initialize(int n){ rt = new int[n + 1]; size = new int[n + 1]; for(int i = 0; i < rt.length; i++){ rt[i] = i; size[i] = 1; } } static int root(int x){ while(rt[x] != x){ rt[x] = rt[rt[x]]; x = rt[x]; } return x; } static long union(int x,int y){ int root_x = root(x); int root_y = root(y); if(root_x == root_y) return 0; long val = size[root_x] *1l* size[root_y]; if(size[root_x]<size[root_y]){ rt[root_x] = rt[root_y]; size[root_y] += size[root_x]; } else{ rt[root_y] = rt[root_x]; size[root_x] += size[root_y]; } return val; } static void solve() { in = new InputReader(System.in); out = new PrintWriter(System.out); int t = 1; while(t-- > 0){ int n = in.nextInt(); int[] arr = in.nextIntArray(n); ArrayList<Pair> list = new ArrayList<>(); for(int i = 1; i < n; i++){ int u = in.nextInt() - 1; int v = in.nextInt() - 1; list.add(new Pair(u, v, Math.max(arr[u],arr[v]))); } list.sort((p1,p2) -> Integer.compare(p1.i, p2.i)); initialize(n); long s1 = 0; for(int i = 0; i < list.size(); i++){ s1 += union(list.get(i).x, list.get(i).y) * list.get(i).i; } for(int i = 0; i < list.size(); i++){ Pair p = list.get(i); p.i = Math.min(arr[p.x],arr[p.y]); } list.sort((p1,p2) -> -Integer.compare(p1.i, p2.i)); initialize(n); long s2 = 0; for(int i = 0; i < list.size(); i++){ s2 += union(list.get(i).x, list.get(i).y) * list.get(i).i; } out.println(s1 - s2); } out.close(); } public static void main(String[] args) { new Thread(null ,new Runnable(){ public void run(){ try{ solve(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } static class Pair implements Comparable<Pair> { int x,y; int i; Pair (int x,int y) { this.x = x; this.y = y; } Pair (int x,int y, int i) { this.x = x; this.y = y; this.i = i; } public int compareTo(Pair o) { if(this.x != o.x) return -Integer.compare(this.x, o.y); return -Integer.compare(this.y,o.y); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y==y; } return false; } @Override public String toString() { return x + " "+ y + " "+i; } /*public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); }*/ } static long add(long a,long b){ long x=(a+b); while(x>=mod) x-=mod; return x; } static long sub(long a,long b){ long x=(a-b); while(x<0) x+=mod; return x; } static long mul(long a,long b){ long x=(a*b); while(x>=mod) x-=mod; return x; } static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static long gcd(long x,long y) { if(y==0) return x; else return gcd(y,x%y); } static int gcd(int x,int y) { if(y==0) return x; else return gcd(y,x%y); } static long pow(long n,long p,long m) { long result = 1; if(p==0){ return n; } while(p!=0) { if(p%2==1) result *= n; if(result >= m) result %= m; p >>=1; n*=n; if(n >= m) n%=m; } return result; } static long pow(long n,long p) { long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } 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; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(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; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
nlogn
915_F. Imbalance Value of a Tree
CODEFORCES
import java.util.*; public class TestClass { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int arr[] = new int[n+1]; for(int i =0;i<n;i++) arr[i+1]= in.nextInt(); long sum[] = new long [n+1]; for(int i=1;i<=n;i++) sum[i]=sum[i-1]+arr[i]; long dp[] = new long[n+1]; for(int i =1;i<=n;i++) { for(int j=i;j>i-m&&j>=1;j--) { long val = sum[i]-sum[j-1]+dp[j-1]-k; dp[i]= Math.max(dp[i],val); } } long max =0; for(int i =1;i<=n;i++) max=Math.max(max,dp[i]); System.out.println(max); } }
quadratic
1197_D. Yet Another Subarray Problem
CODEFORCES
import java.util.*; public class test{ public static void main(String args[]) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int m=s.nextInt(); int arr[]=new int[n]; int max = Integer.MIN_VALUE; long sum = 0; for(int i=0;i<n;i++) { arr[i] = s.nextInt(); sum = sum + arr[i]; max = Math.max(max,arr[i]); } Arrays.sort(arr); int i = 0; int count = 0; int d = 0; for(i=0; i<n; i++) { if(arr[i] > d) { count++; d++; } else if(arr[i] == d && arr[i] > 0) { count++; } } //System.out.println(count + " " + max); if(max - d > 0) { count = count + max - d; } System.out.println(sum - count);}}
nlogn
1061_B. Views Matter
CODEFORCES
import java.io.*; import java.util.*; public class tr { static int[][] ad; static boolean []vis; static int []goods; static int[][]sol; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(); int []a=new int [n]; int max=0; for(int i=0;i<n;i++) a[i]=sc.nextInt(); Stack<Integer> s=new Stack<>(); boolean f=true; for(int i=0;i<n;i++) { max=Math.max(max,a[i]); if(!s.isEmpty() && a[i]>s.peek()) f=false; s.push(a[i]); while(!s.isEmpty()) { int high=s.pop(); if(s.isEmpty() || s.peek()!=high) { s.push(high); break; } s.pop(); } // System.out.println(s+" "+max); } //System.out.println(f+" "+max); if(f && s.size()==0) out.println("YES"); else if(f && s.size()==1 && s.peek()==max) out.println("YES"); else out.println("NO"); out.flush(); } static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } static class pair implements Comparable<pair> { int a; int b; pair(int a, int b) { this.a = a; this.b = b; } public String toString() { return a + " " + b; } @Override public int compareTo(pair o) { return o.a-a ; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
linear
1092_D1. Great Vova Wall (Version 1)
CODEFORCES
import java.util.Scanner; public class MargariteBestPresent_1080B { private static int f(int x) { return (x%2==0)?x/2:(x-1)/2-x; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n,r,l; n = sc.nextInt(); while(n-->0) { l = sc.nextInt(); r = sc.nextInt(); System.out.println(f(r)-f(l-1)); } sc.close(); } }
constant
1080_B. Margarite and the best present
CODEFORCES
import java.util.*; public class helloWorld { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int l = 1000, r = 0, u = 1000, b = 0; for(int i = 0; i < n; i++ ) { String str = in.next(); for(int j = 0; j < m; j++) if(str.charAt(j) == 'B') { l = Math.min(j+1, l); r = Math.max(j+1, r); u = Math.min(i+1, u); b = Math.max(i+1, b); } } System.out.println((u+b)/2 + " " + (l+r)/2); in.close(); } }
quadratic
1028_A. Find Square
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author pandusonu */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { // out.print("Case #" + testNumber + ": "); int n = in.readInt(); int[] a = in.readIntArray(n); int[][] sol = new int[n][n]; for (int i = 0; i < n; i++) { sol[0][i] = a[i]; } for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { sol[i][j] = sol[i - 1][j] ^ sol[i - 1][j + 1]; } } for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { sol[i][j] = Math.max(sol[i][j], Math.max(sol[i - 1][j], sol[i - 1][j + 1])); } } int q = in.readInt(); for (int i = 0; i < q; i++) { int l = in.readInt() - 1; int r = in.readInt() - 1; out.println(sol[r - l][l]); } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { try { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) return -1; } } catch (IOException e) { throw new RuntimeException(e); } return buf[curChar++]; } public int readInt() { return (int) readLong(); } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); if (c == -1) throw new RuntimeException(); } boolean negative = false; if (c == '-') { negative = true; 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 negative ? (-res) : (res); } public int[] readIntArray(int size) { int[] arr = new int[size]; for (int i = 0; i < size; i++) arr[i] = readInt(); return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
983_B. XOR-pyramid
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class EhabAndAComponentChoosingProblem { long INF = (long) 1e18; int n; int[] a; int[][] G; void solve() { n = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); int[] fr = new int[n - 1], to = new int[n - 1]; for (int i = 0; i < n - 1; i++) { fr[i] = in.nextInt() - 1; to[i] = in.nextInt() - 1; } G = build_graph(n, fr, to); int[][] ret = bfs(G, 0); int[] par = ret[0], ord = ret[2]; long best = -INF; long[] dp = new long[n]; for (int i = n - 1; i >= 0; i--) { int u = ord[i]; dp[u] = a[u]; for (int v : G[u]) { if (v != par[u]) { if (dp[v] > 0) dp[u] += dp[v]; } } best = Math.max(best, dp[u]); } int k = 0; for (int i = n - 1; i >= 0; i--) { int u = ord[i]; dp[u] = a[u]; for (int v : G[u]) { if (v != par[u]) { if (dp[v] > 0) dp[u] += dp[v]; } } if (dp[u] == best) { dp[u] = -INF; k++; } } out.printf("%d %d%n", best * k, k); } int[][] bfs(int[][] G, int root) { int n = G.length; int[] par = new int[n]; Arrays.fill(par, -1); int[] dep = new int[n]; dep[root] = 0; int[] qu = new int[n]; qu[0] = root; for (int l = 0, r = 1; l < r; l++) { int u = qu[l]; for (int v : G[u]) { if (v != par[u]) { qu[r++] = v; par[v] = u; dep[v] = dep[u] + 1; } } } return new int[][]{par, dep, qu}; } int[][] build_graph(int n, int[] from, int[] to) { int[][] G = new int[n][]; int[] cnt = new int[n]; for (int i = 0; i < from.length; i++) { cnt[from[i]]++; cnt[to[i]]++; } for (int i = 0; i < n; i++) G[i] = new int[cnt[i]]; for (int i = 0; i < from.length; i++) { G[from[i]][--cnt[from[i]]] = to[i]; G[to[i]][--cnt[to[i]]] = from[i]; } return G; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new EhabAndAComponentChoosingProblem().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
linear
1088_E. Ehab and a component choosing problem
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class BOOL { static char [][]ch; static int n,m; private static FastReader in =new FastReader(); public static void main(String[] args) { int n=in.nextInt(); int a[]=new int[1000002]; int dp[]=new int[1000002],ans=0; for(int i=0;i<n;i++){a[in.nextInt()]=in.nextInt();} dp[0]=a[0]==0?0:1; for(int i=1;i<1000002;i++){ if(a[i]==0){dp[i]=dp[i-1];} else{ if(a[i]>=i){dp[i]=1;} else{ dp[i]=dp[i-a[i]-1]+1; }} if(dp[i]>=ans)ans=dp[i]; } System.out.println(n-ans); }} class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
linear
608_C. Chain Reaction
CODEFORCES
import java.util.*; import java.lang.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.*; public class Main { public static void main(String[] args) throws Exception{ FastReader sc=new FastReader(); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); int n=sc.nextInt(); int[] font=new int[n]; int[] cost=new int[n]; for(int i=0;i<n;i++) { font[i]=sc.nextInt(); } for(int i=0;i<n;i++) { cost[i]=sc.nextInt(); } int[] dou= new int[n]; for(int i=0;i<n;i++) { int min=Integer.MAX_VALUE; for(int j=0;j<i;j++) { if(font[j]<font[i]) { if(min>cost[i]+cost[j]) { min=cost[i]+cost[j]; } } } dou[i]=min; } int ans=Integer.MAX_VALUE; for(int i=0;i<n;i++) { int min=Integer.MAX_VALUE; for(int j=0;j<i;j++) { if(dou[j]!=Integer.MAX_VALUE && font[j]<font[i]) { if(min>dou[j]+cost[i]) { min=dou[j]+cost[i]; } } } if(min<ans) { ans=min; } } if(ans==Integer.MAX_VALUE) { System.out.println(-1); } else { System.out.println(ans); } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
quadratic
987_C. Three displays
CODEFORCES
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner in=new Scanner(System.in); long x=in.nextLong(); long k=in.nextLong(); long mod=1000000007; long get=power(2,k,mod); long ans=((get%mod)*((2*x)%mod))%mod-get+1; if(ans<0) ans+=mod; if(x==0) ans=0; System.out.println(ans); } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if((y & 1)==1) res = (res * x) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x * x) % p; } return res; } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.Scanner; public class New_Year_and_Curling { static final double E = 0.00001; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int r = sc.nextInt(); double[] y = new double[n]; int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] =sc.nextInt(); double top = r; // if we make it 0 and subtract from the result will get WA (do not know why!!!) int x = arr[i]; for(int j =0 ;j<i;j++) { if(Math.abs(arr[j] -x )<=2*r) { top = Math.max(top , y[j] + Math.sqrt((4 * r * r) - ((arr[j] - x) * (arr[j] - x)))); } } y[i] = top ; double res = y[i] ; System.out.print(res+" "); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.StringTokenizer; public class ChainReaction implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); private class Beacon implements Comparable<Beacon> { private int position, range, score; private Beacon(int position, int range) { this.position = position; this.range = range; } public void setScore(int score) { this.score = score; } @Override public int compareTo(Beacon o) { return Integer.compare(this.position, o.position); } } public void solve() { int n = in.ni(); if (n == 1) { out.println(0); return; } beacons = new ArrayList<>(); for (int i = 0; i < n; i++) { beacons.add(new Beacon(in.ni(), in.ni())); } beacons.sort(Comparator.naturalOrder()); for (int i = 1; i < n; i++) { int left = 0, right = i - 1, position = beacons.get(i).position, range = beacons.get(i).range; int leftmost = i; while (left <= right) { int mid = left + (right - left) / 2; if (position - range <= beacons.get(mid).position) { leftmost = Math.min(leftmost, mid); right = mid - 1; } else { left = mid + 1; } } beacons.get(i).setScore(i - leftmost); } dp = new Integer[n]; int ans = Integer.MAX_VALUE; for (int i = n - 1; i >= 0; i--) { ans = Math.min(n - 1 - i + recurse(i), ans); } out.println(ans); } private List<Beacon> beacons; private Integer[] dp; private int recurse(int idx) { if (idx <= 0) return 0; if (dp[idx] != null) return dp[idx]; int destroyed = beacons.get(idx).score; int ans = destroyed + recurse(idx - destroyed - 1); return dp[idx] = ans; } @Override public void close() throws IOException { in.close(); out.close(); } 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 ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (ChainReaction instance = new ChainReaction()) { instance.solve(); } } }
nlogn
608_C. Chain Reaction
CODEFORCES
import java.util.Scanner; import java.util.Vector; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int a[] = new int[n]; int b[] = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); for (int i = 0; i < n; i++) b[i] = sc.nextInt(); int c[] = new int[2 * n]; c[0] = a[0]; for (int i = 1; i < n; i++) { c[i * 2] = a[i]; c[i * 2 - 1] = b[i]; if (a[i] == 1 || b[i] == 1) { System.out.print(-1); System.exit(0); } } c[2 * n - 1] = b[0]; if (a[0] == 1 || b[0] == 1) { System.out.print(-1); System.exit(0); } System.out.println(bin_search(c, m)); } private static double bin_search(int[] c, int m) { double start = 0; double end = Integer.MAX_VALUE; double mid; while (start + 0.0000001 < end) { mid = (start + end) / 2; if (test(mid, m, c)) end = mid; else start = mid; } return end; } private static boolean test(double fuel, int m, int[] c) { for (int i = 0; i < c.length; i++) { fuel -= (m + fuel) / c[i]; if (fuel < 0) { return false; } } return true; } }
nlogn
1010_A. Fly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main (String[] args) { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { String parameterStringList[] = reader.readLine().split(" "); int x = Integer.parseInt(parameterStringList[0]); int y = Integer.parseInt(parameterStringList[1]); int z = Integer.parseInt(parameterStringList[2]); int t1 = Integer.parseInt(parameterStringList[3]); int t2 = Integer.parseInt(parameterStringList[4]); int t3 = Integer.parseInt(parameterStringList[5]); int T1 = Math.abs(x-y) * t1; int T2 = Math.abs(x-z) * t2 + 3*t3 + Math.abs(x-y) * t2; if(T2 <= T1) System.out.println("YES"); else System.out.println("NO"); } catch (IOException e) { e.printStackTrace(); } } }
constant
1054_A. Elevator or Stairs?
CODEFORCES
import java.util.Scanner; public class GenerateLogin { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String a = scan.next(); String b = scan.next(); char last = b.charAt(0); String ans = ""+a.charAt(0); for(int i = 1;i<a.length();i++){ if(a.charAt(i)>=last)break; ans+=a.charAt(i); } ans+=last; System.out.println(ans); } }
linear
909_A. Generate Login
CODEFORCES
import java.io.*; import java.util.StringTokenizer; /** * CodeForces Round 5D. Follow Traffic Rules * Created by Darren on 14-9-14. */ public class Main { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { new Main().run(); } int a, v; int l, d, w; void run() throws IOException { a = in.nextInt(); v = in.nextInt(); l = in.nextInt(); d = in.nextInt(); w = in.nextInt(); double totalTime = 0.0; if (v >= w) { if (w*w >= 2*a*d) { double x = Math.sqrt(2*a*d); totalTime = x / a; if ((v*v-x*x) >= 2*a*(l-d)) totalTime += (-2*x+Math.sqrt(4*x*x+8*a*(l-d))) / (2*a); else totalTime += (v-x)/(1.0*a) + (l-d-(v*v-x*x)/(2.0*a))/v; } else { // totalTime = (-2*w+Math.sqrt(4*w*w+8*a*(l-d))) / (2*a); if (2*v*v-w*w <= 2*a*d) { totalTime = v / (1.0*a) + (v-w) / (1.0*a) + (d-(2*v*v-w*w)/(2.0*a)) / v; } else { double x = Math.sqrt((2*a*d+w*w)/2.0); totalTime = x / a + (x-w) / a; } if ((v*v-w*w) >= 2*a*(l-d)) totalTime += (-2*w+Math.sqrt(4*w*w+8*a*(l-d))) / (2*a); else totalTime += (v-w)/(1.0*a) + (l-d-(v*v-w*w)/(2.0*a))/v; } } else { if (v*v >= 2*a*l) totalTime = Math.sqrt(l*2.0/a); else totalTime = v / (1.0*a) + (l-v*v/(2.0*a)) / v; } out.printf("%.10f", totalTime); out.flush(); } void solve() throws IOException { } static class Reader { BufferedReader reader; StringTokenizer tokenizer; public Reader(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** get next word */ String nextToken() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } String readLine() throws IOException { return reader.readLine(); } char nextChar() throws IOException { return (char)reader.read(); } int nextInt() throws IOException { return Integer.parseInt( nextToken() ); } long nextLong() throws IOException { return Long.parseLong( nextToken() ); } double nextDouble() throws IOException { return Double.parseDouble( nextToken() ); } } }
constant
5_D. Follow Traffic Rules
CODEFORCES
/* * Created on 17.05.2019 */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Wolfgang Weck */ public class C01Easy { public static void main(String[] args) { try (BufferedReader r = new BufferedReader(new InputStreamReader(System.in))) { final String[] line = r.readLine().split(" "); final int N = Integer.parseInt(line[0]), P = Integer.parseInt(line[1]); final String[] numS = r.readLine().split(" "); if (numS.length != N) throw new IllegalArgumentException(); final int[] n = new int[N]; int sum1 = 0, sum2 = 0; for (int i = 0; i < N; i++) { n[i] = Integer.parseInt(numS[i]) % P; sum2 += n[i]; if (sum2 >= P) sum2 -= P; } int max = sum2; for (int i = 0; i < N; i++) { sum1 += n[i]; if (sum1 >= P) sum1 -= P; sum2 -= n[i]; if (sum2 < 0) sum2 += P; final int s = sum1 + sum2; if (s > max) max = s; } System.out.println(max); } catch (IOException e) { e.printStackTrace(); } } }
linear
958_C1. Encryption (easy)
CODEFORCES
import java.util.*; public class A { public static void main(String args[]) { Scanner sc=new Scanner(System.in); long n=sc.nextLong(); if(n==0) System.out.println(0); else if(n%2==1) System.out.println((n+1)/2); else System.out.println(n+1); } }
constant
979_A. Pizza, Pizza, Pizza!!!
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.System.in; public class Main { public static void main(String[] args)throws IOException{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] point = new int[n][]; for(int i=0;i<n;i++) point[i] = new int[]{sc.nextInt(),sc.nextInt()}; Arrays.sort(point,(a,b)->((a[0]-a[1])-(b[0]-b[1]))); TreeMap<Integer,Integer> tm = new TreeMap<>(); int ans = 0; for(int i=n-1;i>=0;i--){ int x = point[i][0], w = point[i][1]; Map.Entry<Integer,Integer> cur = tm.ceilingEntry(x+w); int curRes; if(cur==null) curRes = 1; else curRes = cur.getValue()+1; ans = Math.max(ans,curRes); Map.Entry<Integer,Integer> upper = tm.ceilingEntry(x-w); if(upper==null||upper.getValue()<curRes) tm.put(x-w,curRes); //Integer key = tm. } System.out.println(ans); } }
nlogn
528_B. Clique Problem
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class bhaa { InputStream is; PrintWriter o; /////////////////// CODED++ BY++ ++ ++ ++ BHAVYA++ ARORA++ ++ ++ ++ FROM++ JAYPEE++ INSTITUTE++ OF++ INFORMATION++ TECHNOLOGY++ //////////////// ///////////////////////// Make it work, make it right, make it fast. Make it work, make it right, make it fast. Make it work, make it right, make it fast. Make it work, make it right, make it fast. ///////////////// boolean chpr(int n) { if(n==1) { return true; }if(n==2) { return true; } if(n==3) { return true; } if(n%2==0) { return false; } if(n%3==0) { return false; } int w=2; int i=5; while(i*i<=n) { if(n%i==0) { return false; } i+=w; w=6-w; } return true; } void solve() { int n=ni(); int k=ni(); int rr=2*n; int gr=5*n; int br=8*n; o.println((long)(Math.ceil(rr*1.0/k)+Math.ceil(gr*1.0/k)+Math.ceil(br*1.0/k))); } //---------- I/O Template ---------- public static void main(String[] args) { new bhaa().run(); } void run() { is = System.in; o = new PrintWriter(System.out); solve(); o.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] nia(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } long[] nla(int n) { long a[] = new long[n]; for(int i = 0; i < n; i++) { a[i] = nl(); } return a; } int [][] nim(int n) { int mat[][]=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { mat[i][j]=ni(); } } return mat; } long [][] nlm(int n) { long mat[][]=new long[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { mat[i][j]=nl(); } } return mat; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } void piarr(int arr[]) { for(int i=0;i<arr.length;i++) { o.print(arr[i]+" "); } o.println(); } void plarr(long arr[]) { for(int i=0;i<arr.length;i++) { o.print(arr[i]+" "); } o.println(); } void pimat(int mat[][]) { for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { o.print(mat[i][j]); } o.println(); } } void plmat(long mat[][]) { for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { o.print(mat[i][j]); } o.println(); } } //////////////////////////////////// template finished ////////////////////////////////////// }
constant
1080_A. Petya and Origami
CODEFORCES
import java.util.*; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Comp c1 = getComp(scanner); Comp c2 = getComp(scanner); c1.sortByPrice(); c2.sortByPrice(); int i = 0; int j = 0; while(i < c1.num || j < c2.num) { Elem xi = (i < c1.num) ? c1.elems.get(i) : null; Elem yj = (j < c2.num) ? c2.elems.get(j) : null; if(xi != null && yj != null) { if(xi.price >= yj.price) { if(!c2.resultSet.contains(xi)) { c1.resultSet.add(xi); } i++; } else { if(!c1.resultSet.contains(yj)) { c2.resultSet.add(yj); } j++; } } else if(xi != null) { if(!c2.resultSet.contains(xi)) { c1.resultSet.add(xi); } i++; } else { if(!c1.resultSet.contains(yj)) { c2.resultSet.add(yj); } j++; } } long result = c1.getResultPrice() + c2.getResultPrice(); System.out.println(result); } private static Comp getComp(Scanner scanner) { Comp c = new Comp(); c.num = scanner.nextInt(); for(int i = 0; i < c.num; i++) { c.addElem(scanner.nextLong(), scanner.nextLong()); } return c; } } class Comp { int num; List<Elem> elems = new ArrayList<>(); Set<Elem> resultSet = new HashSet<>(); void addElem(long el, long pr) { Elem elem = new Elem(el, pr); elems.add(elem); } void sortByPrice() { Collections.sort(elems); } long getResultPrice() { long sumPrice = 0; for(Elem elem : resultSet) { sumPrice += elem.price; } return sumPrice; } } class Elem implements Comparable<Elem> { long elem; long price; public Elem(long el, long pr) { this.elem = el; this.price = pr; } public int compareTo(Elem other) { return (int) (other.price - price); } public boolean equals(Object o) { if(!(o instanceof Elem)) { return false; } Elem other = (Elem) o; return (other.elem == elem); } public int hashCode() { return (int) elem; } public String toString() { return "(" + elem + ", " + price + ")"; } }
nlogn
981_B. Businessmen Problems
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new PrintStream(System.out)); StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); long[] arrB = new long[n]; long[] arrG = new long[m]; st=new StringTokenizer(f.readLine()); for(int i=0;i<n;i++){ arrB[i]=Long.parseLong(st.nextToken()); } st=new StringTokenizer(f.readLine()); for(int j=0;j<m;j++){ arrG[j]=Long.parseLong(st.nextToken()); } Arrays.sort(arrB); Arrays.sort(arrG); long ans = 0; // for (int i = 0; i < n; i++) ans += arrB[i] * m; // for (int i = 0; i < m - 1; i++) ans += arrG[i] - arrB[0]; // if (arrB[m - 1] != arrB[0]) { // if (arrB.length == 1) { // ans=-1; // } // else ans += arrG[m - 1] - arrB[1]; // } // if (arrG[m-1] < arrB[0]) { // ans=-1; // } for(int i=0;i<n;i++){ ans+=arrB[i]*(long)m; } for(int i=1;i<m;i++){ ans+=arrG[i]-arrB[n-1]; } if(arrB[n-1]!=arrG[0]){ if(n==1){ ans=-1; } else{ //smallest g goes to second to last ans+=arrG[0]-arrB[n-2]; } } if(arrB[n-1]>arrG[0]){ ans=-1; } System.out.println(ans); f.close(); out.close(); } }
nlogn
1159_C. The Party and Sweets
CODEFORCES
import java.util.*; public class mad{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int cura = 0,curb = 0; int ver; System.out.println("? 0 0"); System.out.flush(); ver = sc.nextInt(); for(int i=29;i>=0;i--){ System.out.println("? "+(cura+(1<<i))+" "+curb); System.out.flush(); int temp1 = sc.nextInt(); System.out.println("? "+cura+" "+(curb+(1<<i))); System.out.flush(); int temp2 = sc.nextInt(); if(temp1!=temp2){ if(temp2==1){ cura += (1<<i); curb += (1<<i); } } else{ if(ver==1) cura += (1<<i); if(ver==-1) curb += (1<<i); ver = temp1; } } System.out.println("! "+cura+" "+curb); } }
logn
1088_D. Ehab and another another xor problem
CODEFORCES
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here long n,s,p; Scanner in=new Scanner(System.in); n=in.nextLong(); s=in.nextLong(); if(n==1 && s<=1) { System.out.print(n-1); } else if(s<n) { if(s%2!=0) {System.out.print(s/2);} else {System.out.print(s/2-1);} } else if(s==n) { if(s%2==0) {System.out.println((n/2)-1);} else {System.out.println(n/2);} } else if(s<=(2*n-1)) { System.out.print((2*n+1-s)/2); } else { System.out.print(0); } } }
constant
1023_B. Pair of Toys
CODEFORCES
/* * Created on 17.05.2019 */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Wolfgang Weck */ public class A01Easy { private static interface Matrix { boolean get(int i, int j); int size(); } private static class MData implements Matrix { private final boolean[][] m; MData(boolean[][] m) { this.m = m; } @Override public boolean get(int i, int j) { return m[i][j]; } @Override public int size() { return m.length; } } private static abstract class MDecorator implements Matrix { protected final Matrix inner; MDecorator(Matrix inner) { this.inner = inner; } @Override public int size() { return inner.size(); } } private static class MHFlip extends MDecorator { MHFlip(Matrix inner) { super(inner); } @Override public boolean get(int i, int j) { return inner.get(size() - 1 - i, j); } } private static class MVFlip extends MDecorator { MVFlip(Matrix inner) { super(inner); } @Override public boolean get(int i, int j) { return inner.get(i, size() - 1 - j); } } private static class MRot extends MDecorator { MRot(Matrix inner) { super(inner); } @Override public boolean get(int i, int j) { return inner.get(j, size() - 1 - i); } } public static void main(String[] args) { try (BufferedReader r = new BufferedReader(new InputStreamReader(System.in))) { final int N = Integer.parseInt(r.readLine()); Matrix m1 = readMatrix(r, N), m2 = readMatrix(r, N); boolean matched = matchesFlipped(m1, m2); int i = 0; while (i < 3 && !matched) { m1 = new MRot(m1); matched = matchesFlipped(m1, m2); i++; } System.out.println(matched ? "Yes" : "No"); } catch (IOException e) { e.printStackTrace(); } } private static Matrix readMatrix(BufferedReader r, int n) throws IOException { boolean[][] m = new boolean[n][n]; for (int i = 0; i < n; i++) { String line = r.readLine(); for (int j = 0; j < n; j++) { m[i][j] = line.charAt(j) == 'X'; } } return new MData(m); } private static boolean matches(Matrix m1, Matrix m2) { int i = 0, j = 0, n = m1.size(); while (i < n && m1.get(i, j) == m2.get(i, j)) { j++; if (j == n) { j = 0; i++; } } return i == n; } private static boolean matchesFlipped(Matrix m1, Matrix m2) { return matches(m1, m2) || matches(new MHFlip(m1), m2) || matches(new MVFlip(m1), m2); } }
quadratic
958_A1. Death Stars (easy)
CODEFORCES
//Author: Patel Rag //Java version "1.8.0_211" import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long modExp(long x, long n, long mod) //binary Modular exponentiation { long result = 1; while(n > 0) { if(n % 2 == 1) result = (result%mod * x%mod)%mod; x = (x%mod * x%mod)%mod; n=n/2; } return result; } static long gcd(long a, long b) { if(a==0) return b; return gcd(b%a,a); } public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); int n = fr.nextInt(); int q = fr.nextInt(); long[] a = new long[n]; long[] k = new long[q]; for(int i = 0; i < n; i++) a[i] = fr.nextLong(); for(int i = 0; i < q; i++) k[i] = fr.nextLong(); long[] pre = new long[n]; pre[0] = a[0]; for(int i = 1; i < n; i++) pre[i] = pre[i-1] + a[i]; long pd = 0; for(int i = 0; i < q; i++) { int l = 0; int r = n - 1; while(r > l) { int mid = (l + r) >> 1; if(pre[mid] - pd < k[i]) { l = mid + 1; } else if(pre[mid] - pd > k[i]) { r = mid - 1; } else { l = r = mid; } } int ans = 0; if(pre[l] - pd <= k[i]) { ans = n - l - 1; } else { ans = n - l; } if(ans == 0) ans = n; pd = pd + k[i]; if(pd >= pre[n-1]) pd = 0; System.out.println(ans); } } } class pair { public int first; public int second; public pair(int first,int second) { this.first = first; this.second = second; } public pair(pair p) { this.first = p.first; this.second = p.second; } public int first() { return first; } public int second() { return second; } public void setFirst(int first) { this.first = first; } public void setSecond(int second) { this.second = second; } } class myComp implements Comparator<pair> { public int compare(pair a,pair b) { if(a.first != b.first) return (a.first - b.first); return (b.second - a.second); } } class BIT //Binary Indexed Tree aka Fenwick Tree { public long[] m_array; public BIT(long[] dat) { m_array = new long[dat.length + 1]; Arrays.fill(m_array,0); for(int i = 0; i < dat.length; i++) { m_array[i + 1] = dat[i]; } for(int i = 1; i < m_array.length; i++) { int j = i + (i & -i); if(j < m_array.length) { m_array[j] = m_array[j] + m_array[i]; } } } public final long prefix_query(int i) { long result = 0; for(++i; i > 0; i = i - (i & -i)) { result = result + m_array[i]; } return result; } public final long range_query(int fro, int to) { if(fro == 0) { return prefix_query(to); } else { return (prefix_query(to) - prefix_query(fro - 1)); } } public void update(int i, long add) { for(++i; i < m_array.length; i = i + (i & -i)) { m_array[i] = m_array[i] + add; } } }
nlogn
975_C. Valhalla Siege
CODEFORCES
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.lang.reflect.Array; import java.math.*; import java.security.SecureRandom; public class WCS { public static class Vector implements Comparable <Vector> { long x, y; int position; Vector first, second; boolean toReverse; public Vector(long xx, long yy, int p) { x = xx; y = yy; position = p; first = null; second = null; toReverse = false; } public Vector negate() { Vector vv = new Vector(-x, -y, position); vv.first = first; vv.second = second; vv.toReverse = !toReverse; return vv; } public Vector add(Vector v) { Vector sum = new Vector(this.x + v.x, this.y + v.y, position); sum.first = this; sum.second = v; return sum; } public Vector subtract(Vector v) { return this.add(v.negate()); } public double euclideanNorm() { return Math.sqrt(x * x + y * y); } @Override public int compareTo(Vector v) { double thisa = Math.atan2(this.y, this.x); double va = Math.atan2(v.y, v.x); if(thisa < 0) thisa += 2 * Math.PI; if(va < 0) va += 2 * Math.PI; if(thisa < va) return -1; if(thisa > va) return 1; return Integer.compare(this.position, v.position); } @Override public String toString() { return x + " " + y; } } public static void dfs(Vector curr, int[] ans) { if(curr.first == null) { ans[curr.position] = curr.toReverse ? -1 : 1; return; } curr.first.toReverse ^= curr.toReverse; curr.second.toReverse ^= curr.toReverse; dfs(curr.first, ans); dfs(curr.second, ans); } public static boolean ok(Vector v1, Vector v2) { return v1.add(v2).euclideanNorm() <= Math.max(v1.euclideanNorm(), v2.euclideanNorm()); } public static void stop(long k) { long time = System.currentTimeMillis(); while(System.currentTimeMillis() - time < k); } public static void main(String[] args) throws IOException { int n = in.nextInt(); TreeSet <Vector> vectors = new TreeSet <> (); for(int i = 0; i < n; i ++) { Vector v = new Vector(in.nextLong(), in.nextLong(), i); vectors.add(v); } while(vectors.size() > 2) { //System.out.println(vectors); //stop(500); TreeSet <Vector> support = new TreeSet <> (); while(vectors.size() > 0) { Vector curr = vectors.pollFirst(); Vector next1 = vectors.higher(curr); Vector next2 = vectors.lower(curr.negate()); Vector next3 = vectors.higher(curr.negate()); Vector next4 = vectors.lower(curr); //System.out.println("CURR: " + curr + "\n" + next1 + "\n" + next2); if(next1 != null) { if(ok(curr, next1)) { support.add(curr.add(next1)); vectors.remove(next1); continue; } } if(next1 != null) { if(ok(curr, next1.negate())) { support.add(curr.subtract(next1)); vectors.remove(next1); continue; } } if(next2 != null) { if(ok(curr, next2)) { support.add(curr.add(next2)); vectors.remove(next2); continue; } } if(next2 != null) { if(ok(curr, next2.negate())) { support.add(curr.subtract(next2)); vectors.remove(next2); continue; } } if(next3 != null) { if(ok(curr, next3)) { support.add(curr.add(next3)); vectors.remove(next3); continue; } } if(next3 != null) { if(ok(curr, next3.negate())) { support.add(curr.subtract(next3)); vectors.remove(next3); continue; } } if(next4 != null) { if(ok(curr, next4)) { support.add(curr.add(next4)); vectors.remove(next4); continue; } } if(next4 != null) { if(ok(curr, next4.negate())) { support.add(curr.subtract(next4)); vectors.remove(next4); continue; } } support.add(curr); } vectors = support; } if(vectors.size() == 2) { Vector curr = vectors.pollFirst(); Vector next = vectors.pollFirst(); Vector add = curr.add(next); Vector sub = curr.subtract(next); if(sub.euclideanNorm() <= add.euclideanNorm()) vectors.add(sub); else vectors.add(add); } //System.out.println(vectors.first().euclideanNorm()); StringBuilder buffer = new StringBuilder(); int[] ans = new int[n]; dfs(vectors.pollFirst(), ans); for(int i = 0; i < n; i ++) buffer.append(ans[i] + " "); System.out.println(buffer); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } BigInteger nextBigInteger() { return new BigInteger(in.next()); } int nextInt() { return Integer.parseInt(next()); } char nextChar() { return in.next().charAt(0); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader in = new FastReader(); static OutputStream out = new BufferedOutputStream(System.out); public static byte[] toByte(Object o) { return String.valueOf(o).getBytes(); } public static void sop(Object o) { System.out.print(o); } }
nlogn
995_C. Leaving the Bar
CODEFORCES
import java.io.*; import java.util.*; public class A4 { public BufferedReader input; public PrintWriter output; public StringTokenizer stoken = new StringTokenizer(""); public static void main(String[] args) throws IOException { new A4(); } A4() throws IOException { input = new BufferedReader(new InputStreamReader(System.in)); output = new PrintWriter(System.out); run(); input.close(); output.close(); } private void run() throws IOException { int n = Math.toIntExact(nextLong()); int m = Math.toIntExact(nextLong()); int[] coor = new int[n + 1]; int[] ss = new int[n + 1]; for (int i = 0; i < n; i++) { coor[i] = Math.toIntExact(nextLong()); } coor[n] = 1000000000; Arrays.sort(coor); for (int i = 0; i < m; i++) { long x1 = nextLong(); long x2 = nextLong(); nextLong(); if (x1 == 1 && x2 >= coor[0]) { int l = 0; int r = n + 1; while (r - l > 1) { int mi = (r + l) / 2; if (coor[mi] > x2) { r = mi; } else { l = mi; } } ss[l]++; } } long[] ans = new long[n + 1]; ans[n] = ss[n] + n; long min = ans[n]; for (int i = n - 1; i > -1; i--) { ans[i] = ans[i + 1] - 1 + ss[i]; if (ans[i] < min) { min = ans[i]; } } System.out.println(min); } private Long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextString()); } private String nextString() throws IOException { while (!stoken.hasMoreTokens()) { String st = input.readLine(); stoken = new StringTokenizer(st); } return stoken.nextToken(); } }
nlogn
1075_C. The Tower is Going Home
CODEFORCES
import java.io.*; import java.util.*; public class Codechef{ static int max=Integer.MIN_VALUE; static int res=0; static int[] checkMax(int arr[],int j){ int sum=0; int x=arr[j]; while(x!=0){ if(j+1==15){ j=0; }else{ arr[j+1]=arr[j+1]+1; } // if(arr[j+1]%2==0){ // sum=sum+arr[j+1]; // if(sum>=max){ // max=sum; // } // } x--; j++; } return arr; } public static void main(String []args){ Scanner sc = new Scanner (System.in); long a [] = new long [14]; long b [] = new long [14]; long p,q,r,s,max = 0; for(int i = 0; i < 14; i++) a[i] = sc.nextInt(); for(int i = 0; i < 14; i++){ p = a[i]%14; q = a[i]/14; r = 0; s = 0; for(int j = 0; j < 14; j++) b[j] = a[j]; b[i] = 0; int j = (i+1)%14; for(; r < p; r++) { b[j]++; j=(j+1)%14; } for( j = 0; j < 14; j++) { b[j] += q; if(b[j] % 2 == 0) s+= b[j]; } max = Math.max(max,s); } System.out.println(max); } }
constant
975_B. Mancala
CODEFORCES
import javafx.util.Pair; import java.io.*; import java.util.*; public class Beacon8 { public static void main(String[] args) throws IOException { // int[] arr = {1, 3, 7, 18}; // int bIndex = Arrays.binarySearch(arr, 4); // System.out.println(bIndex); Scanner scan = new Scanner(System.in); int n = scan.nextInt(); Map<Integer, Integer> beacons = new TreeMap<>(); for (int i = 0; i < n; i++) { int index = scan.nextInt(); int power = scan.nextInt(); beacons.put(index, power); } int[] indicesArr = new int[n]; int arrInd = 0; for (int index : beacons.keySet()) { indicesArr[arrInd] = index; arrInd++; } // Integer[] indicesArr = ((Integer[])beacons.keySet().toArray()); int[] nDestroys = new int[n]; for (int i = 0; i < n; i++) { int bIndex = Arrays.binarySearch(indicesArr, indicesArr[i] - beacons.get(indicesArr[i])); if (bIndex < 0) bIndex = -(bIndex + 1); nDestroys[i] = i - bIndex; } int[] totalBeacons = new int[n]; int maxBeacons = 1; totalBeacons[0] = 1; for (int i = 1; i < n; i++) { if (nDestroys[i] == 0) totalBeacons[i] = totalBeacons[i - 1] + 1; else { if ((i - nDestroys[i] - 1) >= 0) totalBeacons[i] = totalBeacons[i - nDestroys[i] - 1] + 1; else totalBeacons[i] = 1; } // totalBeacons[i] = totalBeacons[i - nDestroys[i]] + 1; //totalBeacons[i] = i - nDestroys[i] + totalBeacons[i - nDestroys[i]] + 1; if(totalBeacons[i] > maxBeacons) maxBeacons = totalBeacons[i]; } // System.out.println("\ntotalBeacons array"); // for (int i = 0; i < n; i++) { // System.out.print(totalBeacons[i] + " "); // } // if (maxBeacons == -1) // System.out.println(n); System.out.println(n - maxBeacons); } }
nlogn
608_C. Chain Reaction
CODEFORCES
import java.io.*; import java.util.*; public class CF1082D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] aa = new int[n]; int[] i1 = new int[n]; int[] i2 = new int[n]; int n1 = 0, n2 = 0, m2 = 0; for (int i = 0; i < n; i++) { int a = Integer.parseInt(st.nextToken()); aa[i] = a; if (a == 1) i1[n1++] = i; else { i2[n2++] = i; m2 += a; } } if (m2 < (n2 - 1) * 2 + n1) { System.out.println("NO"); return; } int m = n2 - 1 + n1; int d = n2 - 1 + Math.min(n1, 2); PrintWriter pw = new PrintWriter(System.out); pw.println("YES " + d); pw.println(m); for (int i = 0; i + 1 < n2; i++) { pw.println((i2[i] + 1) + " " + (i2[i + 1] + 1)); aa[i2[i]]--; aa[i2[i + 1]]--; } if (n1 > 0) { while (n2 > 0 && aa[i2[n2 - 1]] == 0) n2--; pw.println((i2[n2 - 1] + 1) + " " + (i1[n1 - 1] + 1)); aa[i2[n2 - 1]]--; n1--; } for (int i = 0, j = 0; j < n1; j++) { while (aa[i2[i]] == 0) i++; pw.println((i2[i] + 1) + " " + (i1[j] + 1)); aa[i2[i]]--; } pw.close(); } }
linear
1082_D. Maximum Diameter Graph
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class Div1_526C { static int nV; static ArrayList<Integer>[] chldn; static int root; static int[][] anc; static int[] depth; static int[] num; static int[] nLoc; static int[][] tree; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); nV = Integer.parseInt(reader.readLine()); chldn = new ArrayList[nV]; for (int i = 0; i < nV; i++) { chldn[i] = new ArrayList<>(); } anc = new int[nV][21]; depth = new int[nV]; num = new int[nV]; nLoc = new int[nV]; tree = new int[nV * 4][2]; for (int[] a : tree) { a[0] = a[1] = -1; } root = 0; StringTokenizer inputData = new StringTokenizer(reader.readLine()); for (int i = 0; i < nV; i++) { num[i] = Integer.parseInt(inputData.nextToken()); nLoc[num[i]] = i; } inputData = new StringTokenizer(reader.readLine()); for (int i = 1; i < nV; i++) { anc[i][0] = Integer.parseInt(inputData.nextToken()) - 1; chldn[anc[i][0]].add(i); } preprocess(); build(1, 0, nV - 1); int nQ = Integer.parseInt(reader.readLine()); while (nQ-- > 0) { inputData = new StringTokenizer(reader.readLine()); if (inputData.nextToken().equals("1")) { int a = Integer.parseInt(inputData.nextToken()) - 1; int b = Integer.parseInt(inputData.nextToken()) - 1; int temp = num[a]; num[a] = num[b]; num[b] = temp; nLoc[num[a]] = a; nLoc[num[b]] = b; update(1, 0, nV - 1, num[a]); update(1, 0, nV - 1, num[b]); } else { printer.println(query(1, 0, nV - 1, nLoc[0], nLoc[0]) + 1); } } printer.close(); } static void build(int nI, int cL, int cR) { if (cL == cR) { tree[nI][0] = nLoc[cL]; tree[nI][1] = nLoc[cL]; } else { int mid = (cL + cR) >> 1; build(nI * 2, cL, mid); build(nI * 2 + 1, mid + 1, cR); if (tree[nI * 2][0] != -1 && tree[nI * 2 + 1][0] != -1) { merge(tree[nI * 2][0], tree[nI * 2][1], tree[nI * 2 + 1][0], tree[nI * 2 + 1][1]); tree[nI][0] = mResp[0]; tree[nI][1] = mResp[1]; } } } static int query(int nI, int cL, int cR, int e1, int e2) { if (cL == cR) { merge(e1, e2, nLoc[cL], nLoc[cL]); if (mResp[0] != -1) { return cL; } else { return cL - 1; } } int mid = (cL + cR) >> 1; merge(tree[nI * 2][0], tree[nI * 2][1], e1, e2); if (mResp[0] != -1) { return query(nI * 2 + 1, mid + 1, cR, mResp[0], mResp[1]); } return query(nI * 2, cL, mid, e1, e2); } static void update(int nI, int cL, int cR, int uI) { if (cL == cR) { tree[nI][0] = nLoc[cL]; tree[nI][1] = nLoc[cL]; } else { int mid = (cL + cR) >> 1; if (uI <= mid) { update(nI * 2, cL, mid, uI); } else { update(nI * 2 + 1, mid + 1, cR, uI); } merge(tree[nI * 2][0], tree[nI * 2][1], tree[nI * 2 + 1][0], tree[nI * 2 + 1][1]); tree[nI][0] = mResp[0]; tree[nI][1] = mResp[1]; } } static int[] mResp = new int[2]; static void merge1(int... a) { for (int i = 0; i < 3; i++) { if (a[i] == -1) { mResp[0] = mResp[1] = -1; return; } } if (onPath(a[0], a[1], a[2])) { mResp[0] = a[0]; mResp[1] = a[1]; return; } if (onPath(a[0], a[2], a[1])) { mResp[0] = a[0]; mResp[1] = a[2]; return; } if (onPath(a[1], a[2], a[0])) { mResp[0] = a[1]; mResp[1] = a[2]; return; } mResp[0] = mResp[1] = -1; } static void merge(int... a) { merge1(a[0], a[1], a[2]); merge1(mResp[0], mResp[1], a[3]); } static boolean onPath(int a, int b, int c) { if (a == c || b == c) { return true; } if (depth[a] > depth[c]) { a = jump(a, depth[a] - depth[c] - 1); } if (depth[b] > depth[c]) { b = jump(b, depth[b] - depth[c] - 1); } if (a == b) { return false; } if (anc[a][0] == c || anc[b][0] == c) { return true; } return false; } // good for depth of up to 1_048_576 = 2^20 static void preprocess() { anc[root][0] = root; fParent(root); for (int k = 1; k <= 20; k++) { for (int i = 0; i < nV; i++) { anc[i][k] = anc[anc[i][k - 1]][k - 1]; } } } static void fParent(int cV) { for (int aV : chldn[cV]) { anc[aV][0] = cV; depth[aV] = depth[cV] + 1; fParent(aV); } } static int fLCA(int a, int b) { if (depth[a] > depth[b]) { int temp = b; b = a; a = temp; } b = jump(b, depth[b] - depth[a]); if (a == b) { return a; } for (int i = 20; i >= 0; i--) { if (anc[a][i] != anc[b][i]) { a = anc[a][i]; b = anc[b][i]; } } return anc[a][0]; } static int jump(int cV, int d) { for (int i = 0; i <= 20; i++) { if ((d & (1 << i)) != 0) { cV = anc[cV][i]; } } return cV; } static Comparator<Integer> BY_DEPTH = new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return -Integer.compare(depth[o1], depth[o2]); // greatest depth first } }; }
nlogn
1084_F. Max Mex
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class round569d2b { public static void main(String args[]) { FastScanner in = new FastScanner(System.in); int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } if (n % 2 == 0) { for (int i = 0; i < n; i++) { if (arr[i] >= 0) { arr[i] = -1*arr[i]-1; } } } else { int max = Integer.MIN_VALUE; int maxIndex = 0; for (int i = 0; i < n; i++) { int elem = arr[i]; if (elem < 0) { elem = -1*elem-1; } if (elem > max) { max = elem; maxIndex = i; } } for (int i = 0; i < n; i++) { if (i == maxIndex) { if (arr[i] < 0) { arr[i] = -1*arr[i]-1; } } else { if (arr[i] >= 0) { arr[i] = -1*arr[i]-1; } } } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n ;i++) { sb.append(arr[i] + " "); } System.out.println(sb); } // ====================================================================================== // =============================== Reference Code ======================================= // ====================================================================================== static int greatestDivisor(int n) { int limit = (int) Math.sqrt(n); int max = 1; for (int i = 2; i <= limit; i++) { if (n % i == 0) { max = Integer.max(max, i); max = Integer.max(max, n / i); } } return max; } // Method to return all primes smaller than or equal to // n using Sieve of Eratosthenes static boolean[] sieveOfEratosthenes(int n) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; prime[0] = false; prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } return prime; } // Binary search for number greater than or equal to target // returns -1 if number not found private static int bin_gteq(int[] a, int key) { int low = 0; int high = a.length; int max_limit = high; while (low < high) { int mid = low + (high - low) / 2; if (a[mid] < key) { low = mid + 1; } else high = mid; } return high == max_limit ? -1 : high; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static class Tuple<X, Y> { public final X x; public final Y y; public Tuple(X x, Y y) { this.x = x; this.y = y; } public String toString() { return "(" + x + "," + y + ")"; } } static class Tuple3<X, Y, Z> { public final X x; public final Y y; public final Z z; public Tuple3(X x, Y y, Z z) { this.x = x; this.y = y; this.z = z; } public String toString() { return "(" + x + "," + y + "," + z + ")"; } } static Tuple3<Integer, Integer, Integer> gcdExtended(int a, int b, int x, int y) { // Base Case if (a == 0) { x = 0; y = 1; return new Tuple3(0, 1, b); } int x1 = 1, y1 = 1; // To store results of recursive call Tuple3<Integer, Integer, Integer> tuple = gcdExtended(b % a, a, x1, y1); int gcd = tuple.z; x1 = tuple.x; y1 = tuple.y; // Update x and y using results of recursive // call x = y1 - (b / a) * x1; y = x1; return new Tuple3(x, y, gcd); } // Returns modulo inverse of a // with respect to m using extended // Euclid Algorithm. Refer below post for details: // https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/ static int inv(int a, int m) { int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply extended Euclid Algorithm while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, process // same as euclid's algo m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1; } // k is size of num[] and rem[]. // Returns the smallest number // x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] are pairwise // coprime (gcd for every pair is 1) static int findMinX(int num[], int rem[], int k) { // Compute product of all numbers int prod = 1; for (int i = 0; i < k; i++) prod *= num[i]; // Initialize result int result = 0; // Apply above formula for (int i = 0; i < k; i++) { int pp = prod / num[i]; result += rem[i] * inv(pp, num[i]) * pp; } return result % prod; } /** * Source: Matt Fontaine */ static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int chars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (chars == -1) throw new InputMismatchException(); if (curChar >= chars) { curChar = 0; try { chars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (chars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { 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 String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
linear
1180_B. Nick and Array
CODEFORCES
/** * Author: Ridam Nagar * Date: 27 February 2019 * Time: 01:17:36 **/ /* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { static String reverse(String s){ String reverse=""; for(int i=s.length()-1;i>=0;i--){ reverse=reverse + s.charAt(i); } return reverse; } public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int x=m%(int)Math.pow(2,n); System.out.println(x); } }
constant
913_A. Modular Exponentiation
CODEFORCES
import org.omg.PortableServer.AdapterActivator; import java.io.*; import java.lang.reflect.Array; import java.net.CookieHandler; import java.util.*; import java.math.*; import java.lang.*; import java.util.concurrent.LinkedBlockingDeque; import static java.lang.Math.*; public class TaskA implements Runnable { long m = (int)1e9+7; PrintWriter w; InputReader c; public void run() { c = new InputReader(System.in); w = new PrintWriter(System.out); int n = c.nextInt(); int a[] = scanArrayI(n); int maxtime = Integer.MAX_VALUE,ind = -1; for(int i=0;i<n;i++){ int time = Integer.MAX_VALUE; if(a[i]<i+1) time = i; else{ time = (int)ceil((a[i] - i)/(double)n) * n + i; } if(time<maxtime){ maxtime = time; ind = i; } } w.println(ind+1); w.close(); } static 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){ for(int i=0;i<a.length;i++) w.print(a[i]+" "); 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 TaskA(),"TaskA",1<<26).start(); } }
nlogn
996_B. World Cup
CODEFORCES
import java.io.*; import java.util.*; public class Main { static Scanner in = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int n = in.nextInt(); int m = in.nextInt(); long boyMax = 0; int NBoyMax = 0; long sweets = 0; TreeSet<Long> boyMember = new TreeSet<>(); for (int i = 0; i < n; i++) { long input = in.nextLong(); boyMember.add(input); if (boyMax < input) { boyMax = input; NBoyMax = 1; } else if (boyMax == input) NBoyMax++; sweets += (input * m); } long smallestGirl = (long) 1e8 + 1; long sum = 0; for (int i = 0; i < m; i++) { long input = in.nextLong(); sum += input; if (smallestGirl > input) smallestGirl = input; } if (smallestGirl < boyMember.last()) { out.println(-1); } else if (smallestGirl == boyMember.last()) { sweets += sum - boyMember.last() * m; out.println(sweets); } else { if (NBoyMax > 1) { sweets += sum - boyMember.last() * m; out.println(sweets); } else { Object[] boyList = boyMember.toArray(); if (boyList.length > 1) { long boy = 0; boy = (long)boyList[boyList.length - 2]; sweets += (sum - smallestGirl - boyMember.last() * (m - 1)); sweets += (smallestGirl - boy); out.println(sweets); } else { out.println(-1); } } } in.close(); out.close(); } }
linear
1159_C. The Party and Sweets
CODEFORCES
import java.util.*; import java.math.*; public class Split { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n= sc.nextInt(); int k= sc.nextInt(); int a[] = new int[n]; int d[] = new int[n-1]; for(int i=0;i<n;i++) { a[i] = sc.nextInt(); if(i>0) d[i-1] = a[i-1] - a[i]; } Arrays.sort(d); int t = 0; for(int i=0;i<k-1;i++) t += d[i]; System.out.println(a[n-1]-a[0]+t); } }
nlogn
1197_C. Array Splitting
CODEFORCES
import java.util.*; import java.io.*; public class RGBSubstring { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int Q = scanner.nextInt(); while(Q-->0) { int N = scanner.nextInt(); int K = scanner.nextInt(); String s1 = "RGB"; String s2 = "GBR"; String s3 = "BRG"; char[] arr = scanner.next().toCharArray(); int[] cnts = new int[3]; for(int i = 0; i < K; i++) { int ind = i % 3; if (arr[i] != s1.charAt(ind)) cnts[0]++; if (arr[i] != s2.charAt(ind)) cnts[1]++; if (arr[i] != s3.charAt(ind)) cnts[2]++; } int ans = Math.min(Math.min(cnts[0], cnts[1]), cnts[2]); for(int i = K; i < N; i++) { int ind = (K-1)%3; int[] nextCnts = new int[3]; nextCnts[1] = cnts[0]; nextCnts[2] = cnts[1]; nextCnts[0] = cnts[2]; if ('R' != arr[i-K]) nextCnts[1]--; if ('G' != arr[i-K]) nextCnts[2]--; if ('B' != arr[i-K]) nextCnts[0]--; if (arr[i] != s1.charAt(ind)) nextCnts[0]++; if (arr[i] != s2.charAt(ind)) nextCnts[1]++; if (arr[i] != s3.charAt(ind)) nextCnts[2]++; cnts = nextCnts; for(int j = 0; j < 3; j++) ans = Math.min(ans, cnts[j]); } out.println(ans); } out.flush(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } }
quadratic
1196_D1. RGB Substring (easy version)
CODEFORCES
import java.util.Scanner; public class NickAndArray { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int array[]=new int[n]; int max=Integer.MAX_VALUE; int index=0; for(int i=0;i<n;i++) { int k=sc.nextInt(); array[i]=k; if(array[i]>=0) { array[i]=-array[i]-1; } if(array[i]<max) { max=array[i]; index=i; } } if(n%2!=0) { array[index]=-array[index]-1; } for(int i=0;i<n;i++) { System.out.print(array[i]+" " ); } } }
linear
1180_B. Nick and Array
CODEFORCES
import java.io.*; import java.util.*; public class Solution { static boolean canWinFromOneMove(char []s,int k) { int prefix=0; int n=s.length; for(int i=0;i<n && s[i]==s[0];i++) prefix++; int suffix=0; for(int i=n-1;i>=0 && s[i]==s[n-1];i--) suffix++; return s[0]==s[n-1] && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(),k=sc.nextInt(); char []s=sc.next().toCharArray(); if(canWinFromOneMove(s, k)) { System.out.println("tokitsukaze"); return; } int []suff=new int [n+1]; suff[n-1]=1; for(int i=n-2;i>=0;i--) { suff[i]=1+(s[i+1]==s[i]?suff[i+1]:0); } for(int i=n-2;i>=0;i--) suff[i]=Math.max(suff[i], suff[i+1]); int max=0,curr=0; boolean draw=false; int ones=0; for(int i=0;i+k<=n;i++) { // one int prefix=ones==i?k+ones:max; int suffix=i+k==n?k:s[i+k]=='1' && suff[i+k]==n-(i+k)?k+suff[i+k]:suff[i+k]; char first=i==0?'1':s[0],last=i+k==n?'1':s[n-1]; boolean zero=first==last && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n; // zero prefix=ones==0?k+ones:max; suffix=i+k==n?k:s[i+k]=='0' && suff[i+k]==n-(i+k)?k+suff[i+k]:suff[i+k]; first=i==0?'0':s[0]; last=i+k==n?'0':s[n-1]; boolean one=first==last && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n; if(!zero || !one) { // System.err.println(i+1); draw=true; } if(s[i]=='1') ones++; if(i>0 && s[i]==s[i-1] ) curr++; else curr=1; max=Math.max(max, curr); } out.println(draw?"once again":"quailty"); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
linear
1190_C. Tokitsukaze and Duel
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; public class c { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); int n = in.nextInt(), m = in.nextInt(); long bounty = in.nextInt(), increase = in.nextInt(); int damage = in.nextInt(); int[] mh = new int[n]; int[] sh = new int[n]; int[] reg = new int[n]; long countKilled = 0; ArrayList<Event> es = new ArrayList<>(); Event[] regen = new Event[n]; for(int i=0;i<n;i++) { mh[i] = in.nextInt(); sh[i] = in.nextInt(); reg[i] = in.nextInt(); if(sh[i] <= damage) countKilled++; if(reg[i] > 0) { int time = (damage+1 - sh[i]+reg[i]-1)/reg[i]; if(time > 0 && mh[i] >= damage+1) { Event e2 = new Event(time, i, damage+1); regen[i] = e2; es.add(e2); } } } for(int i=0;i<m;i++) { Event e = new Event(in.nextInt(), in.nextInt()-1, in.nextInt()); es.add(e); if(reg[e.e] > 0) { int time = (damage+1 - e.h+reg[e.e]-1)/reg[e.e]; if(time > 0 && mh[e.e] >= damage+1) { Event e2 = new Event(e.t + time, e.e, damage+1); e.regen = e2; es.add(e2); } } } Collections.sort(es, (a,b) -> a.t-b.t); long ans = countKilled*bounty; int lastTime = 0; for(Event e : es) { if(e.t == -1) continue; if(regen[e.e] != e && regen[e.e] != null) { regen[e.e].t = -1; regen[e.e] = null; } if(lastTime != e.t) { ans = Math.max(ans, countKilled*(bounty+(e.t-1)*increase)); } if(sh[e.e] <= damage) countKilled--; sh[e.e] = e.h; if(sh[e.e] <= damage) countKilled++; if(e.regen != null) { regen[e.e] = e.regen; } lastTime = e.t; } if(countKilled != 0) { if(increase > 0) ans = -1; else ans = Math.max(ans, countKilled*bounty); } System.out.println(ans); } static class Event { int t; int e; int h; Event regen; public Event(int tt, int ee, int hh) { t = tt; e = ee; h = hh; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws IOException { if(st.hasMoreTokens()) return st.nextToken(); else st = new StringTokenizer(br.readLine()); return next(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
nlogn
912_C. Perun, Ult!
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class KingEscape { public static void main(String[] args) { Reader read = new Reader(); int n = read.nextInt(); int a1 = read.nextInt(); int a2 = read.nextInt(); int b1 = read.nextInt(); int b2 = read.nextInt(); int c1 = read.nextInt(); int c2 = read.nextInt(); if (b1 > a1 && b2 > a2 && c1 > a1 && c2 > a2) System.out.print("YES"); else if (b1 > a1 && b2 < a2 && c1 > a1 && c2 < a2) System.out.print("YES"); else if (b1 < a1 && b2 > a2 && c1 < a1 && c2 > a2) System.out.print("YES"); else if (b1 < a1 && b2 < a2 && c1 < a1 && c2 < a2) System.out.print("YES"); else System.out.print("NO"); } private static class Reader { private final BufferedReader reader; private final String separator; private String ln; private String[] tokens; private int ptr; Reader(String separator, InputStream input) { this.reader = new BufferedReader(new InputStreamReader(input)); this.separator = separator; this.ptr = -1; } Reader(String separator) { this(separator, System.in); } Reader() { this(" "); } String nextStr(){ if (Objects.isNull(ln)) { try { ln = reader.readLine(); } catch (IOException e) { System.out.println(e.getMessage()); } if (Objects.nonNull(ln)) { tokens = ln.split(separator); ptr = 0; } else { throw new NoSuchElementException("no next element"); } } else if (ptr == tokens.length) { ln = null; tokens = null; ptr = -1; return nextStr(); } return tokens[ptr++]; } int nextInt() { return Integer.parseInt(nextStr()); } long nextLong() { return Long.parseLong(nextStr()); } double nextDouble() { return Double.parseDouble(nextStr()); } } }
constant
1033_A. King Escape
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Map; import java.util.HashMap; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ReaderFastIO in = new ReaderFastIO(inputStream); PrintWriter out = new PrintWriter(outputStream); DConcatenatedMultiples solver = new DConcatenatedMultiples(); solver.solve(1, in, out); out.close(); } static class DConcatenatedMultiples { public void solve(int testNumber, ReaderFastIO in, PrintWriter out) { Map<Integer, Integer>[] mapMods = new HashMap[11]; int n = in.nextInt(); int k = in.nextInt(); int[] a = in.readArrayInt(n); for (int i = 0; i < 11; i++) { mapMods[i] = new HashMap<>(); } for (int i = 0; i < n; i++) { int pot = getPot(a[i]); mapMods[pot].put(a[i] % k, mapMods[pot].getOrDefault(a[i] % k, 0) + 1); } long ct = 0; for (int i = 0; i < n; i++) { int ownPot = getPot(a[i]); long suffix = a[i] * 10L; for (int j = 1; j <= 10; j++) { int mod = (int) (suffix % k); int comMod = (k - mod) % k; int qt = mapMods[j].getOrDefault(comMod, 0); if (j == ownPot && (a[i] % k) == comMod) { qt--; } ct += qt; suffix = (suffix * 10L) % k; } } out.println(ct); } public int getPot(int x) { int ct = 0; while (x != 0) { x /= 10; ct++; } return ct; } } static class ReaderFastIO { BufferedReader br; StringTokenizer st; public ReaderFastIO() { br = new BufferedReader(new InputStreamReader(System.in)); } public ReaderFastIO(InputStream input) { br = new BufferedReader(new InputStreamReader(input)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] readArrayInt(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } } }
nlogn
1029_D. Concatenated Multiples
CODEFORCES
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Equator { public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static StringTokenizer st; public static void main(String[] args) throws IOException { int n = nextInt(); int[] a = intArray(n); long s = 0; for (int x : a) s += x; long m = 0; for (int i = 0; i < n; i++) { m += a[i]; if (m*2 >= s) { System.out.println(i+1); return; } } } public static String nextLine() throws IOException { return in.readLine(); } public static String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(nextString()); } public static long nextLong() throws IOException { return Long.parseLong(nextString()); } public static int[] intArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public static int[][] intArray(int n, int m) throws IOException { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = nextInt(); return a; } public static long[] longArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } }
linear
962_A. Equator
CODEFORCES
//package codeforces; import java.util.Scanner; public class Fingerprints { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] code = new int[scanner.nextInt()]; int[] prints = new int[scanner.nextInt()]; for (int i = 0; i < code.length; i++) { code[i] = scanner.nextInt(); } for (int i = 0; i < prints.length; i++) { prints[i] = scanner.nextInt(); } for (int i = 0; i < code.length; i++) { for (int j = 0; j < prints.length; j++) { if (code[i] == prints[j]) { System.out.print(prints[j] + " "); } } } scanner.close(); } }
quadratic
994_A. Fingerprints
CODEFORCES
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; int n; int m; char[][] mat; long base = 397; void solve() throws IOException { n = nextInt(); m = nextInt(); mat = new char[n][m]; for (int i = 0; i < n; i++) { mat[i] = nextString().toCharArray(); } int alpha = 26; long[] pow = new long[alpha]; pow[0] = 1; for (int i = 1; i < alpha; i++) { pow[i] = pow[i - 1] * base % MOD; } long res = 0; for (int l = 0; l < m; l++) { //[l, r] long[] hash = new long[n]; long[] mask = new long[n]; for (int r = l; r < m; r++) { for (int i = 0; i < n; i++) { hash[i] += pow[mat[i][r] - 'a']; hash[i] %= MOD; mask[i] = mask[i] ^ (1L << (mat[i][r] - 'a')); } int start = 0; while (start < n) { if ((mask[start] & (mask[start] - 1)) != 0) { start++; continue; } int end = start; List<Long> l1 = new ArrayList<>(); while (end < n && (mask[end] & (mask[end] - 1)) == 0) { l1.add(hash[end]); end++; } start = end; res += manacher(l1); } } } outln(res); } long manacher(List<Long> arr) { int len = arr.size(); long[] t = new long[len * 2 + 3]; t[0] = -1; t[len * 2 + 2] = -2; for (int i = 0; i < len; i++) { t[2 * i + 1] = -3; t[2 * i + 2] = arr.get(i); } t[len * 2 + 1] = -3; int[] p = new int[t.length]; int center = 0, right = 0; for (int i = 1; i < t.length - 1; i++) { int mirror = 2 * center - i; if (right > i) { p[i] = Math.min(right - i, p[mirror]); } // attempt to expand palindrome centered at i while (t[i + (1 + p[i])] == t[i - (1 + p[i])]) { p[i]++; } // if palindrome centered at i expands past right, // adjust center based on expanded palindrome. if (i + p[i] > right) { center = i; right = i + p[i]; } } long res = 0; for (int i = 0; i < 2 * len; i++) { int parLength = p[i + 2]; if (i % 2 == 0) { res += (parLength + 1) / 2; } else { res += parLength / 2; } } return res; } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { outln(String.format("%.9f%n", val)); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
nlogn
1080_E. Sonya and Matrix Beauty
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class loser { static class InputReader { public BufferedReader br; public StringTokenizer token; public InputReader(InputStream stream) { br=new BufferedReader(new InputStreamReader(stream),32768); token=null; } public String next() { while(token==null || !token.hasMoreTokens()) { try { token=new StringTokenizer(br.readLine()); } catch(IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } static class card{ int l; int r; public card(int ch,int i) { this.l=ch; this.r=i; } } static class sort implements Comparator<card> { public int compare(card o1,card o2) { if(o1.l!=o2.l) return (int)(o1.l-o2.l); else return (int)(o1.r-o2.r); } } static void shuffle(long a[]) { List<Long> l=new ArrayList<>(); for(int i=0;i<a.length;i++) l.add(a[i]); Collections.shuffle(l); for(int i=0;i<a.length;i++) a[i]=l.get(i); } /*static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } static int ans1=Integer.MAX_VALUE,ans2=Integer.MAX_VALUE,ans3=Integer.MAX_VALUE,ans4=Integer.MAX_VALUE; static boolean v[]=new boolean[101]; static void dfs(Integer so,Set<Integer> s[]){ if(!v[so.intValue()]) { v[so]=true; for(Integer h:s[so.intValue()]) { if(!v[h.intValue()]) dfs(h,s); } } } static class Print{ public PrintWriter out; Print(OutputStream o) { out=new PrintWriter(o); } } static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } static int LongestIncreasingSubsequenceLength(int A[], int size) { // Add boundary case, when array size is one int[] tailTable = new int[size]; int len; // always points empty slot tailTable[0] = A[0]; len = 1; for (int i = 1; i < size; i++) { if (A[i] < tailTable[0]) // new smallest value tailTable[0] = A[i]; else if (A[i] > tailTable[len - 1]) // A[i] wants to extend largest subsequence tailTable[len++] = A[i]; else // A[i] wants to be current end candidate of an existing // subsequence. It will replace ceil value in tailTable tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; } return len; }*/ /*static int binary(int n) { int s=1; while(n>0) { s=s<<1; n--; } return s-1; } static StringBuilder bin(int i,int n) { StringBuilder s=new StringBuilder(); while(i>0) { s.append(i%2); i=i/2; } while(s.length()!=n) { s.append(0); } return s.reverse(); }*/ static boolean valid(int i,int j,int n,int m) { if(i<n && i>=0 && j<m && j>=0) return true; else return false; } public static void main(String[] args) { InputReader sc=new InputReader(System.in); int n=sc.nextInt(); int s=sc.nextInt(); card c[]=new card[n]; for(int i=0;i<n;i++) { int x=sc.nextInt(); int y=sc.nextInt(); c[i]=new card(x,y); } Arrays.sort(c,new sort()); int time=0; for(int i=n-1;i>=0;i--) { time+=s-c[i].l; if((c[i].r-time)>0) time+=c[i].r-time; s=c[i].l; } if(c[0].l!=0) time+=c[0].l; System.out.println(time); } }
nlogn
608_A. Saitama Destroys Hotel
CODEFORCES
import java.io.*; import java.lang.*; import java.util.*; import static java.lang.Integer.*; import static java.lang.Long.*; import static java.lang.Math.*; import static java.lang.System.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main { Main() throws IOException { String a = nextLine(); String b = nextLine(); long ans = 0; int s = 0; for (int i = 0; i < b.length() - a.length(); ++i) { s += b.charAt(i) == '1' ? 1 : 0; } for (int i = 0; i < a.length(); ++i) { s += b.charAt(i + b.length() - a.length()) == '1' ? 1 : 0; ans += a.charAt(i) == '1' ? b.length() - a.length() + 1 - s : s; s -= b.charAt(i) == '1' ? 1 : 0; } out.println(ans); } ////////////////////////////// PrintWriter out = new PrintWriter(System.out, false); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stok = null; String nextLine() throws IOException { while (stok == null || !stok.hasMoreTokens()) { stok = new StringTokenizer(in.readLine()); } return stok.nextToken(); } public static void main(String args[]) throws IOException { if (args.length > 0) { setIn(new FileInputStream(args[0] + ".inp")); setOut(new PrintStream(args[0] + ".out")); } Main solver = new Main(); solver.out.flush(); // could be replace with a method, but nah, this is just competitive programming :p } }
linear
608_B. Hamming Distance Sum
CODEFORCES