src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.util.*; public class vas2 { public static void main( String[] args ) { Scanner in = new Scanner( System.in ); int n = in.nextInt(); String st = in.next(); int[] a = new int[n]; for ( int i = 0; i < n; i++ ) a[i] = st.charAt( i ) - 48; boolean c = false; for ( int i = 1; !c && i < n; i++ ) { int s = 0; for ( int j = 0; j < i; j++ ) s += a[j]; int t = 0; for ( int j = i; j < n; j++ ) { t += a[j]; if ( t > s ) if ( t - a[j] != s ) break; else t = a[j]; } if ( t == s ) c = true; } System.out.println( c ? "YES" : "NO" ); } }
quadratic
1030_C. Vasya and Golden Ticket
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 LogicalExpression { int N = 256; void solve() { Expression[] E = new Expression[N]; for (int i = 0; i < N; i++) E[i] = new Expression(); E[Integer.parseInt("00001111", 2)].update_f("x"); E[Integer.parseInt("00110011", 2)].update_f("y"); E[Integer.parseInt("01010101", 2)].update_f("z"); for (int l = 2; l < 40; l++) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (E[i].e != null && E[j].t != null && E[i].e.length() + E[j].t.length() + 1 == l) { E[i | j].update_e(E[i].e + '|' + E[j].t); } if (E[i].t != null && E[j].f != null && E[i].t.length() + E[j].f.length() + 1 == l) { E[i & j].update_t(E[i].t + '&' + E[j].f); } } if (E[i].f != null) E[i ^ (N - 1)].update_f('!' + E[i].f); } } String[] res = new String[N]; for (int i = 0; i < N; i++) res[i] = E[i].calc_best(); int n = in.nextInt(); for (int i = 0; i < n; i++) { int x = Integer.parseInt(in.nextToken(), 2); out.println(res[x]); } } static class Expression { String e, t, f; Expression() { } public Expression(String e, String t, String f) { this.e = e; this.t = t; this.f = f; } String calc_best() { String best = e; if (compare(best, t) > 0) best = t; if (compare(best, f) > 0) best = f; return best; } void update_e(String ne) { if (e == null || compare(e, ne) > 0) { e = ne; update_f('(' + e + ')'); } } void update_t(String nt) { if (t == null || compare(t, nt) > 0) { t = nt; update_e(t); } } void update_f(String nf) { if (f == null || compare(f, nf) > 0) { f = nf; update_t(f); } } int compare(String a, String b) { if (a.length() != b.length()) return Integer.compare(a.length(), b.length()); return a.compareTo(b); } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new LogicalExpression().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()); } } }
quadratic
913_E. Logical Expression
CODEFORCES
import java.util.*; import java.io.*; public class FirstClass { 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()); int arr[] = new int [n]; StringTokenizer st1 = new StringTokenizer(br.readLine()); for(int i = 0 ; i < n ; i++) { arr[i] = Integer.parseInt(st1.nextToken()); } int max = -1; boolean flag = true; for(int i = 0 ; i < n ; i++) { if(arr[i] > max+1) { flag = false; out.println(i+1); break; } else { max = Math.max(max, arr[i]); } } if(flag) out.println(-1); out.flush(); out.close(); } }
linear
1054_B. Appending Mex
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class AnnoyingPresent { //UPSOLVED public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); long n = Long.parseLong(st.nextToken()) , m = Long.parseLong(st.nextToken()); long sum = 0; for(int i=0;i<m;i++){ StringTokenizer st1 = new StringTokenizer(br.readLine()); sum+= n* Long.parseLong(st1.nextToken()); Long a= Long.parseLong(st1.nextToken()); if(a < 0){ if(n % 2 == 0) sum += n*n / 4*a; else{ sum += (n/2) * (n/2+1) * a; } } else sum += (a*(n) * (n-1) / 2); } System.out.println((double)sum/n); } }
linear
1009_C. Annoying Present
CODEFORCES
import java.util.*; import java.io.*; import java.lang.reflect.Array; public class codeforces { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); long U = in.nextLong(); long[] E = new long[n]; double max = -1; for(int i=0;i<n;i++) E[i] = in.nextLong(); for(int k=1;k<n-1;k++) { int i = k + 1, j = n - 1, mid = 0; double T = 0; while(i < j) { mid = (int)Math.ceil((double)(i+j)/2); if(E[mid] - E[k-1] <= U) i = mid; else j = mid - 1; } j = k; k = i; i = j - 1; T = E[k] - E[j]; T /= E[k] - E[i]; if(E[k] - E[i] <= U) max = Math.max(max, T); k = j; } pw.println(max); pw.flush(); pw.close(); } /* public static void DFS(int sourse) { int count = 0; visited[sourse] = true; for(int u : adj[sourse]) { if(!visited[u]) { DFS(u); } } }*/ public static ArrayList Divisors(long n) { ArrayList<Long> div = new ArrayList<>(); for (long i=1; i<=Math.sqrt(n); i++) { if (n%i == 0) { div.add(i); if(n/i != i) div.add(n/i); } } return div; } public static int BinarySearch(long[] a, long k) { int n = a.length; int i = 0, j = n-1; int mid = 0; if(k < a[0]) return 0; else if(k >= a[n-1]) return n; else { while(j - i > 1) { mid = (i+j)/2; if(k >= a[mid]) i = mid; else j = mid; } } return i+1; } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x - x == 0 && p.y - y == 0 ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } 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 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); } } static class CodeX { public static void sort(long arr[]) { merge_sort(arr, 0, arr.length - 1); } private static void merge_sort(long A[], long start, long end) { if (start < end) { long mid = (start + end) / 2; merge_sort(A, start, mid); merge_sort(A, mid + 1, end); merge(A, start, mid, end); } } private static void merge(long A[], long start,long mid, long end) { long p = start, q = mid + 1; long Arr[] = new long[(int)(end - start + 1)]; long k = 0; for (int i = (int)start; i <= end; i++) { if (p > mid) Arr[(int)k++] = A[(int)q++]; else if (q > end) Arr[(int)k++] = A[(int)p++]; else if (A[(int)p] < A[(int)q]) Arr[(int)k++] = A[(int)p++]; else Arr[(int)k++] = A[(int)q++]; } for (int i = 0; i < k; i++) { A[(int)start++] = Arr[i]; } } } }
nlogn
957_C. Three-level Laser
CODEFORCES
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.*; public class Main { static Graph graph[]; public static void add_edge(int u,int v) { graph[u].adj.add(graph[v]); graph[v].adj.add(graph[u]); } public static void dfs(int index) { Graph z=graph[index]; z.vis=1;Graph v; for( int i=0;i<z.adj.size();i++) { v=z.adj.get(i); if(v.vis==0) { v.dist=z.dist+1; v.parent=z.val; dfs(v.val); } } } 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()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc=new FastReader(); int n=sc.nextInt(); Pair arr[]=new Pair[n]; Pair pref[]=new Pair[n]; Pair suff[]=new Pair[n]; for( int i=0;i<n;i++) { long u=sc.nextLong(); long v=sc.nextLong(); arr[i]=new Pair(u,v); pref[i]=new Pair(0,0); suff[i]=new Pair(0,0); } pref[0].x=arr[0].x; pref[0].y=arr[0].y; for( int i=1;i<n;i++) { pref[i].x=(long)Math.max(pref[i-1].x,arr[i].x); pref[i].y=(long)Math.min(pref[i-1].y,arr[i].y); } suff[n-1].x=arr[n-1].x; suff[n-1].y=arr[n-1].y; for( int i=n-2;i>=0;i--) { suff[i].x=(long)Math.max(suff[i+1].x,arr[i].x); suff[i].y=(long)Math.min(suff[i+1].y,arr[i].y); } long max=Long.MIN_VALUE; long ans=0; for( int i=0;i<n;i++) { long val=Long.MAX_VALUE; long val1=Long.MAX_VALUE; if(i!=0&&i!=n-1) { val=(long)Math.min(pref[i-1].y,suff[i+1].y)-(long)Math.max(pref[i-1].x,suff[i+1].x); } else if(i!=n-1) { val=suff[i+1].y-suff[i+1].x; } else val=pref[i-1].y-pref[i-1].x; ans=val; if(ans<0) ans=0; max=(long)Math.max(ans,max); } System.out.println(max); } } class mycomparator implements Comparator<Graph> { public int compare(Graph a, Graph b) { return b.dist-a.dist; } } class Graph { int vis,col,val;int parent;int deg;int dist; ArrayList<Graph> adj; Graph(int val) { vis=0; col=-1; adj=new ArrayList<>(); parent=-1; this.val=val; deg=0; dist=-1; } } class Pair { long x,y; Pair( long x, long y) { this.x=x; this.y=y; } }
linear
1029_C. Maximal Intersection
CODEFORCES
import java.util.*; public class ehab4 { public static void main( String[] args ) { Scanner in = new Scanner( System.in ); int a = 0, b = 0; System.out.println( "? 0 0 " ); System.out.flush(); int c = in.nextInt(); for ( int i = 29; i >= 0; i-- ) { System.out.println( "? " + ( a + ( 1 << i ) ) + " " + b ); System.out.flush(); int q1 = in.nextInt(); System.out.println( "? " + a + " " + ( b + ( 1 << i ) ) ); System.out.flush(); int q2 = in.nextInt(); if ( q1 == q2 ) { if ( c == 1 ) a += ( 1 << i ); else if ( c == -1 ) b += ( 1 << i ); c = q1; } else if ( q1 == -1 ) { a += ( 1 << i ); b += ( 1 << i ); } else if ( q1 == -2 ) return; } System.out.println( "! " + a + " " + b ); System.out.flush(); } }
logn
1088_D. Ehab and another another xor problem
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); //Scanner sc = new Scanner(); Reader in = new Reader(); Main solver = new Main(); solver.solve(out, in); out.flush(); out.close(); } static int INF = (int)1e5*4*4+5; static int maxn = (int)1e5*2+1; static int mod=(int)1e9+7 ; static int n,m,k,t,q,x,a,b,y; static ArrayList<Integer> adj[]; static int[] dist,parent,back; static boolean[] vis,vist; static int root=0,ans=1; void solve(PrintWriter out, Reader in) throws IOException{ n = in.nextInt(); if(n==1) {out.println(1);return;} adj = new ArrayList[n+1]; for(int i=1;i<=n;i++) adj[i] = new ArrayList<Integer>(); int u,v; for(int i=0;i<n-1;i++){ u = in.nextInt(); v = in.nextInt(); adj[u].add(v); adj[v].add(u); } vist = new boolean[n+1]; vis = new boolean[n+1]; vist[1] =true; makeroot(1); parent = new int[n+1]; dist = new int[n+1]; back = new int[n+1]; dfs(root,0); calcdist(root); vist = new boolean[n+1]; vis = new boolean[n+1]; vist[root] =true; PriorityQueue<Node> pq = new PriorityQueue<Node>(); for(int i=1;i<=n;i++){ if(i!=root) pq.add(new Node(i,dist[i])); } Node elm; int rt = root; out.print(1); makeroot(root); removeNodes(root,rt); ans+=dist[rt]; out.print(" "+ans); int itr=2; for(int i=2;i<=n;i++){ elm = pq.remove(); if(vis[elm.idx]) continue; removeNodes(back[elm.idx],elm.idx); ans += elm.dist+1; out.print(" "+ans); itr++; } for(int i=itr;i<n;i++) out.print(" "+ans); out.println(); } //<> static class Node implements Comparable<Node>{ int dist,idx; Node(int idx,int dist){ this.idx = idx; this.dist = dist; } public int compareTo(Node o) { return o.dist-this.dist; } } static void removeNodes(int s,int e){ vis[s]=true; while(s!=e){ vis[s] = true; s = parent[s]; } vis[s]=true; return; } static int calcdist(int s){ int res=0; int tmp=0; for(int e:adj[s]){ if(e!=parent[s]){ tmp= calcdist(e); if(1+tmp>res){ res = 1+tmp; back[s] = back[e]; } } } if(res==0) back[s]=s; return dist[s] = res; } static void dfs(int s,int p){ for(int e:adj[s]){ if(e!=p){ parent[e]=s; dfs(e,s); } } return; } static void makeroot(int s){ Queue<Integer> q = new LinkedList<>(); q.add(s); int elm=0; while(q.size()!=0){ elm = q.remove(); for(int e:adj[elm]){ if(!vist[e]){ vist[e]=true; q.add(e); root = e; } } } return; } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int 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 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(); } double nextDouble() { return Double.parseDouble(next()); } 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 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) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
nlogn
958_B2. Maximum Control (medium)
CODEFORCES
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.min; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class F { static void solve() throws Exception { int n = scanInt(); long l[] = new long[n]; for (int i = 0; i < n; i++) { l[i] = scanLong(); } long e1 = 0, e2 = 0, ans = 0; boolean water = false; String types = scanString(); for (int i = 0; i < n; i++) { long li = l[i], cur; switch (types.charAt(i)) { case 'G': cur = min(e1, li); e1 -= cur; li -= cur; e2 += 2 * cur; ans += 2 * cur; e2 += li; ans += 3 * li; break; case 'W': water = true; e1 += li; ans += 2 * li; break; case 'L': cur = min(e1, li); e1 -= cur; li -= cur; ans += 2 * cur; cur = min(e2, li); e2 -= cur; li -= cur; ans += 3 * cur; ans += (water ? 4 : 6) * li; break; default: throw new AssertionError(); } } out.print(ans); } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
linear
1091_F. New Year and the Mallard Expedition
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test3 { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int x=Integer.parseInt(br.readLine()); int y=Integer.parseInt(br.readLine()); System.out.print((int)(y%(Math.pow(2, x)))); } }
constant
913_A. Modular Exponentiation
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Solution{ public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringTokenizer st; for(int z=0;z<t;z++){ st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int min=1; int max=1; for(int i=0;i<n;i++){ int k = Integer.parseInt(st.nextToken()); if(max<k){ min = max; max = k; }else if(min<k){ min = k; } } int res = Math.min(n-2,min-1); System.out.println(res); } } }
linear
1197_A. DIY Wooden Ladder
CODEFORCES
// discussed with rainboy import java.io.*; import java.util.*; public class CF915D { static ArrayList[] aa; static boolean[] visited, instack; static int[] stack; static int cnt, h_, i_, j_; static boolean dfs1(int i) { if (visited[i]) { if (instack[i]) { h_ = i; return true; } return false; } visited[i] = instack[i] = true; stack[cnt++] = i; ArrayList<Integer> adj = aa[i]; for (int j : adj) if (dfs1(j)) return true; instack[i] = false; cnt--; return false; } static boolean dfs2(int i) { if (visited[i]) return instack[i]; visited[i] = instack[i] = true; ArrayList<Integer> adj = aa[i]; for (int j : adj) if (!(i == i_ && j == j_) && dfs2(j)) return true; instack[i] = false; return false; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); aa = new ArrayList[n]; for (int i = 0; i < n; i++) aa[i] = new ArrayList<Integer>(); while (m-- > 0) { st = new StringTokenizer(br.readLine()); int i = Integer.parseInt(st.nextToken()) - 1; int j = Integer.parseInt(st.nextToken()) - 1; aa[i].add(j); } visited = new boolean[n]; instack = new boolean[n]; stack = new int[n]; for (int i = 0; i < n; i++) if (dfs1(i)) break; if (cnt == 0) { System.out.println("YES"); return; } for (j_ = h_, i_ = stack[--cnt]; ; j_ = i_, i_ = stack[--cnt]) { Arrays.fill(visited, false); Arrays.fill(instack, false); boolean cycle = false; for (int i = 0; i < n; i++) if (dfs2(i)) { cycle = true; break; } if (!cycle) { System.out.println("YES"); return; } if (i_ == h_) break; } System.out.println("NO"); } }
quadratic
915_D. Almost Acyclic Graph
CODEFORCES
//package fourninetysixDiv3; import java.util.HashMap; import java.util.Scanner; public class Median_Segments_general { 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]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } System.out.println(func(n, m, arr)-func(n, m+1, arr)); } public static long func(int n,int m,int[] arr) { HashMap<Long, Integer> map = new HashMap<>(); map.put((long) 0, 1); long sum = 0; long res = 0; long add=0; for(int i=0;i<n;i++) { if(arr[i]<m) { sum--; if(map.containsKey(sum)) { add-=map.get(sum); } } else { if(map.containsKey(sum)) { add+=map.get(sum); } sum++; } res+=add; if(map.containsKey(sum)) { map.put(sum, map.get(sum)+1); } else { map.put(sum,1); } } return res; } }
nlogn
1005_E1. Median on Segments (Permutations Edition)
CODEFORCES
import java.io.*; import java.util.*; public class Main { private static void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); List<List<Integer>> g = new ArrayList<>(n + 1); for (int i = 0; i < n + 1; i++) { g.add(new LinkedList<>()); } int degree1 = 0, degree2 = 0, root = 0; for (int i = 0; i < n - 1; i++) { int a = in.nextInt(); int b = in.nextInt(); g.get(a).add(b); g.get(b).add(a); if (g.get(a).size() > degree1) { if (a == root) { degree1 = g.get(a).size(); } else { degree2 = degree1; degree1 = g.get(a).size(); root = a; } } else if (g.get(a).size() > degree2) { degree2 = g.get(a).size(); } if (g.get(b).size() > degree1) { if (b == root) { degree1 = g.get(b).size(); } else { degree2 = degree1; degree1 = g.get(b).size(); root = b; } } else if (g.get(b).size() > degree2) { degree2 = g.get(b).size(); } } if (degree2 > 2) { out.print("No"); } else { out.println("Yes"); List<Integer> leaves = new LinkedList<>(); for (int i = 1; i <= n; i++) { if (i != root) { if (g.get(i).size() == 1) { leaves.add(i); } } } out.println(leaves.size()); for (int i : leaves) { out.println(root + " " + i); } } } private static void shuffleArray(int[] array) { int index; Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { index = random.nextInt(i + 1); if (index != i) { array[index] ^= array[i]; array[i] ^= array[index]; array[index] ^= array[i]; } } } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); solve(in, out); in.close(); out.close(); } private static class InputReader { private BufferedReader br; private StringTokenizer st; InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); st = null; } String nextLine() { String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } String next() { while (st == null || !st.hasMoreTokens()) { String line = nextLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } byte nextByte() { return Byte.parseByte(next()); } short nextShort() { return Short.parseShort(next()); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } private static class OutputWriter { BufferedWriter bw; OutputWriter(OutputStream os) { bw = new BufferedWriter(new OutputStreamWriter(os)); } void print(int i) { print(Integer.toString(i)); } void println(int i) { println(Integer.toString(i)); } void print(long l) { print(Long.toString(l)); } void println(long l) { println(Long.toString(l)); } void print(double d) { print(Double.toString(d)); } void println(double d) { println(Double.toString(d)); } void print(boolean b) { print(Boolean.toString(b)); } void println(boolean b) { println(Boolean.toString(b)); } void print(char c) { try { bw.write(c); } catch (IOException e) { e.printStackTrace(); } } void println(char c) { println(Character.toString(c)); } void print(String s) { try { bw.write(s); } catch (IOException e) { e.printStackTrace(); } } void println(String s) { print(s); print('\n'); } void close() { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
linear
981_C. Useful Decomposition
CODEFORCES
// practice with rainboy import java.io.*; import java.util.*; public class CF903F { static final int INF = 0x3f3f3f3f; static void fill(int[][][][] aa, int a) { for (int h0 = 0; h0 <= 4; h0++) for (int h1 = 0; h1 <= 4; h1++) for (int h2 = 0; h2 <= 4; h2++) for (int h3 = 0; h3 <= 4; h3++) aa[h0][h1][h2][h3] = a; } 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 a1 = Integer.parseInt(st.nextToken()); int a2 = Integer.parseInt(st.nextToken()); int a3 = Integer.parseInt(st.nextToken()); int a4 = Integer.parseInt(st.nextToken()); int[] aa = new int[10]; aa[0] = aa[1] = aa[2] = aa[3] = a1; aa[4] = aa[5] = aa[6] = a2; aa[7] = aa[8] = a3; aa[9] = a4; int[][] ww = new int[10][4]; ww[0][0] = 1; ww[1][1] = 1; ww[2][2] = 1; ww[3][3] = 1; ww[4][0] = ww[4][1] = 2; ww[5][1] = ww[5][2] = 2; ww[6][2] = ww[6][3] = 2; ww[7][0] = ww[7][1] = ww[7][2] = 3; ww[8][1] = ww[8][2] = ww[8][3] = 3; ww[9][0] = ww[9][1] = ww[9][2] = ww[9][3] = 4; char[][] cc = new char[4][n + 8]; for (int k = 0; k < 4; k++) { char[] c_ = cc[k]; br.readLine().getChars(0, n, c_, 4); c_[0] = c_[1] = c_[2] = c_[3] = c_[n + 4] = c_[n + 5] = c_[n + 6] = c_[n + 7] = '.'; } int[][][][] dp = new int[5][5][5][5]; int[][][][] dq = new int[5][5][5][5]; fill(dp, INF); dp[4][4][4][4] = 0; int[] hh = new int[4]; for (int i = 0; i < n + 4; i++) { for (int h0 = 0; h0 <= 4; h0++) for (int h1 = 0; h1 <= 4; h1++) for (int h2 = 0; h2 <= 4; h2++) for (int h3 = 0; h3 <= 4; h3++) for (int s = 0; s < 10; s++) { hh[0] = h0; hh[1] = h1; hh[2] = h2; hh[3] = h3; for (int k = 0; k < 4; k++) { int h = ww[s][k]; if (hh[k] < h) { while (h < 4 && cc[k][i + h] == '.') h++; hh[k] = h; } } int x = dp[h0][h1][h2][h3] + aa[s]; if (dp[hh[0]][hh[1]][hh[2]][hh[3]] > x) dp[hh[0]][hh[1]][hh[2]][hh[3]] = x; } fill(dq, INF); for (int h0 = 1; h0 <= 4; h0++) { hh[0] = h0 < 4 || cc[0][i + 4] == '*' ? h0 - 1 : 4; for (int h1 = 1; h1 <= 4; h1++) { hh[1] = h1 < 4 || cc[1][i + 4] == '*' ? h1 - 1 : 4; for (int h2 = 1; h2 <= 4; h2++) { hh[2] = h2 < 4 || cc[2][i + 4] == '*' ? h2 - 1 : 4; for (int h3 = 1; h3 <= 4; h3++) { hh[3] = h3 < 4 || cc[3][i + 4] == '*' ? h3 - 1 : 4; int x = dp[h0][h1][h2][h3]; if (dq[hh[0]][hh[1]][hh[2]][hh[3]] > x) dq[hh[0]][hh[1]][hh[2]][hh[3]] = x; } } } } int[][][][] tmp = dp; dp = dq; dq = tmp; } System.out.println(dp[4][4][4][4]); } }
linear
903_F. Clear The Matrix
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SFly { public static void main(String[] args) throws IOException { BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); int planet = Integer.parseInt(lector.readLine()); int ini = Integer.parseInt(lector.readLine()); double peso = ini; int[] desp = new int[planet]; int[] ater = new int[planet]; String[] temp = lector.readLine().split(" "); for(int i=0; i<planet; i++) { desp[i] = Integer.parseInt(temp[i]); if(desp[i] == 1) { System.out.println(-1); lector.close(); return; } } temp = lector.readLine().split(" "); for(int i=0; i<planet; i++) { ater[i] = Integer.parseInt(temp[i]); if(ater[i] == 1) { System.out.println(-1); lector.close(); return; } } temp = null; int i=planet-1; peso = (peso*ater[0])/(ater[0]-1); while(i>0) { peso = (peso*desp[i])/(desp[i]-1); peso = (peso*ater[i])/(ater[i]-1); i--; } peso = (peso*desp[0])/(desp[0]-1); peso = peso - ini; System.out.println(peso); lector.close(); } }
linear
1010_A. Fly
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; 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 * * @author kessido */ 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); TaskG solver = new TaskG(); solver.solve(1, in, out); out.close(); } static class TaskG { static int[][] g; static int n; static int[] a; static int[][] edges; static long[] dp; static long[] dpPathToRootWithDetours; static int time = 0; static int[] appearance; static int[] firstAppearance; static int[] depth; public static void dfs(int i, int parE) { firstAppearance[i] = time; appearance[time++] = i; dp[i] = a[i]; for (int eIndex : g[i]) { if (eIndex == parE) continue; int child = i ^ edges[eIndex][0] ^ edges[eIndex][1]; dfs(child, eIndex); appearance[time++] = i; dp[i] += Math.max(dp[child] - edges[eIndex][2] * 2, 0); } } public static void dfs2(int i, int parE) { if (i == 0) { dpPathToRootWithDetours[i] = dp[i]; } else { int par = i ^ edges[parE][0] ^ edges[parE][1]; depth[i] = depth[par] + 1; dpPathToRootWithDetours[i] = dpPathToRootWithDetours[par] - Math.max(0, dp[i] - edges[parE][2] * 2); dpPathToRootWithDetours[i] -= edges[parE][2]; dpPathToRootWithDetours[i] += dp[i]; long myPathWeight = Math.max(dp[i] - edges[parE][2] * 2, 0); long change = dp[par] - myPathWeight - edges[parE][2] * 2; change = Math.max(change, 0); dp[i] += change; } for (int eIndex : g[i]) { if (eIndex == parE) continue; dfs2(i ^ edges[eIndex][0] ^ edges[eIndex][1], eIndex); } } public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.NextInt(); int q = in.NextInt(); a = in.NextIntArray(n); edges = new int[n - 1][3]; { long[] count = new long[n]; for (int i = 0; i < n - 1; i++) { int u = in.NextInt() - 1; int v = in.NextInt() - 1; int w = in.NextInt(); edges[i][0] = u; edges[i][1] = v; edges[i][2] = w; count[u]++; count[v]++; } g = new int[n][]; for (int i = 0; i < n; i++) { g[i] = new int[(int) count[i]]; } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < 2; j++) { g[edges[i][j]][(int) --count[edges[i][j]]] = i; } } } dp = new long[n]; dpPathToRootWithDetours = new long[n]; depth = new int[n]; firstAppearance = new int[n]; appearance = new int[(n - 1) * 2 + 1]; dfs(0, -1); dfs2(0, -1); GraphLowestCommonAncestor.LCA lca = GraphLowestCommonAncestor.createLCA(appearance, firstAppearance, depth); firstAppearance = null; depth = null; appearance = null; edges = null; g = null; for (int i = 0; i < q; i++) { int u = in.NextInt() - 1; int v = in.NextInt() - 1; int lcaI = lca.getLCA(u, v); long res = dpPathToRootWithDetours[u] + dpPathToRootWithDetours[v] - 2 * dpPathToRootWithDetours[lcaI] + dp[lcaI]; out.println(res); } } } static class MinRangeSparseTable implements ISearchInRange { private final int[][] sparseTables; private final long[] array; private final boolean reverseOrdered; public MinRangeSparseTable(long[] array, boolean reverseOrdered) { this.reverseOrdered = reverseOrdered; this.array = array; int LCALength = IntegerExtension.getNumberOfBits(array.length); sparseTables = new int[LCALength][]; sparseTables[0] = new int[array.length]; for (int i = 0; i < array.length; i++) { sparseTables[0][i] = i; } for (int i = 1; i < LCALength; i++) { int size = 1 << i; int jumpSize = 1 << (i - 1); sparseTables[i] = new int[sparseTables[0].length - size + 1]; for (int j = 0; j < sparseTables[i].length; j++) { sparseTables[i][j] = min(sparseTables[i - 1][j], sparseTables[i - 1][j + jumpSize]); } } } private int min(int a, int b) { return ((array[a] < array[b]) ^ reverseOrdered) ? a : b; } public Pair<Long, Long> queryIndexValueInRange(long l, long r) { int size = (int) (r - l + 1); int LCAIndex = IntegerExtension.getNumberOfBits(size) - 1; int sizeNeeded = 1 << LCAIndex; int res = min(sparseTables[LCAIndex][(int) l], sparseTables[LCAIndex][(int) (r - sizeNeeded + 1)]); return new Pair<>((long) res, array[res]); } public MinRangeSparseTable(long[] array) { this(array, false); } } static class GraphLowestCommonAncestor { public static GraphLowestCommonAncestor.LCA createLCA(int[] appearances, final int[] firstAppearance, final int[] depth) { return new GraphLowestCommonAncestor.LCA_MinRangeSparseTable(appearances, firstAppearance, depth); } public interface LCA { int getLCA(int a, int b); } private static class LCA_MinRangeSparseTable implements GraphLowestCommonAncestor.LCA { private final MinRangeSparseTable minRangeSparseTable; private final int[] firstAppearance; private final int[] indexToNode; public LCA_MinRangeSparseTable(int[] appearances, final int[] firstAppearance, final int[] depth) { this.firstAppearance = firstAppearance; this.indexToNode = appearances; long[] depthOrder = new long[appearances.length]; for (int i = 0; i < depthOrder.length; i++) { depthOrder[i] = depth[appearances[i]]; } minRangeSparseTable = new MinRangeSparseTable(depthOrder); } public int getLCA(int a, int b) { a = firstAppearance[a]; b = firstAppearance[b]; int l = Math.min(a, b), r = Math.max(a, b); return indexToNode[(int) (long) minRangeSparseTable.queryIndexValueInRange(l, r).first]; } } } static class InputReader { BufferedReader reader; 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(), " \t\n\r\f,"); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int NextInt() { return Integer.parseInt(next()); } public int[] NextIntArray(int n) { return NextIntArray(n, 0); } public int[] NextIntArray(int n, int offset) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = NextInt() + offset; } return a; } } static interface ISearchInRange { } static class Pair<T1, T2> { public T1 first; public T2 second; public Pair(T1 f, T2 s) { first = f; second = s; } } static class IntegerExtension { public static int getNumberOfBits(long i) { return 64 - Long.numberOfLeadingZeros(i); } } }
nlogn
1000_G. Two-Paths
CODEFORCES
import java.io.*; import java.lang.*; import java.util.*; public class alex { public static void main(String[] args)throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt();int sum=1; for(int i=1;i<=n;i++) { sum=sum+(4*(i-1)); } System.out.println(sum); } }
linear
1180_A. Alex and a Rhombus
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class TaskB implements Runnable { boolean prime[] = new boolean[(int)1e6+10]; InputReader c; PrintWriter w; public void run() { c = new InputReader(System.in); w = new PrintWriter(System.out); char a[] = c.next().toCharArray(), b[] = c.next().toCharArray(); int n = a.length, m = b.length; int[][] prefix = new int[m][2]; for(int i=0;i<m;i++){ if(i!=0) { prefix[i][0] = prefix[i-1][0]; prefix[i][1] = prefix[i-1][1]; } prefix[i][b[i] - '0']++; //w.println(prefix[i][0]+" "+prefix[i][1]); } long res = 0; for(int i=0;i<n;i++){ int temp = a[i] - '0'; res += prefix[m - n + i][temp^1]; if(i!=0) res -= prefix[i-1][temp^1]; } w.println(res); w.close(); } void sieveOfEratosthenes(int n) { for(int i=0;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*p; i <= n; i += p) prime[i] = false; } } } class pair implements Comparable<pair>{ char ch; int ind; @Override public String toString() { return "pair{" + "ch=" + ch + ", ind=" + ind + '}'; } public pair(char ch, int ind) { this.ch = ch; this.ind = ind; } public int compareTo(pair car) { if(this.ch==car.ch) return this.ind - car.ind; return this.ch - car.ch; } } 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])); } }); } static long gcd(long a, long b){ if (b == 0) return a; return gcd(b, a % b); } 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 TaskB(),"TaskB",1<<26).start(); } }
linear
608_B. Hamming Distance Sum
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class cf2 { static final double EPS = 1e-9; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); //rec int xr1=sc.nextInt(), yr1=sc.nextInt(), xr2=sc.nextInt(),yr2=sc.nextInt(); int xr3=sc.nextInt(), yr3=sc.nextInt(), xr4=sc.nextInt(),yr4=sc.nextInt(); Point pr1 = new Point(xr1, yr1); Point pr2 = new Point(xr2, yr2); Point pr3 = new Point(xr3, yr3); Point pr4 = new Point(xr4, yr4); LineSegment lr1 = new LineSegment(pr1, pr2); LineSegment lr2 = new LineSegment(pr2, pr3); LineSegment lr3 = new LineSegment(pr3, pr4); LineSegment lr4 = new LineSegment(pr4, pr1); //diamond int xd1=sc.nextInt(), yd1=sc.nextInt(), xd2=sc.nextInt(),yd2=sc.nextInt(); int xd3=sc.nextInt(), yd3=sc.nextInt(), xd4=sc.nextInt(),yd4=sc.nextInt(); Point p1 = new Point(xd1, yd1); Point p2 = new Point(xd2, yd2); Point p3 = new Point(xd3, yd3); Point p4 = new Point(xd4, yd4); Point [] pt = new Point [5]; pt[0]=p1; pt[1]=p2; pt[2]=p3; pt[3]=p4; pt[4]=p1; Polygon pg = new Polygon(pt); if(pg.inside(pr1)||pg.inside(pr2)||pg.inside(pr3)||pg.inside(pr4)) { System.out.println("YES"); return; } LineSegment ld1 = new LineSegment(p1, p2); LineSegment ld2 = new LineSegment(p2, p3); LineSegment ld3 = new LineSegment(p3, p4); LineSegment ld4 = new LineSegment(p4, p1); Rectangle rec = new Rectangle(new Point(Math.min(Math.min(xr3,xr4),Math.min(xr1,xr2)), Math.min(Math.min(yr3,yr4),Math.min(yr1,yr2))), new Point(Math.max(Math.max(xr3,xr4),Math.max(xr1,xr2)), Math.max(Math.max(yr3,yr4),Math.max(yr1,yr2))) ); if(rec.contains(p1)||rec.contains(p2)||rec.contains(p3)||rec.contains(p4)) { System.out.println("YES"); return; } if(ld1.intersect(lr1)||ld1.intersect(lr3)||ld1.intersect(lr3)||ld1.intersect(lr4)) { System.out.println("YES"); return; } if(ld2.intersect(lr1)||ld2.intersect(lr3)||ld2.intersect(lr3)||ld2.intersect(lr4)) { System.out.println("YES"); return; } if(ld3.intersect(lr1)||ld3.intersect(lr3)||ld3.intersect(lr3)||ld3.intersect(lr4)) { System.out.println("YES"); return; } if(ld4.intersect(lr1)||ld4.intersect(lr3)||ld4.intersect(lr3)||ld4.intersect(lr4)) { System.out.println("YES"); return; } System.out.println("NO"); } public static class Polygon { // Cases to handle: collinear points, polygons with n < 3 static final double EPS = 1e-9; Point[] g; //first point = last point, counter-clockwise representation Polygon(Point[] o) { g = o; } double perimeter() { double sum = 0.0; for(int i = 0; i < g.length - 1; ++i) sum += g[i].dist(g[i+1]); return sum; } double area() //clockwise/anti-clockwise check, for convex/concave polygons { double area = 0.0; for(int i = 0; i < g.length - 1; ++i) area += g[i].x * g[i+1].y - g[i].y * g[i+1].x; return Math.abs(area) / 2.0; //negative value in case of clockwise } boolean inside(Point p) //for convex/concave polygons - winding number algorithm { double sum = 0.0; for(int i = 0; i < g.length - 1; ++i) { double angle = Point.angle(g[i], p, g[i+1]); if((Math.abs(angle) < EPS || Math.abs(angle - Math.PI) < EPS) && p.between(g[i], g[i+1])) return true; if(Point.ccw(p, g[i], g[i+1])) sum += angle; else sum -= angle; } return Math.abs(2 * Math.PI - Math.abs(sum)) < EPS; //abs makes it work for clockwise } /* * Another way if the polygon is convex * 1. Triangulate the poylgon through p * 2. Check if sum areas == poygon area * 3. Handle empty polygon */ Point centroid() //center of mass { double cx = 0.0, cy = 0.0; for(int i = 0; i < g.length - 1; i++) { double x1 = g[i].x, y1 = g[i].y; double x2 = g[i+1].x, y2 = g[i+1].y; double f = x1 * y2 - x2 * y1; cx += (x1 + x2) * f; cy += (y1 + y2) * f; } double area = area(); //remove abs cx /= 6.0 * area; cy /= 6.0 * area; return new Point(cx, cy); } } static class LineSegment { Point p, q; LineSegment(Point a, Point b) { p = a; q = b; } boolean intersect(LineSegment ls) { Line l1 = new Line(p, q), l2 = new Line(ls.p, ls.q); if(l1.parallel(l2)) { if(l1.same(l2)) return p.between(ls.p, ls.q) || q.between(ls.p, ls.q) || ls.p.between(p, q) || ls.q.between(p, q); return false; } Point c = l1.intersect(l2); return c.between(p, q) && c.between(ls.p, ls.q); } } static class Rectangle { static final double EPS = 1e-9; Point ll, ur; Rectangle(Point a, Point b) { ll = a; ur = b; } double area() { return (ur.x - ll.x) * (ur.y - ll.y); } boolean contains(Point p) { return p.x <= ur.x + EPS && p.x + EPS >= ll.x && p.y <= ur.y + EPS && p.y + EPS >= ll.y; } Rectangle intersect(Rectangle r) { Point ll = new Point(Math.max(this.ll.x, r.ll.x), Math.max(this.ll.y, r.ll.y)); Point ur = new Point(Math.min(this.ur.x, r.ur.x), Math.min(this.ur.y, r.ur.y)); if(Math.abs(ur.x - ll.x) > EPS && Math.abs(ur.y - ll.y) > EPS && this.contains(ll) && this.contains(ur) && r.contains(ll) && r.contains(ur)) return new Rectangle(ll, ur); return null; } } static class Line { static final double INF = 1e9, EPS = 1e-9; double a, b, c; Line(Point p, Point q) { if(Math.abs(p.x - q.x) < EPS) { a = 1; b = 0; c = -p.x; } else { a = (p.y - q.y) / (q.x - p.x); b = 1.0; c = -(a * p.x + p.y); } } Line(Point p, double m) { a = -m; b = 1; c = -(a * p.x + p.y); } boolean parallel(Line l) { return Math.abs(a - l.a) < EPS && Math.abs(b - l.b) < EPS; } boolean same(Line l) { return parallel(l) && Math.abs(c - l.c) < EPS; } Point intersect(Line l) { if(parallel(l)) return null; double x = (b * l.c - c * l.b) / (a * l.b - b * l.a); double y; if(Math.abs(b) < EPS) y = -l.a * x - l.c; else y = -a * x - c; return new Point(x, y); } Point closestPoint(Point p) { if(Math.abs(b) < EPS) return new Point(-c, p.y); if(Math.abs(a) < EPS) return new Point(p.x, -c); return intersect(new Line(p, 1 / a)); } } public static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } //s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } } static class Point implements Comparable<Point>{ static final double EPS = 1e-9; double x, y; Point(double a, double b) { x = a; y = b; } public int compareTo(Point p) { if(Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if(Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) > 0; } public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } static double sq(double x) { return x * x; } Point rotate(double angle) { double c = Math.cos(angle), s = Math.sin(angle); return new Point(x * c - y * s, x * s + y * c); } // for integer points and rotation by 90 (counterclockwise) : swap x and y, negate x boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } //returns true if it is on the line defined by a and b //returns true if it is on the ray whose start point is a and passes through b // Another way: find closest point and calculate the distance between it and p } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public long nextlong() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); long res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
constant
994_C. Two Squares
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); 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); } System.out.println(Math.min(Math.min(rMin, gMin), bMin)); } } }
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.io.OutputStream; import java.util.List; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; /** * 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, FastReader in, PrintWriter out) { Debug debug = new Debug(); int n = in.nextInt(); int K = in.nextInt(); List<Integer>[] g = GraphUtils.nextU(in, n, n - 1, true); int[] center = GraphUtils.getCenter(g); if (center.length == 2) { out.println("No"); return; } int[][] pars = GraphUtils.parents3(g, center[0]); int[] par = pars[0], ord = pars[1], depth = pars[2]; int[] deg = new int[n]; for (int i = 0; i < n; ++i) deg[i] = g[i].size(); if (deg[center[0]] < 3) { out.println("No"); return; } // all leaves depth = K for (int i = 0; i < n; ++i) { if (deg[i] == 1) { if (depth[i] != K) { out.println("No"); return; } } else if (i != center[0]) { if (deg[i] < 4) { out.println("No"); return; } } } out.println("Yes"); } } static class GraphUtils { public static List<Integer>[] nextU(FastReader in, int n, int m, boolean oneIndexed) { int diff = oneIndexed ? 1 : 0; List<Integer>[] g = new List[n]; for (int i = 0; i < n; ++i) g[i] = new ArrayList<>(); for (int i = 0; i < m; ++i) { int u = in.nextInt() - diff; int v = in.nextInt() - diff; g[u].add(v); g[v].add(u); } return g; } public static int[][] parents3(List<Integer>[] g, int root) { int n = g.length; int[] par = new int[n]; ArrayUtils.fill(par, -1); int[] depth = new int[n]; depth[0] = 0; int[] q = new int[n]; q[0] = root; for (int p = 0, r = 1; p < r; p++) { int cur = q[p]; for (int nex : g[cur]) { if (par[cur] != nex) { q[r++] = nex; par[nex] = cur; depth[nex] = depth[cur] + 1; } } } return new int[][]{par, q, depth}; } public static int[] getCenter(List<Integer>[] g) { int n = g.length; int[] q = new int[n]; int[] deg = new int[n]; int p = 0; for (int i = 0; i < n; i++) { deg[i] = g[i].size(); if (g[i].size() <= 1) { // < for n=1 q[p++] = i; } } int bound = p == n ? 0 : p; for (int z = 0; z < p; z++) { if (bound == z && p < n) bound = p; int cur = q[z]; deg[cur]--; for (int e : g[cur]) { if (--deg[e] == 1) q[p++] = e; } } assert p == n; assert bound >= n - 2 && bound < n; if (bound == n - 2) { return new int[]{q[n - 2], q[n - 1]}; } else { return new int[]{q[n - 1]}; } } } 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; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class ArrayUtils { public static void fill(int[] array, int value) { Arrays.fill(array, value); } } static class Debug { PrintWriter out; boolean oj; boolean system; long timeBegin; Runtime runtime; public Debug(PrintWriter out) { oj = System.getProperty("ONLINE_JUDGE") != null; this.out = out; this.timeBegin = System.currentTimeMillis(); this.runtime = Runtime.getRuntime(); } public Debug() { system = true; oj = System.getProperty("ONLINE_JUDGE") != null; OutputStream outputStream = System.out; this.out = new PrintWriter(outputStream); this.timeBegin = System.currentTimeMillis(); this.runtime = Runtime.getRuntime(); } } }
linear
1067_B. Multihedgehog
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class AAA { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); String a=""; String b=""; for(int i=0;i<1129;i++) { a+="1"; b+="8"; } a+="9"; b+="1"; System.out.println(a); System.out.println(b); } }
constant
1028_B. Unnatural Conditions
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class B { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(bf.readLine()); StringTokenizer st = new StringTokenizer(bf.readLine()); Integer[] a = new Integer[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); Arrays.sort(a); int[] b = new int[n]; for(int i=0; i<n; i++) b[i] = a[i].intValue(); boolean diff = false; boolean diff2 = false; Set<Integer> vals = new HashSet<Integer>(); vals.add(b[0]); int valval = 0; for(int i=1; i<n; i++) { vals.add(b[i]); if(b[i] == b[i-1]) { if(!diff) { diff = true; valval = b[i]; } else diff2 = true; } } long sum = 0; for(int i : b) sum += i; sum -= 1L*n*(n-1)/2; if(diff && !diff2) { if(!vals.contains((valval-1)) && (valval > 0)) { if(sum%2 == 0) out.println("cslnb"); else out.println("sjfnb"); } else out.println("cslnb"); } else if(diff2) out.println("cslnb"); else if(sum%2 == 0) out.println("cslnb"); else out.println("sjfnb"); // int n = Integer.parseInt(st.nextToken()); out.close(); System.exit(0); } }
linear
1190_B. Tokitsukaze, CSL and Stone Game
CODEFORCES
//package ContestEd69; import java.io.*; import java.util.StringTokenizer; public class mainD { public static PrintWriter out = new PrintWriter(System.out); public static FastScanner enter = new FastScanner(System.in); public static long[] arr; public static void main(String[] args) throws IOException { int n=enter.nextInt(); int m=enter.nextInt(); long k=enter.nextLong(); arr=new long[n+1]; for (int i = 1; i <n+1 ; i++) { arr[i]=enter.nextLong(); } long[] summ=new long[n+1]; for (int i = 1; i <n+1 ; i++) { summ[i]+=arr[i]+summ[i-1]; } long[] best=new long[n+1]; for (int i = 1; i <n+1 ; i++) { best[i]=Math.max(0, ((i-m>=0) ? best[i-m]+summ[i]-summ[i-m]-k:0)); } long ans=best[1]; for (int i = 1; i <n+1 ; i++) { ans=Math.max(ans,best[i]); for (int j = 1; j <m ; j++) { ans=Math.max(ans, ((i-j>=0) ? best[i-j] -k +summ[i]-summ[i-j]:0)); } } System.out.println(ans); } static class FastScanner { BufferedReader br; StringTokenizer stok; FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } char nextChar() throws IOException { return (char) (br.read()); } String nextLine() throws IOException { return br.readLine(); } } }
quadratic
1197_D. Yet Another Subarray Problem
CODEFORCES
import java.util.*; import java.lang.*; public class Main { static long m = 1000000007; static long powmod(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; } static long mulmod(long a, long b, long mod){ long res=0; a = a % mod; while (b > 0) { // If b is odd, add 'a' to result if (b % 2 == 1) res = (res + a) % mod; // Multiply 'a' with 2 a = (a * 2) % mod; // Divide b by 2 b /= 2; } // Return result return res % mod; } public static void main(String args[] ) throws Exception { Scanner sc = new Scanner(System.in); long x = sc.nextLong(); long k = sc.nextLong(); if(x>0) { long d= powmod(2,k,m); long ans= mulmod(d,2,m)%m; ans= mulmod(ans,x,m)%m; ans++; ans%=m; ans= (ans-d+m)%m; System.out.println(ans); } else System.out.println(0); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; import java.util.Map.*; public class codeforces { static int count =0; static boolean f=false; static int [] arr; static PrintWriter pw=new PrintWriter(System.out); static void solve(int index , int mask) { if(index==arr.length) { int sum1=0; int sum2=0; for(int i=0;i<arr.length;i++) { if((mask & 1<<i)!=0) sum1+=arr[i]; } return; } solve(index+1, mask | 1<<index); solve(index+1, mask); } public static void main(String [] args) throws IOException, InterruptedException { Scanner sc=new Scanner(System.in); int x=sc.nextInt(); int y=sc.nextInt(); pair [] arr=new pair[x]; for(int i=0;i<x;i++) arr[i]=new pair(i, sc.nextInt(),0); for(int i=0;i<x;i++) arr[i].y=sc.nextInt(); Arrays.sort(arr); PriorityQueue<Integer> qq=new PriorityQueue<>(); //pw.println(Arrays.toString(arr)); Long [] list=new Long [x]; long sum=0; for(int i=0;i<x;i++) { pair w=arr[i]; if(qq.size()<y) { qq.add(w.y); sum+=w.y; list[w.i]=sum; }else if(!qq.isEmpty()) { sum+=w.y; list[w.i]=sum; int first=qq.poll(); if(w.y>first) { sum-=first; qq.add(w.y); }else { qq.add(first); sum-=w.y; } } else list[w.i]=(long) w.y; //pw.println(qq); } for(Long w:list) pw.print(w+" "); pw.flush(); pw.close(); } static class pair implements Comparable<pair>{ String name; int x,y,i ; public pair(String name , int x) { this.name=name; this.x=x; } public pair (int i,int x,int y) { this.i=i; this.x=x; this.y=y; } public int compareTo(pair o) { return x-o.x; } public int compareTo1(pair o) { if(!name.equals(o.name)) return name.compareTo(o.name); return x-o.x; } public String toString() { return i+" "+x+" "+y; } } 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); } } }
nlogn
994_B. Knights of a Polygonal Table
CODEFORCES
import java.io.*; import java.util.*; public class Codeforces913F { public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); int n = input.nextInt(); int a = input.nextInt(); int b = input.nextInt(); input.close(); final int mod = 998244353; int frac = multiply(a, inverse(b, mod), mod); int reverse = (mod+1-frac)%mod; int[] fracpower = new int[n+1]; int[] reversepower = new int[n+1]; fracpower[0] = 1; reversepower[0] = 1; for (int i = 1; i <= n; i++) { fracpower[i] = multiply(fracpower[i-1], frac, mod); reversepower[i] = multiply(reversepower[i-1], reverse, mod); } int[][] dp1 = new int[n+1][n+1]; dp1[2][1] = 1; for (int i = 3; i <= n; i++) { for (int j = 1; j < i; j++) { if (j == 1) { dp1[i][j] = fracpower[i-1]; } else { dp1[i][j] = multiply(dp1[i-1][j-1], fracpower[i-j], mod); } if (j == i-1) { dp1[i][j] += reversepower[i-1]; dp1[i][j] %= mod; } else { dp1[i][j] += multiply(dp1[i-1][j], reversepower[j], mod); dp1[i][j] %= mod; } } } int[][] dp2 = new int[n+1][n+1]; dp2[1][1] = 1; dp2[2][1] = 1; dp2[2][2] = 0; for (int i = 3; i <= n; i++) { int val = 0; for (int j = 1; j < i; j++) { dp2[i][j] = multiply(dp2[j][j], dp1[i][j], mod); val += dp2[i][j]; val %= mod; } dp2[i][i] = (mod+1-val)%mod; } /*for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print(dp2[i][j] + " "); } System.out.println(); }*/ int[] EV = new int[n+1]; EV[1] = 0; EV[2] = 1; for (int i = 3; i <= n; i++) { int val = 0; for (int j = 1; j < i; j++) { int r = j*(i-j) + (j*(j-1))/2 + EV[i-j] + EV[j]; r %= mod; val += multiply(dp2[i][j], r, mod); val %= mod; } val += multiply((i*(i-1))/2, dp2[i][i], mod); val %= mod; int s = (mod+1-dp2[i][i])%mod; EV[i] = multiply(val, inverse(s, mod), mod); } System.out.println(EV[n]); } public static int multiply(int a, int b, int mod) { long x = (long)a*(long)b; return (int) (x%mod); } public static int inverse (int a, int n) { int m = n; int r1 = 1; int r2 = 0; int r3 = 0; int r4 = 1; while ((a > 0) && (n > 0)) { if (n >= a) { r3 -= r1*(n/a); r4 -= r2*(n/a); n = n%a; } else { int tmp = a; a = n; n = tmp; tmp = r1; r1 = r3; r3 = tmp; tmp = r2; r2 = r4; r4 = tmp; } } if (a == 0) { if (r3 >= 0) return (r3%m); else return (m+(r3%m)); } else { if (r1 >= 0) return (r1%m); else return (m+(r1%m)); } } }
quadratic
913_F. Strongly Connected Tournament
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().go(); } PrintWriter out; Reader in; BufferedReader br; Main() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); //in = new Reader("input.txt"); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws Exception { //int t = in.nextInt(); int t = 1; while (t > 0) { solve(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; ArrayList<Pair>[] g; String s; int[][] a; void solve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); a = new int[n][m]; for (int i = 0; i < n; i++) { String s = in.nextLine(); for (int j = 0; j < m; j++) { a[i][j] = s.charAt(j); } } int[][] f = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) f[i][j] = inf; for (int i = 0; i < n; i++) { int cnt = 0; for (int j = 0; j < m; j++) { if (a[i][j] == '*') { f[i][j] = Math.min(f[i][j], cnt); cnt++; } else { cnt = 0; } } } for (int i = 0; i < n; i++) { int cnt = 0; for (int j = m - 1; j >= 0; j--) { if (a[i][j] == '*') { f[i][j] = Math.min(f[i][j], cnt); cnt++; } else { cnt = 0; } } } for (int j = 0; j < m; j++) { int cnt = 0; for (int i = 0; i < n; i++) { if (a[i][j] == '*') { f[i][j] = Math.min(f[i][j], cnt); cnt++; } else { cnt = 0; } } } for (int j = 0; j < m; j++) { int cnt = 0; for (int i = n - 1; i >= 0; i--) { if (a[i][j] == '*') { f[i][j] = Math.min(f[i][j], cnt); cnt++; } else { cnt = 0; } } } ArrayList<Item> ans = new ArrayList<>(); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (a[i][j] == '*' && f[i][j] > 0) ans.add(new Item(i + 1, j + 1, f[i][j])); } boolean[][] used = new boolean[n][m]; for (int i = 0; i < n; i++) { int cnt = 0; for (int j = 0; j < m; j++) { if (a[i][j] == '*' && f[i][j] > 0) { cnt = Math.max(cnt, f[i][j] + 1); } if (cnt > 0) used[i][j] = true; cnt--; } cnt = 0; for (int j = m - 1; j >= 0; j--) { if (a[i][j] == '*' && f[i][j] > 0) { cnt = Math.max(cnt, f[i][j] + 1); } if (cnt > 0) used[i][j] = true; cnt--; } } for (int j = 0; j < m; j++) { int cnt = 0; for (int i = 0; i < n; i++) { if (a[i][j] == '*' && f[i][j] > 0) { cnt = Math.max(cnt, f[i][j] + 1); } if (cnt > 0) used[i][j] = true; cnt--; } cnt = 0; for (int i = n - 1; i >= 0; i--) { if (a[i][j] == '*' && f[i][j] > 0) { cnt = Math.max(cnt, f[i][j] + 1); } if (cnt > 0) used[i][j] = true; cnt--; } } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] == '*' && !used[i][j]) { out.println(-1); return; } out.println(ans.size()); for (Item i : ans) out.println(i.a + " " + i.b + " " + i.c); } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a != p.a) return Integer.compare(a, p.a); else return Integer.compare(b, p.b); } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } static class InputReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public InputReader(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]; // line length 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(); } } }
quadratic
1015_E2. Stars Drawing (Hard Edition)
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Solution{ 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[] a = new int[n]; for(int i=0;i<n;i++) a[i] = Integer.parseInt(st.nextToken()); int ind = 0; for(int i=0;i<n;i++){ if(a[i]==n){ ind = i; break; } } boolean ok = true; for(int i=ind+1;i<n;i++) if(a[i]>a[i-1]) ok = false; for(int i=ind-1;i>=0;i--) if(a[i]>a[i+1]) ok = false; if(ok) System.out.println("YES"); else System.out.println("NO"); } }
linear
1197_B. Pillars
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solve4 { public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int x= sc.nextInt(); int y= sc.nextInt(); int z= sc.nextInt(); int t1= sc.nextInt(); int t2= sc.nextInt(); int t3= sc.nextInt(); if(Math.abs(x-y)*t1 < (Math.abs(x-z)+Math.abs(x-y))*t2+3*t3 ) System.out.println("NO"); else System.out.println("YES"); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } 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()); } public String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException ex) { } return s; } } }
constant
1054_A. Elevator or Stairs?
CODEFORCES
import java.util.Scanner; public class codef8 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int beacon[] = new int[1000001]; int pos[] = new int[num]; for (int i = 0; i < num; i++) { int position = sc.nextInt(); beacon[position] = sc.nextInt(); pos[i] = position; } int dp[] = new int[1000001]; int max = 0; if (beacon[0] != 0) dp[0] = 1; for (int i = 1; i <= 1000000; i++) { if (beacon[i] == 0) { dp[i] = dp[i-1]; } else { int j = i - beacon[i] - 1; if (j < 0) { dp[i] = 1; } else { dp[i] = dp[j] + 1; } } max = Math.max(max, dp[i]); } System.out.println(num-max); } }
linear
608_C. Chain Reaction
CODEFORCES
import java.io.*; public class coins { public static void main(String args[])throws IOException { InputStreamReader read=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(read); int i,k,n,v; String a; a=in.readLine(); for(i=0;i<a.length();i++) { if(a.charAt(i)==' ') break; } n=Integer.parseInt(a.substring(0,i)); v=Integer.parseInt(a.substring(i+1)); k=v%n; v=v/n; if(k>0) v++; System.out.println(v); } }
constant
1061_A. Coins
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.*; public class p7{ 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()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc = new FastReader(); //PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); long one = (long)Math.pow(2, k) - 1; long[] arr = new long[n+1]; arr[0] = 0; for(int i=1;i<=n;i++){ arr[i] = sc.nextLong(); arr[i] ^= arr[i-1]; } Map<Long, Long> count = new HashMap<>(); for(int i=0;i<=n;i++){ Long key = Math.min(arr[i], (arr[i]^one)); Long val = count.get(key); if(val==null) val = 0L; count.put(key, val+1); } long num = n; long ans = num*(num+1)/2; for(Map.Entry<Long, Long> ent: count.entrySet()){ Long cnt = ent.getValue(); long num1 = cnt/2; long num2 = (cnt+1)/2; ans -= ( (num1*(num1-1))/2 ); ans -= ( (num2*(num2-1))/2 ); } System.out.println(ans); } }
nlogn
1054_D. Changing Array
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.util.Scanner; public class FUck { public static void main(String args[]) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int k=scan.nextInt(); String t=scan.next(); int mx=0; for(int i=1;i<n;i++) { int gd=1; for(int j=0;j<i;j++) { if(t.charAt(j)!=t.charAt((n-i)+j)) { gd=0; // i think i can break here } } if(gd==1){ mx=i; } } System.out.print(t); for(int i=2;i<=k;i++) { for(int j=mx;j<n;j++) { System.out.print(t.charAt(j)); } } } }
quadratic
1029_A. Many Equal Substrings
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(" "); String s2[]=br.readLine().split(" "); int n=Integer.parseInt(s1[0]); int m=Integer.parseInt(s1[1]); int a[]=new int[n]; int b[]=new int[n]; int c[]=new int[n]; int d[]=new int[n]; HashSet<Integer> hs=new HashSet<Integer>(); hs.add(0); hs.add(m); int max=0; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(s2[i]); if(i%2==0) b[i]=1; hs.add(a[i]); } c[0]=a[0]; for(int i=1;i<n;i++) { if(b[i]==0) c[i]=c[i-1]; else c[i]=c[i-1]+a[i]-a[i-1]; } if(b[n-1]==0) d[n-1]=m-a[n-1]; for(int i=n-2;i>=0;i--) { if(b[i]==1) d[i]=d[i+1]; else d[i]=d[i+1]+a[i+1]-a[i]; } max=c[n-1]; if(b[n-1]==0) max+=m-a[n-1]; //System.out.println(max); for(int i=n-1;i>=0;i--) { int u=a[i]-1; int v=a[i]+1; if(!hs.contains(u)) { if(b[i]==0) { int r=1+m-a[i]-d[i]+c[i-1]; max=Math.max(max,r); } else { int l=0; if(i>0) l=a[i-1]; int r=c[i]-1+m-a[i]-d[i]; max=Math.max(max,r); } } if(!hs.contains(v)) { if(b[i]==0) { if(i==n-1) { int r=c[i]+1; max=Math.max(max,r); } else { int r=c[i]+1+m-a[i+1]-d[i+1]; max=Math.max(max,r); } } else { if(i==n-1) { int r=c[i]+m-a[i]-1; max=Math.max(max,r); } else { int r=c[i]+m-a[i+1]-d[i+1]+a[i+1]-1-a[i]; max=Math.max(max,r); } } } } System.out.println(max); } }
linear
1000_B. Light It Up
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner in =new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = in.nextInt(); for(int i = n-1; i > 0; i--) arr[i] -= arr[i-1]; arr[0] = 0; Arrays.sort(arr); long sum = 0; for(int i = n-k; i >= 0; i--) sum += arr[i]; System.out.println(sum); } }
nlogn
1197_C. Array Splitting
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; /* spar5h */ public class cf1 implements Runnable{ public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int t = 1; while(t-- > 0) { int n = s.nextInt(), m = s.nextInt(); int[] a = new int[n + 1]; for(int i = 1; i <= n; i++) a[i] = s.nextInt(); int[] b = new int[n + 1]; for(int i = 1; i <= n; i++) b[i] = s.nextInt(); ArrayList<Integer> list = new ArrayList<Integer>(); list.add(a[1]); for(int i = 2; i <= n; i++) { list.add(b[i]); list.add(a[i]); } list.add(b[1]); double wt = m; boolean check = true; for(int i = list.size() - 1; i >= 0; i--) { if(list.get(i) <= 1) { check = false; break; } double x = wt / (list.get(i) - 1); wt += x; } if(check) w.println(wt - m); else w.println(-1); } w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private 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 String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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 cf1(),"cf1",1<<26).start(); } }
linear
1010_A. Fly
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; import java.util.stream.IntStream; public class B { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); Solver solver = new Solver(); solver.solve(in, out); out.close(); } static class Solver { int n; int n2; InputReader in; PrintWriter out; public void solve(InputReader in, PrintWriter out) { this.in = in; this.out = out; n = in.readInt(); n2 = n/2; int res = find(); out.print("! "); out.println(res); } public int find() { if (n%4 != 0) return -1; int c = compare(0); if (c == 0) return 1; int s = 1; int f = n2-1; if (c > 0) { s = n2+1; f = n-1; } while (s <= f) { int m = (s+f)/2; int v = compare(m); if (v == 0) return m+1; else if (v < 0) s = m+1; else f = m-1; } return -1; } public int compare(int z) { out.print("? "); out.println(z+1); out.flush(); int r1 = in.readInt(); out.print("? "); out.println((z+n2)%n+1); out.flush(); int r2 = in.readInt(); return r1-r2; } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { this.reader = new BufferedReader(new InputStreamReader(stream)); } public String read() { try { if (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException ex) { throw new RuntimeException(ex); } return tokenizer.nextToken(); } public int readInt() { return Integer.parseInt(read()); } public long readLong() { return Long.parseLong(read()); } public void readIntArrays(int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } } }
logn
1019_B. The hat
CODEFORCES
import java.util.*; import java.math.*; public class Solution{ private long [] sums; private void solve(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int [] arr = new int[n]; this.sums = new long[n]; for(int i = 0; i < n; i++){ arr[i] = sc.nextInt(); sums[i] = arr[i] + (i == 0 ? 0 : sums[i - 1]); } long ans = 0; for(int i = 1; i <= n && i <= m; i++){ ans = Math.max(ans, sum(0, i - 1) - k); } long [] dp = new long[n]; for(int i = 0; i < n; i++){ if(i + 1 >= m){ long cur = sum(i - m + 1, i) - k; if(i - m >= 0){ cur += dp[i - m]; } dp[i] = Math.max(dp[i], cur); } for(int j = 0; j <= m && i + j < n; j++){ ans = Math.max(ans, dp[i] + sum(i + 1, i + j) - k * (j > 0 ? 1 : 0)); } } System.out.println(ans); } private long sum(int l, int r){ if(l <= 0){ return sums[r]; }else{ return sums[r] - sums[l - 1]; } } public static void main(String [] args){ new Solution().solve(); } }
quadratic
1197_D. Yet Another Subarray Problem
CODEFORCES
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); long totalBlocks = 0; long a[] = new long[n]; for(int i = 0; i < n; ++i) { a[i] = sc.nextLong(); totalBlocks += a[i]; } Arrays.sort(a); long selected = 0; for(int i = 0; i < n; ++i) { if(a[i] > selected) selected++; } long leftCols = a[n - 1] - selected; long remBlocks = totalBlocks - leftCols - n; System.out.print(remBlocks); } }
nlogn
1061_B. Views Matter
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. */ import java.util.ArrayList; import java.util.Scanner; /** * * @author Ahmed */ public class Watermelon { static class Passengers { public int floor ; public int time; public Passengers( int floor , int time){ this.floor =floor; this.time =time; } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner in = new Scanner(System.in); int x = in.nextInt() , y = in.nextInt(); ArrayList<Passengers> list = new ArrayList<>(); for(int i = 1 ; i <= x ; ++i){ list.add(new Passengers(in.nextInt(), in.nextInt())); } int sum = 0 ; for(int i = list.size() - 1 ; i >= 0 ; --i) { int s = y - list.get(i).floor; sum = sum + s ; if(sum < list.get(i).time) { sum = sum + ( list.get(i).time - sum); } y = list.get(i).floor; } if( list.get(list.size() - 1).floor != 0){ sum = sum + (list.get(0).floor); } System.out.println(sum); } }
linear
608_A. Saitama Destroys Hotel
CODEFORCES
import java.util.*; import java.io.*; public class MinimumDiameterTree{ public static void main(String[] args) { InputReader in = new InputReader (System.in); PrintWriter out = new PrintWriter (System.out); int n = in.nextInt(); int s = in.nextInt(); int deg[] = new int [n]; for (int i = 1; i < n; ++i) { deg[in.nextInt() - 1] ++; deg[in.nextInt() - 1] ++; } int l = 0; for (int i = 0; i < n; ++i) if (deg[i] == 1) l ++; out.println((double) 2 * s / l); out.close(); } public static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch(IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
linear
1086_B. Minimum Diameter Tree
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author Antonio "Teo" Alurralde */ 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()); StringTokenizer tok = new StringTokenizer(br.readLine()); int ax = Integer.parseInt(tok.nextToken()); int ay = Integer.parseInt(tok.nextToken()); tok = new StringTokenizer(br.readLine()); int bx = Integer.parseInt(tok.nextToken()); int by = Integer.parseInt(tok.nextToken()); tok = new StringTokenizer(br.readLine()); int cx = Integer.parseInt(tok.nextToken()); int cy = Integer.parseInt(tok.nextToken()); boolean ans = (bx < ax && cx < ax && by < ay && cy < ay) || (bx < ax && cx < ax && by > ay && cy > ay) || (bx > ax && cx > ax && by < ay && cy < ay) || (bx > ax && cx > ax && by > ay && cy > ay); System.out.print(ans?"YES":"NO"); } }
constant
1033_A. King Escape
CODEFORCES
/** * Created by Aminul on 3/14/2019. */ import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import static java.lang.Math.max; public class E_2 { public static void main(String[] args) throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(), k = in.nextInt(), N = (int) 5e6 + 1; int left = 0, right = 0; int a[] = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); if (a[i] == k) left++; } int f[] = new int[N + 1]; int ans = 0; for (int i = n; i >= 1; i--) { if (a[i] == k) left--; f[a[i]]++; f[a[i]] = max(f[a[i]], 1 + right); ans = max(ans, f[a[i]] + left); if (a[i] == k) right++; } pw.println(ans); pw.close(); } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class FastReader { InputStream is; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; public FastReader(InputStream is) { this.is = is; } public int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } public int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = (num << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } } }
linear
1082_E. Increasing Frequency
CODEFORCES
import java.util.Scanner; public class TreasureHunt { public static String Solve() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); String kuro = sc.nextLine(), shiro = sc.nextLine(), katie = sc.nextLine(); sc.close(); String[] output = {"Kuro", "Shiro", "Katie", "Draw"}; if(n >= kuro.length()) return output[3]; int[] maxArr = new int[3]; int[][] freq = new int[3][58]; for(int i = 0; i < kuro.length(); i++) { maxArr[0] = ++freq[0][kuro.charAt(i) - 65] > maxArr[0]? freq[0][kuro.charAt(i) - 65] : maxArr[0]; maxArr[1] = ++freq[1][shiro.charAt(i) - 65] > maxArr[1]? freq[1][shiro.charAt(i) - 65] : maxArr[1]; maxArr[2] = ++freq[2][katie.charAt(i) - 65] > maxArr[2]? freq[2][katie.charAt(i) - 65] : maxArr[2]; } int winner = 0, max = 0; for(int i = 0; i < 3; i++) { if(kuro.length() - maxArr[i] >= n) maxArr[i] += n; else maxArr[i] = n == 1? kuro.length() - 1: kuro.length(); if(max < maxArr[i]) { winner = i; max = maxArr[i]; } else if(max == maxArr[i]) winner = 3; } return output[winner]; } public static void main(String[] args) { System.out.println(Solve()); } }
linear
979_B. Treasure Hunt
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CF1197B { public static void main(String[] args) { FastReader input = new FastReader(); int n = input.nextInt(); int[] arr = new int[n]; int max = 0; int maxIndex = 0; for(int i = 0;i < n;i++){ arr[i] = input.nextInt(); if(arr[i] > max){ max = arr[i]; maxIndex = i; } } int j = maxIndex - 1; int k = maxIndex + 1; while (j >= 0 && k < n){ if(arr[j] > arr[k]){ if(arr[j] < max){ max = arr[j]; j--; } else { System.out.println("NO"); return; } } else{ if(arr[k] < max){ max = arr[k]; k++; } else{ System.out.println("NO"); return; } } } if(j >= 0){ while (j >= 0){ if(arr[j] < max){ max = arr[j]; j--; } else{ System.out.println("NO"); return; } } } if(k < n){ while (k < n){ if(arr[k] < max){ max = arr[k]; k++; } else{ System.out.println("NO"); return; } } } if(j == -1 && k == n){ System.out.println("YES"); } } 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()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
linear
1197_B. Pillars
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; 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 * * @author programajor */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { BigInteger mod = new BigInteger("1000000007"); public void solve(int testNumber, InputReader in, PrintWriter out) { BigInteger x = new BigInteger(in.next()); BigInteger k = new BigInteger(in.next()); if (x.longValue() == 0) { out.print(x); return; } BigInteger pow = powerWithMod(new BigInteger("2"), k); BigInteger current = x.mod(mod).multiply(pow).mod(mod); BigInteger result = current.multiply(new BigInteger("2")).mod(mod) .subtract(pow.subtract(new BigInteger("1")).mod(mod)) .mod(mod); out.print(result); } BigInteger powerWithMod(BigInteger base, BigInteger exponent) { if (exponent.longValue() == 0) { return new BigInteger("1"); } BigInteger temp = powerWithMod(base, exponent.divide(new BigInteger("2"))); BigInteger term = temp.mod(mod); if (exponent.mod(new BigInteger("2")).intValue() == 0) { return term.multiply(term.mod(mod)).mod(mod); } else { return term.multiply(term.mod(mod)).multiply(base.mod(mod)).mod(mod); } } } static class InputReader { private BufferedReader reader; private 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(); } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; // author @mdazmat9 public class codeforces{ public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int test = 1; for (int ind = 0; ind < test; ind++) { int [] a=new int[3]; a[0]=sc.nextInt(); a[1]=sc.nextInt(); a[2]=sc.nextInt(); Arrays.sort(a); int k1=a[0]; int k2=a[1]; int k3=a[2]; if(k1==1 || k2==1 || k3==1){ out.println("YES"); } else if((k1==2 && k2==2)||(k2==2 && k3==2)){ out.println("YES"); } else if(k1==3 && k2==3 && k3==3){ out.println("YES"); } else if(k1==2 && k2==4 && k3==4){ out.println("YES"); } else out.println("NO"); } out.flush(); } 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; } } static long gcd(long a , long b) { if(b == 0) return a; return gcd(b , a % b); } } class Scanner { public BufferedReader reader; public StringTokenizer st; public Scanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) return null; st = new StringTokenizer(line); } catch (Exception e) { throw (new RuntimeException()); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } class OutputWriter { BufferedWriter writer; public OutputWriter(OutputStream stream) { writer = new BufferedWriter(new OutputStreamWriter(stream)); } public void print(int i) throws IOException { writer.write(i); } public void print(String s) throws IOException { writer.write(s); } public void print(char[] c) throws IOException { writer.write(c); } public void close() throws IOException { writer.close(); } }
constant
911_C. Three Garlands
CODEFORCES
import java.io.*; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static long oo = 1000000000000L; public static void main(String[] args) throws IOException { int n = in.nextInt(); int q = in.nextInt(); ArrayDeque<Integer> dq = new ArrayDeque<>(); int max = -1; for(int i = 0; i < n; ++i) { int x = in.nextInt(); dq.add(x); max = Math.max(max, x); } ArrayList<Pair> ans = new ArrayList<>(); while(dq.peekFirst() != max) { int a = dq.pollFirst(); int b = dq.pollFirst(); ans.add(new Pair(a, b)); if(a > b) { dq.addFirst(a); dq.addLast(b); } else { dq.addFirst(b); dq.addLast(a); } } ArrayList<Integer> a = new ArrayList<>(); dq.pollFirst(); for(int x : dq) a.add(x); while(q --> 0) { long m = in.nextLong() - 1; if(m < ans.size()) { System.out.println(ans.get((int)m).first + " " + ans.get((int)m).second); } else { int idx = (int)((m - ans.size()) % a.size()); System.out.println(max + " " + a.get(idx)); } } out.close(); } static long lcm(long a, long b) { return a * b / gcd(a, b); } static boolean nextPermutation(int[] a) { for(int i = a.length - 2; i >= 0; --i) { if(a[i] < a[i+1]) { for(int j = a.length - 1; ; --j) { if(a[i] < a[j]) { int t = a[i]; a[i] = a[j]; a[j] = t; for(i++, j = a.length - 1; i < j; ++i, --j) { t = a[i]; a[i] = a[j]; a[j] = t; } return true; } } } } return false; } static void shuffle(int[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); int t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(long[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); long t = a[si]; a[si] = a[i]; a[i] = t; } } static int lower_bound(int[] a, int n, int k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int lower_bound(long[] a, int n, long k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return this.first != o.first ? this.first - o.first : this.second - o.second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { 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 = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { 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 { res *= 10; res += c - '0'; c = read(); } 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 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 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
linear
1180_C. Valeriy and Deque
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class AAA { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); String a=""; String b=""; for(int i=0;i<1129;i++) { a+="1"; b+="8"; } a+="9"; b+="1"; System.out.println(a); System.out.println(b); } }
constant
1028_B. Unnatural Conditions
CODEFORCES
import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.*; public class E1180D { public static void main(String args[]) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); // Move from both ends, Time limit exceeded on test 6 for (int i= 1; i<= m/2; i++) { // String s = ""; int i2 = m -i + 1; // the other end of i // i is left row, i2 is right row for (int j = 1; j <= n ; j++) { int j2 = n - j + 1; // start with (i,j), then go thru all the cell with (,i) and (,i2) pw.println(j + " " + i); pw.println(j2+ " " + i2); // s += j + " " + i + "\n" + j2+ " " + i2 + "\n"; } // out.print(s); } // if n is odd, there is one line in the middle if (m % 2 == 1) { int i2 = m /2 + 1; // this is the middle column for (int j = 1; j <= n/2 ; j++) { int j2 = n - j + 1; // start with (i,j), then go thru all the cell with (,i) and (,i2) pw.println(j + " " + i2); pw.println(j2+ " " + i2); } if (n %2 == 1) { int j = n /2 + 1; pw.println(j + " " + i2); } } pw.flush(); pw.close(); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class C { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); // Scanner scan = new Scanner(System.in); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(bf.readLine()); int counter = 0; for(int i=0; i<2*n/3; i++) System.out.println("0 " + i); for(int i=0; i<n-2*n/3; i++) System.out.println("3 " + (2*i+1)); } }
linear
1067_C. Knights
CODEFORCES
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); long totalBlocks = 0; long a[] = new long[n]; for(int i = 0; i < n; ++i) { a[i] = sc.nextLong(); totalBlocks += a[i]; } Arrays.sort(a); long selected = 0; for(int i = 0; i < n; ++i) { if(a[i] > selected) selected++; } long leftCols = a[n - 1] - selected; long remBlocks = totalBlocks - leftCols - n; System.out.print(remBlocks); } }
nlogn
1061_B. Views Matter
CODEFORCES
import java.util.Scanner; public class codef8 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int beacon[] = new int[1000001]; int pos[] = new int[num]; for (int i = 0; i < num; i++) { int position = sc.nextInt(); beacon[position] = sc.nextInt(); pos[i] = position; } int dp[] = new int[1000001]; int max = 1; if (beacon[0] != 0) dp[0] = 1; for (int i = 1; i <= 1000000; i++) { if (beacon[i] == 0) { dp[i] = dp[i-1]; } else { int j = i - beacon[i] - 1; if (j < 0) { dp[i] = 1; } else { dp[i] = dp[j] + 1; } } max = Math.max(max, dp[i]); } System.out.println(num-max); } }
linear
608_C. Chain Reaction
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; 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; 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) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int inv = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (a[j] > a[i]) { inv++; } } } int m = in.nextInt(); for (int i = 0; i < m; i++) { int l = in.nextInt(); int r = in.nextInt(); int s = (r - l + 1) * (r - l) / 2; inv = (inv + s) % 2; out.println(inv % 2 == 0 ? "even" : "odd"); } } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import com.sun.org.apache.xpath.internal.operations.Bool; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { MyScanner scan = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = scan.nextInt(); int[] vals = new int[n]; for (int i = 0; i < n; i++) { vals[i] = scan.nextInt(); } for (int i = 0; i < n; i++) { if (solve(i, vals)) { out.print('A'); } else { out.print('B'); } } out.close(); } static HashMap<Integer, Boolean> dpResult = new HashMap<>(); private static boolean solve(int pos, int[] vals) { if (dpResult.containsKey(pos)) return dpResult.get(pos); int val = vals[pos]; boolean hasLose = false; for (int i = pos; i < vals.length; i += val) { if (i == pos) continue; if (vals[i] <= vals[pos]) continue; if (hasLose) break; if (!solve(i, vals)) { hasLose = true; } } for (int i = pos; i >= 0; i -= val) { if (i == pos) continue; if (vals[i] <= vals[pos]) continue; if (hasLose) break; if (!solve(i, vals)) { hasLose = true; } } dpResult.put(pos, hasLose); return hasLose; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { 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; } } //-------------------------------------------------------- }
nlogn
1033_C. Permutation Game
CODEFORCES
import java.io.*; import java.util.*; public class Main { public void solve() { int n = ni(); int a = ni(); int b = ni(); long ans = 0; HashMap<Long, Long> m = new HashMap<>(); HashMap<String, Long> s = new HashMap<>(); for (int i = 0; i < n; i++) { ni(); long vx = ni(); long vy = ni(); long v = (long) a * vx - vy; String k = vx + "|" + vy; long cs = s.getOrDefault(k, 0L); long c = m.getOrDefault(v, 0L); ans += c - cs; m.put(v, c + 1); s.put(k, cs + 1); } write (ans * 2 + "\n"); } public static void main(String[] args) { Main m = new Main(); m.solve(); try { m.out.close(); } catch (IOException e) {} } BufferedReader in; BufferedWriter out; StringTokenizer tokenizer; public Main() { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); } public String n() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException e) {} } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(n()); } public long nl() { return Long.parseLong(n()); } public void write(String s) { try { out.write(s); } catch (IOException e) {} } }
linear
975_D. Ghosts
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class pr1073B { 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()); int[] a = new int[n]; int[] b = new int[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { b[i] = Integer.parseInt(st.nextToken()); } solve(n, a, b, out); out.flush(); out.close(); } private static void solve(int n, int[] a, int[] b, PrintWriter out) { boolean[] book = new boolean[n+1]; boolean f; int j1 = 0, j2 = 0; for (int i = 0; i < n; i++) { f = false; int num = b[i]; if(!book[num]) { f = true; j1 = j2; for (;j2 < n; j2++) { book[a[j2]] = true; if (a[j2] == num) { j2++; break; } } } out.print(f ? j2-j1 + " ": 0 + " "); } } }
linear
1073_B. Vasya and Books
CODEFORCES
import java.io.*; import java.util.*; public class LectureSleep { static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } 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 float nextFloat() { return Float.parseFloat(next()); } } static InputReader r = new InputReader(System.in); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) { int n = r.nextInt(); // duration of lecture int k = r.nextInt(); // number of minutes keep mishka awake int[] theorems = new int[n+1]; for(int i = 1; i <= n; i++){ theorems[i] = r.nextInt(); } int[] mishka = new int[n+1]; for(int i = 1; i <= n; i++){ mishka[i] = r.nextInt(); } int[] sums = new int[n+1]; for(int i = 1; i <= n; i++){ if(mishka[i] == 0){ sums[i] = sums[i-1] + theorems[i]; } else{ sums[i] = sums[i-1]; } } int max = 0; for(int i = 1; i <= n-k+1; i++){ int sum = sums[i+k-1] - sums[i-1]; max = Math.max(max, sum); } int totalSum = 0; for(int i = 1; i <= n; i++){ if(mishka[i] == 1){ totalSum += theorems[i]; } } pw.println(totalSum + max); pw.close(); } }
linear
961_B. Lecture Sleep
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class C { public static int mod = 1000000000 + 7; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String n = br.readLine(); int k = Integer.parseInt(br.readLine()); int l = n.length(); if(k == 0) { System.out.println(1); }else { int max = 1000; if (l <= 10) { max = Integer.min(1000, Integer.parseInt(n, 2)); } int[] steps = new int[max + 1]; for (int i = 2; i <= max; i++) { int ones = numberOfOnes(i); steps[i] = 1 + steps[ones]; } if (l <= 10) { int ans = 0; for (int i = 1; i <= max; i++) { if (steps[i] == k) { ans++; } } System.out.println(ans); } else { int[][] C = binomial(max); int ans = 0; int count = 0; for (int i = 0; i < l; i++) { if (n.charAt(i) == '1') { for (int j = count; j < max; j++) { if (steps[j] == k - 1) { ans = (ans + C[l - i - 1][j - count]) % mod; if (i == 0 && k == 1) { ans = (ans + mod - 1) % mod; } } } count++; } } int ones = 0; for (int i = 0; i < l; i++) { if (n.charAt(i) == '1') { ones++; } } if (steps[ones] == k-1) { ans = (ans + 1) % mod; } System.out.println(ans); } } } public static int numberOfOnes(int x) { char[] s = Integer.toBinaryString(x).toCharArray(); int count = 0; for (char c : s) { if (c == '1') { count++; } } return count; } public static int[][] binomial(int n) { int[][] C = new int[n + 1][n + 1]; for (int i = 0; i <= n; i++) { C[i][0] = 1; for (int j = 1; j <= i; j++) { C[i][j] = ((C[i - 1][j - 1] % mod) + (C[i - 1][j] % mod)) % mod; } } return C; } }
linear
914_C. Travelling Salesman and Special Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; import java.util.Arrays; public class Main { static Scanner in = new Scanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { long n = in.nextLong(), m = in.nextLong(); out.print(m / n + (m % n == 0 ? 0 : 1)); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } public String next() throws IOException { if(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
constant
1036_A. Function Height
CODEFORCES
import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable; import jdk.management.cmm.SystemResourcePressureMXBean; import java.awt.*; import java.io.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.util.List; import java.math.*; public class Newbie { static InputReader sc = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { solver s = new solver(); int t = 1; while (t > 0) { s.solve(); t--; } out.close(); } /* static class descend implements Comparator<pair1> { public int compare(pair1 o1, pair1 o2) { if (o1.pop != o2.pop) return (int) (o1.pop - o2.pop); else return o1.in - o2.in; } }*/ 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()); } public double nextDouble() { return Double.parseDouble(next()); } } static class card { long a; int cnt; int i; public card(long a, int cnt, int i) { this.a = a; this.cnt = cnt; this.i = i; } } static class ascend implements Comparator<pair> { public int compare(pair o1, pair o2) { return o1.a - o2.a; } } static class extra { static boolean v[] = new boolean[100001]; static List<Integer> l = new ArrayList<>(); static int t; 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 boolean valid(int i, int j, int r, int c) { if (i >= 0 && i < r && j >= 0 && j < c) return true; else return false; } static void seive() { for (int i = 2; i < 100001; i++) { if (!v[i]) { t++; l.add(i); for (int j = 2 * i; j < 100001; j += i) v[j] = true; } } } static int binary(long a[], long val, int n) { int mid = 0, l = 0, r = n - 1, ans = 0; while (l <= r) { mid = (l + r) >> 1; if (a[mid] == val) { r = mid - 1; ans = mid; } else if (a[mid] > val) r = mid - 1; else { l = mid + 1; ans = l; } } return (ans + 1); } static long fastexpo(int x, int y) { long res = 1; while (y > 0) { if ((y & 1) == 1) { res *= x; } y = y >> 1; x = x * x; } return res; } static long lfastexpo(int x, int y, int p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) { res = (res * x) % p; } y = y >> 1; x = (x * x) % p; } return res; } } static class pair { int a; int b; public pair(int a, int i) { this.a = a; this.b = i; } } static class pair1 { pair p; int in; public pair1(pair a, int n) { this.p = a; this.in = n; } } static long m = (long) 1e9 + 7; static class solver { void solve() { int n = sc.nextInt(); int ans=0; int a[]=new int[2*n]; for (int i = 0; i < 2 * n; i++) { a[i]=sc.nextInt(); } for(int i=0;i<2*n;i++) { if(a[i]>0) { int j=0; for(j=i+1;a[i]!=a[j];j++) { if(a[j]>0) ans++; } a[j]=0; } } System.out.println(ans); } } }
quadratic
995_B. Suit and Tie
CODEFORCES
import java.io.*; import java.util.*; public class Main { private static void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); String[] sa = new String[n]; for (int i = 0; i < n; i++) { sa[i] = in.next(); } Set<Integer> switches = new HashSet<>(); for (int i = 0; i < m; i++) { int cnt = 0, swtch = -1; for (int j = 0; j < n; j++) { if (sa[j].charAt(i) == '1') { cnt++; swtch = j; if (cnt > 1) break; } } if (cnt == 1) { switches.add(swtch); } } out.print(switches.size() == n ? "NO" : "YES"); } private static void shuffleArray(int[] array) { int index; Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { index = random.nextInt(i + 1); if (index != i) { array[index] ^= array[i]; array[i] ^= array[index]; array[index] ^= array[i]; } } } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); solve(in, out); in.close(); out.close(); } private static class InputReader { private BufferedReader br; private StringTokenizer st; InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); st = null; } String nextLine() { String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } String next() { while (st == null || !st.hasMoreTokens()) { String line = nextLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } private static class OutputWriter { BufferedWriter bw; OutputWriter(OutputStream os) { bw = new BufferedWriter(new OutputStreamWriter(os)); } void print(int i) { print(Integer.toString(i)); } void println(int i) { println(Integer.toString(i)); } void print(long l) { print(Long.toString(l)); } void println(long l) { println(Long.toString(l)); } void print(double d) { print(Double.toString(d)); } void println(double d) { println(Double.toString(d)); } void print(boolean b) { print(Boolean.toString(b)); } void println(boolean b) { println(Boolean.toString(b)); } void print(char c) { try { bw.write(c); } catch (IOException e) { e.printStackTrace(); } } void println(char c) { println(Character.toString(c)); } void print(String s) { try { bw.write(s); } catch (IOException e) { e.printStackTrace(); } } void println(String s) { print(s); print('\n'); } void close() { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
quadratic
985_B. Switches and Lamps
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; public class CodeForces { public static void main(String[] args) { Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in))); System.out.println(input.nextInt() / 2 + 1); } }
constant
964_A. Splits
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class MicroWorld { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[] temp = new int[1000001]; StringTokenizer st1 = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++){ temp[Integer.parseInt(st1.nextToken())]++; } int b = k + 1; for (int i = 1000000; i > 0; i--){ if (temp[i] > 0){ if (b <= k){ n -= temp[i]; } b = 1; }else{ b++; } } System.out.println(n); } }
nlogn
990_B. Micro-World
CODEFORCES
import java.util.*; import java.io.*; public class SonyaExhibition { static BufferedReader br; static StringTokenizer tokenizer; public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(); int[] arr = {0,1}; for(int i = 0; i < n; i++) { System.out.print(arr[i % 2]); } System.out.println(); } public static String next() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) throw new IOException(); tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } }
linear
1004_B. Sonya and Exhibition
CODEFORCES
import java.io.*; import java.util.*; public class ayyyyyy { public static void main(String[] args) { new ayyyyyy(); } Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int t, n; int[] a; ayyyyyy() { t = in.nextInt(); while (t --> 0) { a = new int[n = in.nextInt()]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); shuffle(a); Arrays.sort(a); out.println(Math.min(n-2, a[n-2]-1)); } out.close(); } void shuffle(int[] x) { for (int i = 0; i < n; i++) { int swp = (int)(n*Math.random()); int tmp = x[swp]; x[swp] = x[i]; x[i] = tmp; } } }
nlogn
1197_A. DIY Wooden Ladder
CODEFORCES
//package contese_476; import java.util.*; public class q1 { int m=(int)1e9+7; public class Node { int a; int b; public void Node(int a,int b) { this.a=a; this.b=b; } } public int mul(int a ,int b) { a=a%m; b=b%m; return((a*b)%m); } public int pow(int a,int b) { int x=1; while(b>0) { if(b%2!=0) x=mul(x,a); a=mul(a,a); b=b/2; } return x; } public static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); HashMap<Integer,Integer> h=new HashMap(); //HashMap<Integer,Integer> h1=new HashMap(); int[] a=new int[n]; int x=sc.nextInt(); for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(h.get(a[i])==null) { h.put(a[i], 1); //h1.put(a[i],i); } else { System.out.print(0); System.exit(0); } } for(int i=0;i<n;i++) { int num=a[i]&x; if(num==a[i]) continue; if(h.get(num)==null) continue; else { System.out.print(1); System.exit(0); } } for(int i=0;i<n;i++) { int num=a[i]&x; if(num==a[i]) continue; if(h.get(num)==null) h.put(num, 1); else { System.out.print(2); System.exit(0); } } System.out.print(-1); } }
linear
1013_B. And
CODEFORCES
import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; /** * Built using CHelper plug-in Actual solution is at the top */ public class Practice { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); String[] arr1 = new String[n]; String[] arr2 = new String[n]; for (int i = 0; i < n; i++) { arr1[i] = in.next(); } for (int i = 0; i < n; i++) { arr2[i] = in.next(); } int ans = 0; boolean arr[]=new boolean[n]; boolean found=false; for (int i = 0; i < arr1.length; i++) { for(int j=0;j<arr1.length;j++){ found=false; if(arr1[i].equals(arr2[j]) && !arr[j]){ found=true; arr[j]=true; break; } } if(!found){ ans++; } } out.println(ans); } } public static boolean checkPrime(int n, int p) { for (int i = 2; i <= Math.sqrt(n) && i <= p; i++) { if (n % i == 0) { return false; } } return true; } public static void mergeArrays(int[] arr1, int[] arr2, int n1, int n2, int[] arr3) { int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { if (arr1[i] < arr2[j]) { arr3[k++] = arr1[i++]; } else { arr3[k++] = arr2[j++]; } } while (i < n1) { arr3[k++] = arr1[i++]; } while (j < n2) { arr3[k++] = arr2[j++]; } } public long GCD(long a, long b) { if (b == 0) { return a; } return GCD(b, a % b); } public static long nCr(int n, int r) { return n * (n - 1) / 2; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
quadratic
1000_A. Codehorses T-shirts
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 sumit */ 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); CChessboard solver = new CChessboard(); solver.solve(1, in, out); out.close(); } static class CChessboard { int[] nextPermutation(int[] array) { int i = array.length - 1; while (i > 0 && array[i - 1] >= array[i]) { i--; } if (i <= 0) { return null; } int j = array.length - 1; while (array[j] <= array[i - 1]) { j--; } int temp = array[i - 1]; array[i - 1] = array[j]; array[j] = temp; j = array.length - 1; while (i < j) { temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } return array; } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int arr[][][] = new int[4][n][n]; int sum[] = new int[4]; for (int k = 0; k < 4; k++) { for (int i = 0; i < n; i++) { String str = in.next(); for (int j = 0; j < n; j++) { arr[k][i][j] = (str.charAt(j) - '0'); } } } for (int k = 0; k < 4; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((i + j) % 2 == arr[k][i][j]) sum[k]++; } } } int perm[] = new int[4]; for (int i = 0; i < 4; i++) perm[i] = i; int min = Integer.MAX_VALUE; while (true) { perm = nextPermutation(perm); if (perm == null) break; int sm = 0; for (int j = 0; j < 4; j++) { if (j % 2 == 0) { sm += (sum[perm[j]]); } else { sm += (n * n - sum[perm[j]]); } } min = Math.min(min, sm); sm = 0; for (int j = 0; j < 4; j++) { if (j % 2 == 0) { sm += (n * n - sum[perm[j]]); } else { sm += (sum[perm[j]]); } } min = Math.min(sm, min); } out.printLine(min); } } 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(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; 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 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 & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
961_C. Chessboard
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); double a = (double)read.nextInt(); double v = (double)read.nextInt(); double l = (double)read.nextInt(); double d = (double)read.nextInt(); double w = (double)read.nextInt(); double t=0; if(w>=v){ double d1=v*v/(2*a); if(d1>l){ t+= Math.sqrt(2*l/a); } else{ t+= v/a + (l-d1)/v; } } else{ double temp = (v-w)/a; double d1 = v*v/(2*a); double d2 = d - v*temp + a*temp*temp/2; if(d1>d2){ double temp2 = Math.sqrt(2*a*d); if(temp2<w){ w=temp2; temp=(v-w)/a; t+= temp2/a; } else{ double vx=Math.sqrt(v*v/2+a*d2); t+= (vx/a) + ((vx-w)/a); } } else{ t+= (v/a) + ((d2-d1)/v) + (temp); } double d3 = d + w*temp + a*temp*temp/2; if(d3>l){ t+= (-w+Math.sqrt(w*w+2*a*(l-d)))/a; } else{ t+= (temp) + ((l-d3)/v); } } System.out.printf("%.6f", t); read.close(); } }
constant
5_D. Follow Traffic Rules
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 m=Integer.parseInt(s1[1]); int a[]=new int[n]; String s2[]=br.readLine().split(" "); long S=0; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(s2[i]); S+=(long)a[i]; } Arrays.sort(a); m=a[n-1]; int last=1; int t=1; for(int i=1;i<n-1;i++) { if(a[i]==last) t++; else { t++; last=last+1; } } if(last<m) { t+=m-last; } else t++; System.out.println(S-t); } }
nlogn
1061_B. Views Matter
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Solution { private static int[] a; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); a = new int[101]; for (int i = 0; i < m; i++) { int type = sc.nextInt(); a[type] = a[type] + 1; } int lo=1, hi=100, max=0; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (check(n, mid)) { max = mid; lo = mid+1; } else { hi = mid -1; } } System.out.println(max); } public static boolean check(int n, int target) { int result = 0; for (int i=0; i <a.length; i++) { result = result + (a[i] / target); } if (result >= n) {return true;} return false; } }
nlogn
1011_B. Planning The Expedition
CODEFORCES
import java.util.*; public class ErrorCorrectSystem { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String a = scan.next(); String b = scan.next(); int[][] mismatch = new int[26][26]; for(int i = 0; i < 26; i++) Arrays.fill(mismatch[i], -1); int[][] pair = new int[2][26]; for(int i = 0; i < 2; i++) Arrays.fill(pair[i], -1); int hd = 0; for(int i = 0; i < n; i++) { if(a.charAt(i) != b.charAt(i)) { hd++; mismatch[a.charAt(i)-'a'][b.charAt(i)-'a'] = i; pair[0][a.charAt(i)-'a'] = i; pair[1][b.charAt(i)-'a'] = i; } } for(int i = 0; i < 26; i++) { for(int j = i+1; j < 26; j++) { if(mismatch[i][j] > -1 && mismatch[j][i] > -1) { System.out.println(hd-2); System.out.println((mismatch[i][j]+1)+" "+(mismatch[j][i]+1)); return; } } } for(int i = 0; i < n; i++) { if(a.charAt(i) != b.charAt(i)) { //try a gets b's letter if(pair[0][b.charAt(i)-'a'] > -1) { System.out.println(hd-1); System.out.println((i+1)+" "+(pair[0][b.charAt(i)-'a']+1)); return; } } } System.out.println(hd); System.out.println("-1 -1"); } }
linear
527_B. Error Correct System
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.Random; import java.util.StringJoiner; import java.util.StringTokenizer; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; public class Main { static int T; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); T = sc.nextInt(); PrintWriter pw = new PrintWriter(System.out); for (int i = 0; i < T; i++) { int n = sc.nextInt(); int[] a = sc.nextIntArray(n); int[] ans = solve(n, a); StringJoiner j = new StringJoiner(" "); for (int each : ans) { j.add(String.valueOf(each)); } pw.println(j.toString()); } pw.flush(); } static int[] solve(int N, int[] A) { // a/b が1に近いものを探す shuffle(A); Arrays.sort(A); int cur = A[0]; int time = 1; double r = 0; int prev = -1; int a = -1; int b = -1; for (int i = 1; i < N; i++) { if( cur == A[i] ) { time++; if( time == 2 ) { if( prev != -1 ) { double r1 = (double)prev/cur; if( r1 > r ) { r = r1; a = prev; b = cur; } } prev = cur; } if( time == 4 ) { return new int[]{cur, cur, cur, cur}; } } else { time = 1; cur = A[i]; } } return new int[]{a, a, b, b}; } static void shuffle(int[] a) { Random r = ThreadLocalRandom.current(); for (int i = a.length-1; i >= 0; i--) { int j = r.nextInt(i+1); int t = a[i]; a[i] = a[j]; a[j] = t; } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
nlogn
1027_C. Minimum Value Rectangle
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class ElevatorOrStairs { private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static final OutputStreamWriter writer = new OutputStreamWriter(System.out); public static void main(String...strings) throws Exception { String[] specs = reader.readLine().split(" "); int x = Integer.parseInt(specs[0]); int y = Integer.parseInt(specs[1]); int z = Integer.parseInt(specs[2]); int t1 = Integer.parseInt(specs[3]); int t2 = Integer.parseInt(specs[4]); int t3 = Integer.parseInt(specs[5]); reader.close(); String ans = solve(x, y, z, t1, t2, t3); writer.append(ans); writer.flush(); writer.close(); } private static String solve(int x, int y, int z, int t1, int t2, int t3) { int time_using_stairs = Math.abs(x - y) * t1; int elevator_time_between_floor = Math.abs(x - z) * t2; int elevator_from_z_to_x = elevator_time_between_floor + 2*t3; int time_using_elevator = elevator_from_z_to_x + (Math.abs(x - y) * t2) + t3; if(time_using_elevator <= time_using_stairs) { return "YES"; } return "NO"; } }
constant
1054_A. Elevator or Stairs?
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.InputMismatchException; public class Solution1 implements Runnable { static final long MAX = 1000000007L; 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 Solution1(),"Solution1",1<<26).start(); } long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } // method to return LCM of two numbers long lcm(long a, long b) { return (a*b)/gcd(a, b); } int root(int a){ while(arr[a] != a){ arr[a] = arr[arr[a]]; a = arr[a]; } return a; } void union(int a,int b){ int xroot = root(a); int yroot = root(b); if(arr[xroot] < arr[yroot]){ arr[xroot] = yroot; }else{ arr[yroot] = xroot; } } boolean find(int a,int b){ int roota = root(a); int rootb = root(b); if(roota == rootb){ return true; }else{ return false; } } int[] arr; final int level = 20; public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); int n = sc.nextInt(); char[] ch = new char[n]; char[] ch2 = new char[n]; ch = sc.next().toCharArray(); ch2 = sc.next().toCharArray(); HashSet<Integer> hset[] = new HashSet[26]; for(int i = 0;i < 26;i++){ hset[i] =new HashSet(); } int count = 0; for(int i = 0;i < ch.length;i++){ if(ch[i] != ch2[i]){ hset[ch[i]-97].add(ch2[i]-97); count++; } } boolean flag = false; int swap1 = -1; int swap2 = -1; int rem = -1; for(int i = 0;i < ch.length;i++){ if(ch[i] != ch2[i]){ if(hset[ch2[i]-97].size() != 0){ swap1 = i; flag = true; if(hset[ch2[i]-97].contains(ch[i]-97)){ rem = i; count-=2; flag = false; break; } } } } if(flag){ count--; w.println(count); for(int i = 0;i < n;i++){ if(i != swap1 && ch[i] == ch2[swap1] && ch[i] != ch2[i]){ w.println((swap1+1) + " " + (i+1)); w.close(); System.exit(0); } } }else{ if(rem == -1){ w.println(count); w.println("-1 -1"); }else{ w.println(count); for(int i = 0;i < n;i++){ if(i != rem && ch[i] == ch2[rem] && ch[rem] == ch2[i] && ch[i] != ch2[i]){ w.println((rem+1) + " " + (i+1)); w.close(); System.exit(0); } } } } w.close(); } boolean fun(long[] prefix,long mid,long temp,long[] arr){ if(temp >= prefix[(int)mid]){ return true; } return false; } static class Pair implements Comparable<Pair>{ int x; int y; Pair(){} Pair(int x,int y){ this.x = x; this.y = y; } public int compareTo(Pair p){ return Long.compare(this.x,p.x); } } }
linear
527_B. Error Correct System
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SFly { public static void main(String[] args) throws IOException { BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); int planet = Integer.parseInt(lector.readLine()); int ini = Integer.parseInt(lector.readLine()); double peso = ini; int[] desp = new int[planet]; int[] ater = new int[planet]; String[] temp = lector.readLine().split(" "); for(int i=0; i<planet; i++) { desp[i] = Integer.parseInt(temp[i]); if(desp[i] == 1) { System.out.println(-1); lector.close(); return; } } temp = lector.readLine().split(" "); for(int i=0; i<planet; i++) { ater[i] = Integer.parseInt(temp[i]); if(ater[i] == 1) { System.out.println(-1); lector.close(); return; } } temp = null; int i=planet-1; peso = (peso*ater[0])/(ater[0]-1); while(i>0) { peso = (peso*desp[i])/(desp[i]-1); peso = (peso*ater[i])/(ater[i]-1); i--; } peso = (peso*desp[0])/(desp[0]-1); peso = peso - ini; System.out.println(peso); lector.close(); } }
linear
1010_A. Fly
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class Main { static BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer tok; static boolean hasNext() { while(tok==null||!tok.hasMoreTokens()) try{ tok=new StringTokenizer(in.readLine()); } catch(Exception e){ return false; } return true; } static String next() { hasNext(); return tok.nextToken(); } static long nextLong() { return Long.parseLong(next()); } static int nextInt() { return Integer.parseInt(next()); } static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) { Map<Integer,Integer> map = new HashMap(); map.put(0,1); int n = nextInt(); int m = nextInt(); int index = -1; int a[] = new int[n]; for(int i=0;i<n;i++){ a[i]=nextInt(); if(a[i]==m) index=i; } int sum = 0; for(int i=0;i<index;i++){ if (a[i]<m) sum--; else sum++; if (map.containsKey(sum)){ map.put(sum,map.get(sum)+1); }else { map.put(sum,1); } } long ans = 0; for(int i=index;i<n;i++){ if (a[i]<m) sum--; else if(a[i]>m) sum++; if (map.containsKey(sum)) ans+=map.get(sum); if (map.containsKey(sum-1)) ans+=map.get(sum-1); } out.print(ans); out.flush(); } }
nlogn
1005_E1. Median on Segments (Permutations Edition)
CODEFORCES
import java.util.HashSet; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); HashSet<Integer> set = new HashSet<>(); for(int i = 0; i<n; i++){ int a = sc.nextInt(); if(a!=0){ set.add(a); } } System.out.println(set.size()); } }
linear
992_A. Nastya and an Array
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; public class Solution { private static int[] dx = { -1, -1, -1, 0, 0, 1, 1, 1}; private static int[] dy = { -1, 0, 1, -1, 1, -1, 0, 1}; public static void main(String[] args) { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int r = in.nextInt(); int c = in.nextInt(); boolean[][] m = new boolean[r + 1][c + 1]; boolean[][] inp = new boolean[r + 1][c + 1]; for (int i = 0; i < r; i++) { String s = in.next(); //System.out.println(m[i]); for (int j = 0; j < s.length(); j++) { if (s.charAt(j) == '#') { m[i][j] = true; inp[i][j] = true; } } } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (canPress(i, j, r, c, inp)) { // make press for (int k = 0; k < 8; k++) { int xi = i + dx[k]; int yi = j + dy[k]; m[xi][yi] = false; } } } } boolean isLeftAny = false; for (int i = 0; i < r && !isLeftAny; i++) { for (int j = 0; j < c && !isLeftAny; j++) { if (m[i][j]) { isLeftAny = true; break; } } } if(isLeftAny){ System.out.println("NO"); }else{ System.out.println("YES"); } } private static boolean canPress(int x, int y, int r, int c, boolean[][] inp) { for (int i = 0; i < 8; i++) { int xi = x + dx[i]; int yi = y + dy[i]; if (xi < 0 || yi < 0) { return false; } if (xi >= r || yi >= c) { return false; } if(!inp[xi][yi]){ return false; } } return true; } }
quadratic
1059_B. Forgery
CODEFORCES
import java.util.*; public class Main { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int n=scan.nextInt(); int m=scan.nextInt(); int[] game=new int[n]; int[] bill=new int[m]; for (int i = 0; i <n ; i++) { game[i]=scan.nextInt(); } for (int i = 0; i <m ; i++) { bill[i]=scan.nextInt(); } int i=0; int j=0; int ans=0; while (i<m){ boolean f=true; for (int k = j; k <n ; k++) { if (bill[i]>=game[k]){ ans++; i++; j=k+1; f=false; break; } } if (f){ break; } } System.out.println(ans); } }
linear
1009_A. Game Shopping
CODEFORCES
import java.math.BigInteger; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class Practice { public static void main(String []args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); sc.nextLine(); String s=sc.nextLine(); //System.out.println(s); char c[]=s.toCharArray(); ArrayList a =new ArrayList(); for(int i=0;i<c.length;i++) { //System.out.println(c[i]); a.add(c[i]); } int x=Collections.frequency(a,'0' ); int y=Collections.frequency(a,'1'); //System.out.println(x+ " "+y ); if(y==0 || y==1) { System.out.println(s); } else { if(y>=2) { String s1="1"; for(int i=0;i<x;i++) { s1=s1+"0"; } System.out.println(s1); } } } }
linear
976_A. Minimum Binary Number
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 Pradyumn */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { FastReader in; PrintWriter out; int n; public void solve(int testNumber, FastReader in, PrintWriter out) { this.in = in; this.out = out; n = in.nextInt(); if (n % 4 != 0) { out.println("! -1"); return; } int low = 0; int high = n >> 1; int fSign = Integer.signum(BValue(low)); if (fSign == 0) { out.println("! " + (low + 1)); return; } while (high - low > 1) { int mid = (high + low) >> 1; int mSign = Integer.signum(BValue(mid)); if (mSign == 0) { out.println("! " + (mid + 1)); return; } if (mSign == -fSign) { high = mid; } else { low = mid; } } out.println("! -1"); } public int BValue(int index) { out.println("? " + (index + 1)); out.flush(); int f = in.nextInt(); out.println("? " + (index + 1 + (n >> 1))); out.flush(); int s = in.nextInt(); return f - s; } } 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; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
logn
1019_B. The hat
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 a = solve(); out.print(a == 0 ? "tokitsukaze" : a == 1 ? "quailty" : "once again"); } int n, k; char ch[]; int a[], c0 = 0, c1 = 0; TreeSet<Integer> ts[] = new TreeSet[2]; boolean check(){ int min = 0, max = n; if(!ts[0].isEmpty()){ min = ts[0].first(); max = ts[0].last(); if(max - min + 1 > k)return true; } if(!ts[1].isEmpty()){ min = ts[1].first(); max = ts[1].last(); if(max - min + 1 > k)return true; } return false; } int solve(){ n = in.nextInt(); k = in.nextInt(); ch = in.next().trim().toCharArray(); a = new int[n]; for(int i = 0; i < n; i++)c1 += a[i] = ch[i] - '0'; c0 = n - c1; for(int i = 0; i < k; i++){ if(a[i] == 0)c0--; else c1--; } if(c0 == 0 || c1 == 0)return 0; for(int i = k; i < n; i++){ if(a[i] == 0)c0--; else c1--; if(a[i - k] == 0)c0++; else c1++; if(c0 == 0 || c1 == 0)return 0; } for(int i = 0; i < 2; i++)ts[i] = new TreeSet<>(); for(int i = 0; i < n; i++){ ts[a[i]].add(i); } for(int i = 0; i < k; i++){ ts[a[i]].remove(i); } if(check())return 2; for(int i = k; i < n; i++){ ts[a[i]].remove(i); ts[a[i - k]].add(i - k); if(check())return 2; } return 1; } 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_C. Tokitsukaze and Duel
CODEFORCES
import java.util.*; import java.io.*; import java.util.Map.Entry; public class Codeforces { static int n; static double max; static int[] pre; public static void findIntensity(int l){ for(int i = 0, j = i + l; j < n + 1; i++, j++){ double res = (pre[j] - pre[i]) / (double) l; max = Math.max(max, res); } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[] heat = new int[n]; st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++){ heat[i] = Integer.parseInt(st.nextToken()); } max = 0; pre = new int[n + 1]; pre[0] = 0; for(int i = 0; i < n; i++){ pre[i + 1] = pre[i] + heat[i]; } for(int i = k; i <= n; i++){ findIntensity(i); } System.out.println(max); } }
quadratic
1003_C. Intense Heat
CODEFORCES
import java.util.*; import java.io.*; public class code{ public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int ok,ok2; int va,vb; va = 0; vb = 0; out.println("? "+va+" "+vb); out.flush(); ok = sc.nextInt(); for(int i=29;i>=0;i--){ if(ok==0){ va += (1<<i); out.println("? "+va+" "+vb); out.flush(); ok2 = sc.nextInt(); if(ok2==1){ va -= (1<<i); }else{ vb += (1<<i); } }else{ va += (1<<i); vb += (1<<i); out.println("? "+va+" "+vb); out.flush(); ok2 = sc.nextInt(); if(ok==ok2){ vb -= (1<<i); out.println("? "+va+" "+vb); out.flush(); ok2 = sc.nextInt(); if(ok2==1){ va -= (1<<i); }else{ vb += (1<<i); } }else{ if(ok==1){ vb -= (1<<i); out.println("? "+va+" "+vb); out.flush(); ok = sc.nextInt(); } else { va -= (1<<i); out.println("? "+va+" "+vb); out.flush(); ok = sc.nextInt(); } } } } out.println("! "+va+" "+vb); out.flush(); } }
logn
1088_D. Ehab and another another xor problem
CODEFORCES
import java.io.*; import java.util.*; public class Main { private static void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); if (n < 6) { out.println(-1); } else { int m = (n - 2); for (int i = 2; i <= m; i++) { out.println("1 " + i); } out.println(m + " " + (m + 1)); out.println(m + " " + (m + 2)); } for (int i = 2; i <= n; i++) { out.println("1 " + i); } } private static void shuffleArray(int[] array) { int index; Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { index = random.nextInt(i + 1); if (index != i) { array[index] ^= array[i]; array[i] ^= array[index]; array[index] ^= array[i]; } } } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); solve(in, out); in.close(); out.close(); } private static class InputReader { private BufferedReader br; private StringTokenizer st; InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); st = null; } String nextLine() { String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } String next() { while (st == null || !st.hasMoreTokens()) { String line = nextLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } byte nextByte() { return Byte.parseByte(next()); } short nextShort() { return Short.parseShort(next()); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } private static class OutputWriter { BufferedWriter bw; OutputWriter(OutputStream os) { bw = new BufferedWriter(new OutputStreamWriter(os)); } void print(int i) { print(Integer.toString(i)); } void println(int i) { println(Integer.toString(i)); } void print(long l) { print(Long.toString(l)); } void println(long l) { println(Long.toString(l)); } void print(double d) { print(Double.toString(d)); } void println(double d) { println(Double.toString(d)); } void print(boolean b) { print(Boolean.toString(b)); } void println(boolean b) { println(Boolean.toString(b)); } void print(char c) { try { bw.write(c); } catch (IOException e) { e.printStackTrace(); } } void println(char c) { println(Character.toString(c)); } void print(String s) { try { bw.write(s); } catch (IOException e) { e.printStackTrace(); } } void println(String s) { print(s); print('\n'); } void close() { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
linear
959_C. Mahmoud and Ehab and the wrong algorithm
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; import java.util.function.Function; public class P1196D2 { static boolean multipleIndependent = true; void run() { int n = in.nextInt(); int k = in.nextInt(); char[] s = in.next().toCharArray(); int[] dp = new int[3]; char[] c = {'R', 'G', 'B'}; int min = Integer.MAX_VALUE; for (int i = 0; i < k; i++) { dp[0] += s[i] == c[(i + 0) % 3] ? 0 : 1; dp[1] += s[i] == c[(i + 1) % 3] ? 0 : 1; dp[2] += s[i] == c[(i + 2) % 3] ? 0 : 1; } min = Math.min(Math.min(Math.min(dp[0], dp[1]), dp[2]), min); // System.out.println(Arrays.toString(dp)); for (int i = k; i < n; i++) { dp[0] += (s[i] == c[(i + 0) % 3] ? 0 : 1) - (s[i - k] == c[(i - k + 0) % 3] ? 0 : 1); dp[1] += (s[i] == c[(i + 1) % 3] ? 0 : 1) - (s[i - k] == c[(i - k + 1) % 3] ? 0 : 1); dp[2] += (s[i] == c[(i + 2) % 3] ? 0 : 1) - (s[i - k] == c[(i - k + 2) % 3] ? 0 : 1); min = Math.min(Math.min(Math.min(dp[0], dp[1]), dp[2]), min); // System.out.println(Arrays.toString(dp)); } System.out.println(min); } /* -----: Template :----- */ static InputReader in = new InputReader(System.in); public static void main(String[] args) { P1196D2 p = new P1196D2(); int q = multipleIndependent ? in.nextInt() : 1; while (q-- > 0) { p.run(); } } int numLength(long n) { int l = 0; while (n > 0) { n /= 10; l++; } return l; } <R> long binarySearch(long lowerBound, long upperBound, R value, Function<Long, R> generatorFunction, Comparator<R> comparator) { if (lowerBound <= upperBound) { long mid = (lowerBound + upperBound) / 2; int compare = comparator.compare(generatorFunction.apply(mid), value); if (compare == 0) { return mid; } else if (compare < 0) { return binarySearch(mid + 1, upperBound, value, generatorFunction, comparator); } else { return binarySearch(lowerBound, mid - 1, value, generatorFunction, comparator); } } else { return -1; } } <T> Integer[] sortSimultaneously(T[] key, Comparator<T> comparator, Object[]... moreArrays) { int n = key.length; for (Object[] array : moreArrays) { if (array.length != n) { throw new RuntimeException("Arrays must have equals lengths"); } } Integer[] indices = new Integer[n]; for (int i = 0; i < n; i++) { indices[i] = i; } Comparator<Integer> delegatingComparator = (a, b) -> { return comparator.compare(key[a], key[b]); }; Arrays.sort(indices, delegatingComparator); reorder(indices, key); for (Object[] array : moreArrays) { reorder(indices, array); } return indices; } void reorder(Integer[] indices, Object[] arr) { if (indices.length != arr.length) { throw new RuntimeException("Arrays must have equals lengths"); } int n = arr.length; Object[] copy = new Object[n]; for (int i = 0; i < n; i++) { copy[i] = arr[indices[i]]; } System.arraycopy(copy, 0, arr, 0, n); } int prodMod(int a, int b, int mod) { return (int) (((long) a) * b % mod); } long prodMod(long a, long b, long mod) { long res = 0; a %= mod; b %= mod; while (b > 0) { if ((b & 1) > 0) { res = (res + a) % mod; } a = (a << 1) % mod; b >>= 1; } return res; } long sumMod(int[] b, long mod) { long res = 0; for (int i = 0; i < b.length; i++) { res = (res + b[i] % mod) % mod; } return res; } long sumMod(long[] a, long mod) { long res = 0; for (int i = 0; i < a.length; i++) { res = (res + a[i] % mod) % mod; } return res; } long sumProdMod(int[] a, long b, long mod) { long res = sumMod(a, mod); return prodMod(res, b, mod); } long sumProdMod(long[] a, long b, long mod) { long res = sumMod(a, mod); return prodMod(res, b, mod); } long sumProdMod(int[] a, int[] b, long mod) { if (a.length != b.length) { throw new RuntimeException("Arrays must have equals lengths"); } long res = 0; for (int i = 0; i < a.length; i++) { res = (res + prodMod(a[i], b[i], mod)) % mod; } return res; } long sumProdMod(long[] a, long[] b, long mod) { if (a.length != b.length) { throw new RuntimeException("Arrays must have equals lengths"); } long res = 0; for (int i = 0; i < a.length; i++) { res = (res + prodMod(a[i], b[i], mod)) % mod; } return res; } int[] toPrimitive(Integer[] arr) { int[] res = new int[arr.length]; for (int i = 0; i < arr.length; i++) { res[i] = arr[i]; } return res; } int[][] toPrimitive(Integer[][] arr) { int[][] res = new int[arr.length][]; for (int i = 0; i < arr.length; i++) { res[i] = toPrimitive(arr[i]); } return res; } long[] toPrimitive(Long[] arr) { long[] res = new long[arr.length]; for (int i = 0; i < arr.length; i++) { res[i] = arr[i]; } return res; } long[][] toPrimitive(Long[][] arr) { long[][] res = new long[arr.length][]; for (int i = 0; i < arr.length; i++) { res[i] = toPrimitive(arr[i]); } return res; } Integer[] toWrapper(int[] arr) { Integer[] res = new Integer[arr.length]; for (int i = 0; i < arr.length; i++) { res[i] = arr[i]; } return res; } Integer[][] toWrapper(int[][] arr) { Integer[][] res = new Integer[arr.length][]; for (int i = 0; i < arr.length; i++) { res[i] = toWrapper(arr[i]); } return res; } Long[] toWrapper(long[] arr) { Long[] res = new Long[arr.length]; for (int i = 0; i < arr.length; i++) { res[i] = arr[i]; } return res; } Long[][] toWrapper(long[][] arr) { Long[][] res = new Long[arr.length][]; for (int i = 0; i < arr.length; i++) { res[i] = toWrapper(arr[i]); } return res; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public <T> T[] nextIntArray(int n, Function<Integer, T> function, Class<T> c) { T[] arr = (T[]) Array.newInstance(c, n); for (int i = 0; i < n; i++) { arr[i] = function.apply(nextInt()); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public <T> T[] nextLongArray(int n, Function<Long, T> function, Class<T> c) { T[] arr = (T[]) Array.newInstance(c, n); for (int i = 0; i < n; i++) { arr[i] = function.apply(nextLong()); } return arr; } public int[][] nextIntMap(int n, int m) { int[][] map = new int[n][m]; for (int i = 0; i < n; i++) { map[i] = nextIntArray(m); } return map; } public long[][] nextLongMap(int n, int m) { long[][] map = new long[n][m]; for (int i = 0; i < n; i++) { map[i] = nextLongArray(m); } return map; } public char[][] nextCharMap(int n) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) { map[i] = next().toCharArray(); } return map; } public void readColumns(Object[]... columns) { int n = columns[0].length; for (Object[] column : columns) { if (column.length != n) { throw new RuntimeException("Arrays must have equals lengths"); } } for (int i = 0; i < n; i++) { for (Object[] column : columns) { column[i] = read(column[i].getClass()); } } } public <T> T read(Class<T> c) { throw new UnsupportedOperationException("To be implemented"); } } }
quadratic
1196_D2. RGB Substring (hard version)
CODEFORCES
import java.io.*; import java.util.*; import java.lang.*; import static java.lang.Math.*; // _ h _ r _ t r _ // _ t _ t _ s t _ public class TaskA implements Runnable { long m = (int)1e9+7; PrintWriter w; InputReader c; final int MAXN = (int)1e6 + 100; public void run() { c = new InputReader(System.in); w = new PrintWriter(System.out); int n = c.nextInt(), hamming_distance = 0; char[] s = c.next().toCharArray(), t = c.next().toCharArray(); HashMap<Character, HashSet<Character>> replace = new HashMap<>(); HashMap<Character, Integer> map = new HashMap<>(); for(int i=0;i<n;++i) if(s[i] != t[i]) { HashSet<Character> temp; if(replace.containsKey(s[i])){ temp = replace.get(s[i]); temp.add(t[i]); } else { temp = new HashSet<>(); temp.add(t[i]); } map.put(s[i],i); replace.put(s[i], temp); hamming_distance++; } int l = -1, r = -1; boolean global_check = false; for(int i=0;i<n;i++) if(s[i] != t[i]) { if(replace.containsKey(t[i])) { HashSet<Character> indices = replace.get(t[i]); int ind = map.get(t[i]); l = i + 1; r = ind + 1; if (indices.contains(s[i])) { hamming_distance -= 2; global_check = true; break; } } if(global_check) break; } if(!global_check && l!=-1) hamming_distance--; else if(global_check){ for(int i=0;i<n;i++) { if(t[i] == s[l-1] && s[i] == t[l-1]){ r = i + 1; break; } } } w.println(hamming_distance); w.println(l+" "+r); 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(); } }
linear
527_B. Error Correct System
CODEFORCES
import java.io.*; import java.util.*; public class CF1009E { static final int MD = 998244353; 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[1 + n]; for (int i = 1, a = 0; i <= n; i++) aa[i] = a = (a + Integer.parseInt(st.nextToken())) % MD; int[] pp = new int[n]; pp[0] = 1; for (int i = 1, p = 1; i < n; i++) { pp[i] = p; p = p * 2 % MD; } int d = 0; long ans = 0; for (int i = n - 1; i >= 0; i--) { // rest at i d = (d * 2 % MD + aa[n - 1 - i]) % MD; // rest again before n ans = (ans + (long) (d + aa[n - i]) * pp[i]) % MD; } System.out.println(ans); } }
linear
1009_E. Intercity Travelling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.InputMismatchException; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { try { int n = in.readInt(); int[] x = new int[n], w = new int[n]; in.readIntArrays(x, w); int[] begin = new int[n], end = new int[n]; Arrays.setAll(begin, i -> x[i] - w[i]); Arrays.setAll(end, i -> x[i] + w[i]); int m = ArrayUtils.compress(begin, end).length; int[] dp = new int[m + 1], order = ArrayUtils.order(end); int idx = 0; for (int i = 0; i < m; i++) { if (i > 0) { dp[i] = dp[i - 1]; } while (idx < n && end[order[idx]] == i) { dp[i] = Math.max(dp[i], dp[begin[order[idx]]] + 1); idx++; } } int res = dp[m - 1]; out.printLine(res); } catch (Exception e) { e.printStackTrace(); } } } static class Sorter { private static final int INSERTION_THRESHOLD = 16; private Sorter() { } public static void sort(IntList list, IntComparator comparator) { quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1, comparator); } private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) { if (to - from < INSERTION_THRESHOLD) { insertionSort(list, from, to, comparator); return; } if (remaining == 0) { heapSort(list, from, to, comparator); return; } remaining--; int pivotIndex = (from + to) >> 1; int pivot = list.get(pivotIndex); list.swap(pivotIndex, to); int storeIndex = from; int equalIndex = to; for (int i = from; i < equalIndex; i++) { int value = comparator.compare(list.get(i), pivot); if (value < 0) { list.swap(storeIndex++, i); } else if (value == 0) { list.swap(--equalIndex, i--); } } quickSort(list, from, storeIndex - 1, remaining, comparator); for (int i = equalIndex; i <= to; i++) { list.swap(storeIndex++, i); } quickSort(list, storeIndex, to, remaining, comparator); } private static void heapSort(IntList list, int from, int to, IntComparator comparator) { for (int i = (to + from - 1) >> 1; i >= from; i--) { siftDown(list, i, to, comparator, from); } for (int i = to; i > from; i--) { list.swap(from, i); siftDown(list, from, i - 1, comparator, from); } } private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) { int value = list.get(start); while (true) { int child = ((start - delta) << 1) + 1 + delta; if (child > end) { return; } int childValue = list.get(child); if (child + 1 <= end) { int otherValue = list.get(child + 1); if (comparator.compare(otherValue, childValue) > 0) { child++; childValue = otherValue; } } if (comparator.compare(value, childValue) >= 0) { return; } list.swap(start, child); start = child; } } private static void insertionSort(IntList list, int from, int to, IntComparator comparator) { for (int i = from + 1; i <= to; i++) { int value = list.get(i); for (int j = i - 1; j >= from; j--) { if (comparator.compare(list.get(j), value) <= 0) { break; } list.swap(j, j + 1); } } } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void set(int index, int value); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public void swap(int first, int second) { if (first == second) { return; } int temp = get(first); set(first, get(second)); set(second, temp); } default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } default public IntList sort(IntComparator comparator) { Sorter.sort(this, comparator); return this; } default IntList unique() { int last = Integer.MIN_VALUE; IntList result = new IntArrayList(); int size = size(); for (int i = 0; i < size; i++) { int current = get(i); if (current != last) { result.add(current); last = current; } } return result; } default public IntList subList(final int from, final int to) { return new IntList() { private final int shift; private final int size; { if (from < 0 || from > to || to > IntList.this.size()) { throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size()); } shift = from; size = to - from; } public int size() { return size; } public int get(int at) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } return IntList.this.get(at + shift); } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int at, int value) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } IntList.this.set(at + shift, value); } public IntList compute() { return new IntArrayList(this); } }; } } static interface IntComparator { IntComparator DEFAULT = Integer::compare; int compare(int first, int second); } static class Range { public static IntList range(int from, int to) { int[] result = new int[Math.abs(from - to)]; int current = from; if (from <= to) { for (int i = 0; i < result.length; i++) { result[i] = current++; } } else { for (int i = 0; i < result.length; i++) { result[i] = current--; } } return new IntArray(result); } } static interface IntReversableCollection extends IntCollection { } 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(int i) { writer.println(i); } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { IntIterator intIterator(); default Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } 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 void readIntArrays(int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } 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 readInt() { 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 interface SpaceCharFilter { boolean isSpaceChar(int ch); } } static interface IntCollection extends IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public int[] toArray() { int size = size(); int[] array = new int[size]; int i = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { array[i++] = it.value(); } return array; } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int index, int value) { data[index] = value; } } static class ArrayUtils { public static int[] range(int from, int to) { return Range.range(from, to).toArray(); } public static int[] createOrder(int size) { return range(0, size); } public static int[] sort(int[] array, IntComparator comparator) { return sort(array, 0, array.length, comparator); } public static int[] sort(int[] array, int from, int to, IntComparator comparator) { if (from == 0 && to == array.length) { new IntArray(array).sort(comparator); } else { new IntArray(array).subList(from, to).sort(comparator); } return array; } public static int[] order(final int[] array) { return sort(createOrder(array.length), (first, second) -> Integer.compare(array[first], array[second])); } public static int[] unique(int[] array) { return new IntArray(array).unique().toArray(); } public static int[] compress(int[]... arrays) { int totalLength = 0; for (int[] array : arrays) { totalLength += array.length; } int[] all = new int[totalLength]; int delta = 0; for (int[] array : arrays) { System.arraycopy(array, 0, all, delta, array.length); delta += array.length; } sort(all, IntComparator.DEFAULT); all = unique(all); for (int[] array : arrays) { for (int i = 0; i < array.length; i++) { array[i] = Arrays.binarySearch(all, array[i]); } } return all; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static class IntArrayList extends IntAbstractStream implements IntList { private int size; private int[] data; public IntArrayList() { this(3); } public IntArrayList(int capacity) { data = new int[capacity]; } public IntArrayList(IntCollection c) { this(c.size()); addAll(c); } public IntArrayList(IntStream c) { this(); if (c instanceof IntCollection) { ensureCapacity(((IntCollection) c).size()); } addAll(c); } public IntArrayList(IntArrayList c) { size = c.size(); data = c.data.clone(); } public IntArrayList(int[] arr) { size = arr.length; data = arr.clone(); } public int size() { return size; } public int get(int at) { if (at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size); } return data[at]; } private void ensureCapacity(int capacity) { if (data.length >= capacity) { return; } capacity = Math.max(2 * data.length, capacity); data = Arrays.copyOf(data, capacity); } public void addAt(int index, int value) { ensureCapacity(size + 1); if (index > size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } data[index] = value; size++; } public void removeAt(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size - 1) { System.arraycopy(data, index + 1, data, index, size - index - 1); } size--; } public void set(int index, int value) { if (index >= size) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } data[index] = value; } public int[] toArray() { return Arrays.copyOf(data, size); } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } }
nlogn
528_B. Clique Problem
CODEFORCES
import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class PlayingPiano { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); List<Integer> as = new LinkedList<>(); int[] as2 = new int[n]; for (int i = 0; i < n; i++) { int a = scanner.nextInt(); as.add(a); as2[i] = a; } //System.out.println(solve(as)); System.out.println(solve2(as2)); scanner.close(); } public static String solve(List<Integer> as) { List<Integer> fingers = new LinkedList<>(); fingers.add(1); fingers.add(2); fingers.add(3); fingers.add(4); fingers.add(5); List<Integer> solution = assign(as, fingers, fingers); if (solution == null) { return "-1"; } else { StringBuilder sb = new StringBuilder(); for (int b : solution) { sb.append(b); sb.append(" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } } private static List<Integer> assign(List<Integer> as, List<Integer> fingers, List<Integer> allFingers) { // if fingers is empty return null if (fingers.isEmpty()) { return null; } // if as size is one then return first element in fingers if (as.size() == 1) { List<Integer> ret = new LinkedList<>(); ret.add(fingers.get(0)); return ret; } // get sublist List<Integer> subList = as.subList(1, as.size()); for (int i = 0; i < fingers.size(); i++) { // recursively call with sublist and limited list of fingers List<Integer> subFingers = new LinkedList<>(); final int j = i; if (as.get(0) < as.get(1)) { subFingers = allFingers.stream() .filter(p -> p > fingers.get(j)).collect(Collectors.toList()); } else if (as.get(0) > as.get(1)) { subFingers = allFingers.stream() .filter(p -> p < fingers.get(j)).collect(Collectors.toList()); } else { subFingers = allFingers.stream() .filter(p -> p != fingers.get(j)).collect(Collectors.toList()); } List<Integer> ret = assign(subList, subFingers, allFingers); if (ret != null) { List<Integer> solution = new LinkedList<>(); solution.add(fingers.get(i)); solution.addAll(ret); return solution; } // if return is null, then return null, else return an array } return null; } public static String solve2(int[] as) { int[] ret = new int[as.length]; if (as.length == 1) return "1"; if (as[0] < as[1]) ret[0] = 1; else if (as[0] == as[1]) ret[0] = 3; else ret[0] = 5; for (int i = 1; i < as.length - 1; i++) { if (as[i-1] < as[i] && ret[i-1] == 5) return "-1"; if (as[i-1] > as[i] && ret[i-1] == 1) return "-1"; if (as[i-1] < as[i] && as[i] < as[i+1]) { ret[i] = ret[i-1] + 1; } else if (as[i-1] == as[i] && as[i] < as[i+1]) { ret[i] = ret[i-1] == 1 ? 2 : 1; } else if (as[i-1] > as[i] && as[i] < as[i+1]) { ret[i] = 1; } else if (as[i-1] < as[i] && as[i] == as[i+1]) { ret[i] = ret[i-1] + 1; } else if (as[i-1] == as[i] && as[i] == as[i+1]) { ret[i] = ret[i-1] == 4 ? 2 : 4; } else if (as[i-1] > as[i] && as[i] == as[i+1]) { ret[i] = ret[i-1] == 2 ? 1 : 2; } else if (as[i-1] < as[i] && as[i] > as[i+1]) { ret[i] = 5; } else if (as[i-1] == as[i] && as[i] > as[i+1]) { ret[i] = ret[i-1] == 5 ? 4 : 5; } else if (as[i-1] > as[i] && as[i] > as[i+1]) { ret[i] = ret[i-1] - 1; } } if (as.length > 1) { if (as[as.length - 1] > as[as.length - 2]) { if (ret[as.length - 2] == 5) return "-1"; ret[as.length - 1] = 5; } else if (as[as.length - 1] == as[as.length - 2]) { ret[as.length - 1] = ret[as.length - 2] == 5 ? 4 : 5; } else { if (ret[as.length - 2] == 1) return "-1"; ret[as.length - 1] = 1; } } StringBuilder sb = new StringBuilder(); for (int b : ret) { sb.append(b); sb.append(" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } }
linear
1032_C. Playing Piano
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; 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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); E solver = new E(); solver.solve(1, in, out); out.close(); } static class E { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.ni(), K = in.ni(); long mod = 998244353; long[][] dp = new long[n + 1][n + 1]; for (int lim = 1; lim <= n; lim++) { long sum = 1; dp[0][lim] = 1; for (int i = 1; i <= n; i++) { dp[i][lim] = (dp[i][lim] + sum) % mod; sum = (sum + dp[i][lim]) % mod; if (i >= lim) sum = (sum - dp[i - lim][lim] + mod) % mod; } } long ans = 0; for (int k = 1; k < Math.min(K, n + 1); k++) { long h = dp[n][k] - dp[n][k - 1]; int lim = K / k; if (K % k == 0) lim--; if (lim > n) lim = n; ans += dp[n][lim] * h % mod; } out.println(2 * ans % mod); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int ni() { return Integer.parseInt(ns()); } } }
quadratic
1027_E. Inverse Coloring
CODEFORCES
import java.util.Scanner; public class A961_Tetris { public static void main(String[] args) { Scanner input = new Scanner(System.in); int platforms = input.nextInt(); int in = input.nextInt(); int[] cols = new int[platforms]; int[] squares = new int[in]; for (int i = 0; i < in; i ++) { squares[i] = input.nextInt(); } boolean hi = false; int score = 0; for (int i = 0; i < in; i ++) { cols[squares[i] - 1] ++; hi = checkscore(cols); if (hi == true) { hi = false; score ++; for (int j = 0; j < cols.length; j ++) { cols[j] --; } } } System.out.println(score); } public static boolean checkscore(int[] cols) { for (int i = 0; i < cols.length; i ++) { if (cols[i] == 0) { return false; } } return true; } }
quadratic
961_A. Tetris
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import static java.lang.Math.*; public class Main { private FastScanner scanner = new FastScanner(); public static void main(String[] args) { new Main().solve(); } private void solve() { int n = scanner.nextInt(); Map<Integer, Integer> cnt = new HashMap<>(); for (int i = 0; i < n; i++) { String s = scanner.nextLine(); LinkedList<Character> st = new LinkedList<>(); for (char c : s.toCharArray()) { if (c == ')' && !st.isEmpty() && st.getLast() == '(') { st.pollLast(); continue; } st.addLast(c); } int t = st.size(); Set<Character> set = new HashSet<>(st); if (set.size() > 1) { continue; } if (set.isEmpty()) { cnt.put(0, cnt.getOrDefault(0, 0) + 1); continue; } if (st.getLast() == '(') { cnt.put(t, cnt.getOrDefault(t, 0) + 1); } else { cnt.put(-t, cnt.getOrDefault(-t, 0) + 1); } } long ans = 0; for (int next : cnt.keySet()) { if (next == 0) { ans += (long) cnt.get(next) * (cnt.get(next) - 1) + cnt.get(next); } else if (next > 0) { int t = next * -1; if (cnt.containsKey(t)) { ans += (long) cnt.get(next) * cnt.get(t); } } } System.out.print(ans); } class FastScanner { BufferedReader reader; StringTokenizer tokenizer; FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } Integer[] nextA(int n) { Integer a[] = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } return a; } 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); } } } }
linear
990_C. Bracket Sequences Concatenation Problem
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{ long a; int i; public card(long a,int i) { this.a=a; this.i=i; } } static class sort implements Comparator<pair> { public int compare(pair o1,pair o2) { if(o1.a!=o2.a) return (int)(o1.a-o2.a); else return (int)(o1.b-o2.b); } } 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 boolean valid(int i,int j) { if(i<4 && i>=0 && j<4 && j>=0) return true; else return false; }*/ static class pair{ int a,b; public pair(int a,int b) { this.a=a; this.b=b; } } public static void main(String[] args) { InputReader sc=new InputReader(System.in); int k=sc.nextInt(); int n=sc.nextInt(); int s=sc.nextInt(); int p=sc.nextInt(); long d=(long)Math.ceil((double)n/s); if(d==0) d=1; d=k*d; long ans=(long)Math.ceil((double)d/p); System.out.println(ans); } }
constant
965_A. Paper Airplanes
CODEFORCES