src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.lang.reflect.Array; import java.math.*; import java.security.SecureRandom; public class WCS { public static class Vector implements Comparable <Vector> { long x, y; int position; Vector first, second; boolean toReverse; public Vector(long xx, long yy, int p) { x = xx; y = yy; position = p; first = null; second = null; toReverse = false; } public Vector negate() { Vector vv = new Vector(-x, -y, position); vv.first = first; vv.second = second; vv.toReverse = !toReverse; return vv; } public Vector add(Vector v) { Vector sum = new Vector(this.x + v.x, this.y + v.y, position); sum.first = this; sum.second = v; return sum; } public Vector subtract(Vector v) { return this.add(v.negate()); } public double euclideanNorm() { return Math.sqrt(x * x + y * y); } @Override public int compareTo(Vector v) { double thisa = Math.atan2(this.y, this.x); double va = Math.atan2(v.y, v.x); if(thisa < 0) thisa += 2 * Math.PI; if(va < 0) va += 2 * Math.PI; if(thisa < va) return -1; if(thisa > va) return 1; return Integer.compare(this.position, v.position); } @Override public String toString() { return x + " " + y; } } public static void dfs(Vector curr, int[] ans) { if(curr.first == null) { ans[curr.position] = curr.toReverse ? -1 : 1; return; } curr.first.toReverse ^= curr.toReverse; curr.second.toReverse ^= curr.toReverse; dfs(curr.first, ans); dfs(curr.second, ans); } public static boolean ok(Vector v1, Vector v2) { return v1.add(v2).euclideanNorm() <= Math.max(v1.euclideanNorm(), v2.euclideanNorm()); } public static void stop(long k) { long time = System.currentTimeMillis(); while(System.currentTimeMillis() - time < k); } public static void main(String[] args) throws IOException { int n = in.nextInt(); TreeSet <Vector> vectors = new TreeSet <> (); for(int i = 0; i < n; i ++) { Vector v = new Vector(in.nextLong(), in.nextLong(), i); vectors.add(v); } while(vectors.size() > 2) { //System.out.println(vectors); //stop(500); TreeSet <Vector> support = new TreeSet <> (); while(vectors.size() > 0) { Vector curr = vectors.pollFirst(); Vector next1 = vectors.higher(curr); Vector next2 = vectors.lower(curr.negate()); Vector next3 = vectors.higher(curr.negate()); Vector next4 = vectors.lower(curr); //System.out.println("CURR: " + curr + "\n" + next1 + "\n" + next2); if(next1 != null) { if(ok(curr, next1)) { support.add(curr.add(next1)); vectors.remove(next1); continue; } } if(next1 != null) { if(ok(curr, next1.negate())) { support.add(curr.subtract(next1)); vectors.remove(next1); continue; } } if(next2 != null) { if(ok(curr, next2)) { support.add(curr.add(next2)); vectors.remove(next2); continue; } } if(next2 != null) { if(ok(curr, next2.negate())) { support.add(curr.subtract(next2)); vectors.remove(next2); continue; } } if(next3 != null) { if(ok(curr, next3)) { support.add(curr.add(next3)); vectors.remove(next3); continue; } } if(next3 != null) { if(ok(curr, next3.negate())) { support.add(curr.subtract(next3)); vectors.remove(next3); continue; } } if(next4 != null) { if(ok(curr, next4)) { support.add(curr.add(next4)); vectors.remove(next4); continue; } } if(next4 != null) { if(ok(curr, next4.negate())) { support.add(curr.subtract(next4)); vectors.remove(next4); continue; } } support.add(curr); } vectors = support; } if(vectors.size() == 2) { Vector curr = vectors.pollFirst(); Vector next = vectors.pollFirst(); Vector add = curr.add(next); Vector sub = curr.subtract(next); if(sub.euclideanNorm() <= add.euclideanNorm()) vectors.add(sub); else vectors.add(add); } //System.out.println(vectors.first().euclideanNorm()); StringBuilder buffer = new StringBuilder(); int[] ans = new int[n]; dfs(vectors.pollFirst(), ans); for(int i = 0; i < n; i ++) buffer.append(ans[i] + " "); System.out.println(buffer); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } BigInteger nextBigInteger() { return new BigInteger(in.next()); } int nextInt() { return Integer.parseInt(next()); } char nextChar() { return in.next().charAt(0); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader in = new FastReader(); static OutputStream out = new BufferedOutputStream(System.out); public static byte[] toByte(Object o) { return String.valueOf(o).getBytes(); } public static void sop(Object o) { System.out.print(o); } }
nlogn
995_C. Leaving the Bar
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class A { public void run() throws IOException { final int n = IOFast.nextInt(); int[] xs = new int[n]; for(int i = 0; i < n; i++) { xs[i] = IOFast.nextInt(); } int[] ys = xs.clone(); Random random = new Random(); for(int i = 0; i < n; i++) { final int j = random.nextInt(i + 1); final int t = ys[j]; ys[j] = ys[i]; ys[i] = t; } Arrays.sort(ys); int diff = 0; for(int i = 0; i < ys.length; i++) { if(xs[i] != ys[i]) { diff++; } } IOFast.out.println(diff > 2 ? "NO" : "YES"); } public static void main(String[] args) throws IOException { new A().run(); IOFast.out.flush(); } static public class IOFast { private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out); // private static final int BUFFER_SIZE = 50 * 200000; private static int pos, readLen; private static final char[] buffer = new char[1024 * 8]; private static final StringBuilder buf = new StringBuilder(); private static boolean[] isDigit = new boolean[256]; private static boolean[] isSpace = new boolean[256]; static { for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; } static boolean endInput; private static int read() throws IOException { if(readLen == -1) { return -1; } if(pos >= readLen) { readLen = in.read(buffer); pos = 0; if(readLen <= 0) { return -1; } } return buffer[pos++]; } private static int nextInt() throws IOException { boolean plus = false; int ret = 0; while(true) { final int c = read(); if(c == -1) { endInput = true; return Integer.MIN_VALUE; } if(isDigit[c]) { if(c != '-') { plus = true; ret = c - '0'; } break; } } while(true) { final int c = read(); if(c == -1 || !isDigit[c]) { break; } ret = ret * 10 + c - '0'; } return plus ? ret : -ret; } private static long nextLong() throws IOException { boolean plus = false; long ret = 0; while(true) { final int c = read(); if(c == -1) { endInput = true; return Integer.MIN_VALUE; } if(isDigit[c]) { if(c != '-') { plus = true; ret = c - '0'; } break; } } while(true) { final int c = read(); if(c == -1 || !isDigit[c]) { break; } ret = ret * 10 + c - '0'; } return plus ? ret : -ret; } private static char nextChar() throws IOException { while(true) { final int c = read(); if(c == -1) { endInput = true; return '\0'; } if(!isSpace[c]) { return (char)c; } } } private static int next(char[] cs) throws IOException { int n = 0; while(true) { final int c = read(); if(c == -1) { endInput = true; return n; } if(!isSpace[c]) { cs[n++] = (char)c; break; } } while(true) { final int c = read(); if(c == -1 || isSpace[c]) { break; } cs[n++] = (char)c; } return n; } private static String next() throws IOException { buf.setLength(0); while(true) { final int c = read(); if(c == -1) { endInput = true; return "-1"; } if(!isSpace[c]) { buf.append((char)c); break; } } while(true) { final int c = read(); if(c == -1 || isSpace[c]) { break; } buf.append((char)c); } return buf.toString(); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { public void solve() throws Exception { int n = nextInt(); int a [] = new int [n]; for (int i = 0 ;i < n; i++) { a[i] = nextInt(); } Arrays.sort(a); if (n == 1) { if (a[0] == 1) { out.print(2); } else { out.print(1); } } else { out.print(1); for (int i = 1; i < n; i++) { if (i == n-1 && a[i] == 1) { out.print(" "+2); } else { out.print(" "+a[i-1]); } } } } /********************************************************************************************/ /* THERE IS INPUT */ BufferedReader in; PrintWriter out; StringTokenizer st; long stime=0; private String next() throws Exception { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } private int nextInt() throws Exception { return Integer.parseInt(next()); } private long nextLong() throws Exception { return Long.parseLong(next()); } private double nextDouble() throws Exception { return Double.parseDouble(next()); } public void run() { try { //Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { out.close(); } } public static void main(String[] args) throws Exception { new Thread(null, new Solution(), "", 1 << 25).start(); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; public class B { static ArrayList<Integer> [] adj; static int [] num; static int dfs(int u, int p){ int cnt = 0; for(int v:adj[u]){ if(v != p) cnt += dfs(v, u); } if(adj[u].size() == 1 && u != 0 || u == 0 && adj[0].size() == 0) cnt++; num[cnt]++; return cnt; } public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); adj = new ArrayList[n]; for (int i = 0; i < adj.length; ++i) { adj[i] = new ArrayList<>(); } for (int i = 1; i < n; ++i) { int p = sc.nextInt()-1; adj[p].add(i); adj[i].add(p); } num = new int[n+1]; dfs(0, -1); for (int i = 1; i < num.length; ++i) { num[i] += num[i-1]; } int cur = 1; for (int i = 0; i < num.length; ++i) { while(cur <= num[i]){ out.print(i + " "); ++cur; } } out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } } }
linear
1056_D. Decorate Apple Tree
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.StringTokenizer; public class Main implements Runnable { static Throwable sError; public static void main(String[] args) throws Throwable { Thread t = new Thread(new Main()); t.start(); t.join(); if (sError != null) throw sError; } PrintWriter pw; BufferedReader in; StringTokenizer st; void initStreams() throws FileNotFoundException, UnsupportedEncodingException { pw = new PrintWriter(System.out); if (System.getProperty("ONLINE_JUDGE") == null) { System.setIn(new FileInputStream("1")); } in = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-9")); } String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextString()); } public void run() { try { initStreams(); double a = nextDouble(), vmax = nextDouble(), l = nextDouble(), d = nextDouble(), w = nextDouble(); if (vmax <= w) { double v = Math.sqrt(2 * a * l); if (v <= vmax) { out(v / a); } else { double s = vmax * vmax / (2 * a); double t = (l - s) / vmax; out(vmax / a + t); } } else { double v = Math.sqrt(a * d + w * w / 2); double t1 = 0; if (w <= Math.sqrt(2 * a * d)) { if (v <= vmax) { t1 = v / a + (v - w) / a; } else { double s = d - vmax * vmax / (2 * a) - (vmax * vmax - w * w) / (2 * a); t1 = s / vmax + vmax / a + (vmax - w) / a; } } else { t1 = Math.sqrt(2 * d / a); w = a * t1; } v = Math.sqrt(2 * a * (l - d) + w * w); double t2 = 0; if (v <= vmax) { t2 = (v - w) / a; } else { double s = l - d - (vmax * vmax - w * w) / (2 * a); t2 = (vmax - w) / a + s / vmax; } out(t1 + t2); } } catch (Throwable e) { sError = e; } finally { pw.flush(); pw.close(); } } private void out(double t) { pw.println(t); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class A{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int mod=(int)1e9+9; long n, m, k; void run(){ n=sc.nextLong(); m=sc.nextLong(); k=sc.nextLong(); solve(); } void solve(){ long ans=0; long s=n-m; long remain=max(n-s*k, 0); // debug("remain", remain); ans=m-remain; // debug("ans", ans); long r=remain%k; ans=(ans+r)%mod; remain-=r; // debug("remain2", remain); long a=remain/k; long add=(powMod(2, a, mod)-1)*k%mod*2%mod; // debug("add", add); ans=(ans+add)%mod; // debug(ans); println(ans+""); } long powMod(long x, long k, long mod){ if(k==0){ return 1%mod; }else if(k%2==0){ return powMod(x*x%mod, k/2, mod); }else{ return x*powMod(x, k-1, mod)%mod; } } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } public static void main(String[] args){ Locale.setDefault(Locale.US); new A().run(); } }
logn
338_A. Quiz
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main { private static Node[] node; public static void main(String[] args) { Scanner cin = new Scanner(System.in); int ret = 2, del; int n = cin.nextInt(); int t = cin.nextInt() * 2; node = new Node[n]; for (int i = 0; i < n; i++) { int x = cin.nextInt(); int a = cin.nextInt(); node[i] = new Node(x * 2 - a, x * 2 + a); } Arrays.sort(node); for (int i = 1; i < n; i++) { del = node[i].l - node[i - 1].r; if (del > t) { ret += 2; } else if (del == t) { ret++; } } System.out.println(ret); } private static class Node implements Comparable<Node> { public int l; public int r; public Node(int l, int r) { // TODO Auto-generated constructor stub this.l = l; this.r = r; } @Override public int compareTo(Node arg0) { // TODO Auto-generated method stub return l - arg0.l; } } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; /** @author KhanhNguyenn */ public class C{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver // sub-problem: 2 orders to merge together x1,x2,..,xn and y1,y2,..,ym // Dựa vào bài toán chia kẹp Euler, ta chứng minh dc số cách merge là // (m+n)C(m-1)=(m+n)C(n+1) static class Task{ int M; public void solve(InputReader in, PrintWriter out) { int n= in.nextInt(); M= in.nextInt(); if(n<=1){ out.println(n); return; } // calculate nCk // nCk= (n-1)C(k-1)+ (n-1)Ck int[][] Ckn= new int[n+1][n+1]; for(int i=0;i<=n;i++){ Ckn[i][i]=1; Ckn[0][i]=1; for(int j=i-1;j>=1;j--){ Ckn[j][i]= add(Ckn[j-1][i-1],Ckn[j][i-1]); } } int ans=0; int[][] dp= new int[n+1][n+1]; dp[1][1]=1; //dp[i][j]: number of ways to turn on first i , using j manually for(int i=2;i<=n;i++){ dp[i][i]= mul(2,dp[i-1][i-1]); for(int j=1;j<=i-1;j++){ for(int k=1;k<=j;k++){ dp[i][j]= add(dp[i][j],mul(mul(dp[k][k],dp[i-k-1][j-k]),Ckn[k][j])); } } } for(int i=0;i<=n;i++) ans= add(ans,dp[n][i]); out.println(ans); } public int add(int a, int b){ a+=b; if(a>=M) a-=M; return a; } public int mul(int a, int b){ long res= (long)a*(long)b; res %=M; return (int)res; } } static class Pair { public String x; public int y; public Pair(String x, int y){ this.x = x; this.y=y; } // @Override // public int compareTo(Pair o) { // if (this.x > o.x){ // return 1; // } // else if (this.x < o.x){ // return -1; // } // else{ // return Integer.compare(this.y, o.y); // } // } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.io.*; import java.util.*; public class D11 { static HashMap<State, Integer> map; static long[][] ans; static boolean[][] connect; 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()); map = new HashMap<State, Integer>(); connect = new boolean[n][n]; ans = new long[n][1<<n]; for(int i = 0; i < n; i++) Arrays.fill(ans[i], -1); int m = Integer.parseInt(st.nextToken()); while(m-- > 0) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); a--; b--; connect[a][b] = connect[b][a] = true; } long ret = 0; int mask = 1 << n; mask--; for(int i = 0; i < n; i++) { for(int out = i+1; out < n; out++) { if(connect[i][out]) { ret += solve(mask - (1<<out), out, true); } } mask -= (1<<i); } System.out.println(ret/2); } public static long solve(int mask, int start, boolean a) { if(ans[start][mask] != -1) return ans[start][mask]; int end = 0; while((mask & (1<<end)) == 0) end++; long ret = 0; for(int out = 0; out < connect.length; out++) { if(connect[start][out] && (mask & (1 << out)) != 0) { if(out == end) { if(!a) ret++; } else ret += solve(mask - (1<<out), out, false); } } ans[start][mask] = ret; return ret; } static class State { public byte start, go; public int mask; public State(byte a, byte b, int c) { start = a; go = b; mask = c; } public int hashCode() { return 10007*mask + 43 * start + go; } public boolean equals(Object o) { State s = (State)o; return start == s.start && go == s.go && mask == s.mask; } } }
np
11_D. A Simple Task
CODEFORCES
//package round429; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class C2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); for(int i = 0;i < n;i++){ int v = a[i]; for(int j = 2;j*j <= v;j++){ while(v % (j*j) == 0){ v /= j*j; } } a[i] = v; } Arrays.sort(a); int[] f = new int[n]; int p = 0; for(int i= 0;i < n;i++){ if(i > 0 && a[i] != a[i-1]){ p++; } f[p]++; } f = Arrays.copyOf(f, p+1); int mod = 1000000007; int[][] fif = enumFIF(1000, mod); long[] res = countSameNeighborsSequence(f, fif, mod); long ans = res[0]; for(int v : f){ ans = ans * fif[0][v] % mod; } out.println(ans); } public static int[][] enumFIF(int n, int mod) { int[] f = new int[n + 1]; int[] invf = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; i++) { f[i] = (int) ((long) f[i - 1] * i % mod); } long a = f[n]; long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } invf[n] = (int) (p < 0 ? p + mod : p); for (int i = n - 1; i >= 0; i--) { invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod); } return new int[][] { f, invf }; } public static long[] countSameNeighborsSequence(int[] a, int[][] fif, int mod) { int n = a.length; int bef = a[0]; int aft = a[0]; long[] dp = new long[bef]; dp[bef-1] = 1; for(int u = 1;u < n;u++){ int v = a[u]; aft += v; long[][] ldp = new long[bef][aft]; for(int i = 0;i < dp.length;i++){ ldp[i][0] = dp[i]; } for(int i = 0;i < v;i++){ long[][] ndp = new long[bef][aft]; for(int j = 0;j < bef;j++){ for(int k = 0;j+k < aft;k++){ if(ldp[j][k] == 0)continue; // XX -> XCX if(j > 0){ ndp[j-1][k] += ldp[j][k] * j; ndp[j-1][k] %= mod; } // CC -> CCC // XC -> XCC // #XC = 2*(i-k) ndp[j][k+1] += ldp[j][k] * (2*i-k); ndp[j][k+1] %= mod; // XY -> XCY // #XY = bef+i+1-#XC-#CC-#XX ndp[j][k] += ldp[j][k] * (bef+i+1-j-k-2*(i-k)); ndp[j][k] %= mod; } } ldp = ndp; } dp = new long[aft]; for(int j = 0;j < bef;j++){ for(int k = 0;j+k < aft;k++){ dp[j+k] += ldp[j][k]; if(dp[j+k] >= mod)dp[j+k] -= mod; } } for(int j = 0;j < aft;j++)dp[j] = dp[j] * fif[1][v] % mod; bef = aft; } return dp; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C2().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private 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++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { 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 * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int 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 * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class pr988B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); ArrayList<String> a = new ArrayList<>(); for (int i = 0; i < n; i++) { a.add(br.readLine()); } if(solve(n, a)){ out.println("YES"); for (String s : a) { out.println(s); } } else out.println("NO"); out.flush(); out.close(); } private static boolean solve(int n, ArrayList<String> a) { a.sort(Comparator.comparingInt(String::length)); for (int i = 0; i < n - 1; i++) { if(!a.get(i+1).contains(a.get(i))) return false; } return true; } }
nlogn
988_B. Substrings Sort
CODEFORCES
import java.io.*; import java.util.*; public class A { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); Arrays.sort(a); int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; int cur = 0; for (int i = n - 1; i >= 0; i--) { cur += a[i]; if (cur > sum - cur) { out.println(n - i); return; } } } void inp() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new A().inp(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "0"; } } return st.nextToken(); } String nextString() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "0"; } } return st.nextToken("\n"); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
nlogn
160_A. Twins
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; public class C { private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static PrintStream out = System.out; public static void main(String[] args) throws NumberFormatException, IOException { int n = Integer.parseInt(in.readLine()); char[] s = in.readLine().toCharArray(); HashSet<Character> all = new HashSet<Character>(); for (char c : s) all.add(c); int totalCount = all.size(); HashMap<Character, Integer> cnts = new HashMap<Character, Integer>(); int ans = Integer.MAX_VALUE; int x = 0; for (int y = 0; y < n; ++y) { if (!cnts.containsKey(s[y])) cnts.put(s[y], 0); cnts.put(s[y], cnts.get(s[y]) + 1); if (cnts.size() < totalCount) continue; while (cnts.get(s[x]) > 1) { cnts.put(s[x], cnts.get(s[x]) - 1); ++x; } ans = Math.min(ans, y - x + 1); } out.println(ans); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); if (n % 4 == 0 || n % 7 == 0 || n % 47 == 0 || n % 77 == 0 || n % 74 == 0 || n % 447 == 0 || n % 474 == 0 || n % 477 == 0 || n % 747 == 0 || n % 774 == 0 || n % 777 == 0) System.out.println("YES"); else System.out.println("NO"); } }
constant
122_A. Lucky Division
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.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author phantom11 */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { long MOD = (long) 1e9 + 7; long[][] dp; int[] a; public void solve(int testNumber, InputReader in, OutputWriter out) { int N = in.nextInt(); a = new int[N]; dp = new long[N][N]; int i; for (i = 0; i < N; i++) { char c = in.nextChar(); if (c == 'f') { a[i] = 1; } } out.printLine(iterative()); // for(i=0;i<=N;i++) { // Arrays.fill(dp[i], -1); // } // out.printLine(recur(0, 0)); } public long iterative() { int i, j, N = a.length, lastLevel = 0; dp[0][0] = 1; for (i = 1; i < N; i++) { if (a[i - 1] == 1) { lastLevel++; for (j = 1; j <= lastLevel; j++) { dp[i][j] = dp[i - 1][j - 1]; } } else { dp[i][N - 1] = dp[i - 1][N - 1]; for (j = N - 2; j >= 0; j--) { dp[i][j] = (dp[i][j + 1] + dp[i - 1][j]) % MOD; } } } long ans = 0; for (i = 0; i < N; i++) { ans += dp[N - 1][i]; } return ans % MOD; } } static class InputReader { BufferedReader in; StringTokenizer tokenizer = null; public InputReader(InputStream inputStream) { in = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (IOException e) { return null; } } public int nextInt() { return Integer.parseInt(next()); } public char nextChar() { return next().charAt(0); } } 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 print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
quadratic
909_C. Python Indentation
CODEFORCES
/* * The MIT License * * Copyright 2016 Mouad NACIRI <mouadnaciri1@gmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.IOException; import java.util.StringTokenizer; /** * * @author NACIRI Mouad <mouadnaciri1@gmail.com> * @version 1.5.1 */ public class MainA { /* VIP, DON'T TOUCH!! */ static StringTokenizer ST; static BufferedReader IN; static BufferedWriter OUT; static { IN = new BufferedReader(new InputStreamReader(System.in)); OUT = new BufferedWriter(new OutputStreamWriter(System.out)); } public static void main(String[] args) throws IOException { pl("25"); cAll(); } //IO stuff... static void ll() throws IOException { ST = new StringTokenizer(nlnt()); } static void ll(String del) throws IOException { ST = new StringTokenizer(nlnt(), del); } static void ll(String s, String del) throws IOException { ST = new StringTokenizer(s, del); } static void ll(String s, char c) throws IOException { ST = new StringTokenizer(s); } static int tlen() { return ST.countTokens(); } static boolean hn() { return ST.hasMoreTokens(); } static String n() throws IOException { return ST.nextToken(); } static String nln() throws IOException { String l; while((l = IN.readLine()) != null && l.trim().length() == 0) {} return l; } static String nlnt() throws IOException { String l; while((l = IN.readLine()) != null && (l = l.trim()).length() == 0) {} return l; } static boolean nbl() throws IOException { return Boolean.parseBoolean(ST.nextToken()); } static byte nb() throws IOException { return Byte.parseByte(ST.nextToken()); } static byte nb(int radix) throws IOException { return Byte.parseByte(ST.nextToken(), radix); } static double nd() throws IOException { return Double.parseDouble(ST.nextToken()); } static float nf() throws IOException { return Float.parseFloat(ST.nextToken()); } static int ni() throws IOException { return Integer.parseInt(ST.nextToken()); } static int ni(int radix) throws IOException { return Integer.parseInt(ST.nextToken(), radix); } static long nl() throws IOException { return Long.parseLong(ST.nextToken()); } static long nl(int radix) throws IOException { return Long.parseLong(ST.nextToken(), radix); } static short ns() throws IOException { return Short.parseShort(ST.nextToken()); } static short ns(int radix) throws IOException { return Short.parseShort(ST.nextToken(), radix); } static void p(String s) throws IOException { OUT.write(s); } static void p(char c) throws IOException { OUT.write(c); } static void p(char s[]) throws IOException { OUT.write(s); } static void pl(String s) throws IOException { OUT.write(s); OUT.newLine(); } static void pl(char c) throws IOException { OUT.write(c); OUT.newLine(); } static void pl(char s[]) throws IOException { OUT.write(s); OUT.newLine(); } static void pl() throws IOException { OUT.newLine(); } static void cAll() throws IOException { IN.close(); OUT.close(); } }
constant
630_A. Again Twenty Five!
CODEFORCES
//~~~~~~~~~~~~~~~~~~~~~~~@@@@@@@@@@@@@@@_____________K_____S_____J__________@@@@@@@@@@@@@@@@@@@@@@@@@@@@~~~~~~~~~~~~~~~~~~~~~~~~~~ //Date:00/00/17 //------------- import java.util.*; import java.io.*; /* [[[[[[[[[[[[[[[ ]]]]]]]]]]]]]]] [:::::::::::::: ::::::::::::::] [:::::::::::::: ::::::::::::::] [::::::[[[[[[[: :]]]]]]]::::::] [:::::[ ]:::::] [:::::[ ]:::::] [:::::[ ]:::::] [:::::[ ]:::::] [:::::[ CODE YOUR LIFE ]:::::] [:::::[ Kripa Shankar jha ]:::::] [:::::[ ]:::::] [:::::[ ]:::::] [:::::[ ]:::::] [:::::[ ]:::::] [::::::[[[[[[[: :]]]]]]]::::::] [:::::::::::::: ::::::::::::::] [:::::::::::::: ::::::::::::::] [[[[[[[[[[[[[[[ ]]]]]]]]]]]]]]] */ public class prob3{ static Parser sc=new Parser(System.in); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static int p[]=new int[100005]; public static void main(String[] args) throws IOException { // use ((((((( sc ............... for input int n=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } int swap=0; for(int i=0;i<n;i++){ for(int j=0;j<i;j++){ if(arr[i]<arr[j]){ swap++; } } } swap%=2; int m=sc.nextInt(); for(int i=0;i<m;i++){ int a=sc.nextInt(),b=sc.nextInt(); swap+=((b-a)*((b-a)+1))/2; swap%=2; if(swap%2==0){System.out.println("even");} else{System.out.println("odd");} } } public static void union(int a,int b){ int i=find(a); int j=find(b); if(p[i]!=j){ p[i]=j; } } public static int find(int a){ while(p[a]!=a){ a=p[a]; } return a; } //___________________________Fast-Input_Output-------------------******************* static class Parser { final private int BUFFER_SIZE = 1 << 20; // 2^16, a good compromise for some problems private InputStream din; // Underlying input stream private byte[] buffer; // Self-maintained buffer private int bufferPointer; // Current read position in the buffer private int bytesRead; // Effective bytes in the buffer read from the input stream private SpaceCharFilter filter; public Parser(InputStream in) { din = in; buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } /** * Read the next integer from the input stream. * @return The next integer. * @throws IOException */ public int nextInt() throws IOException { int result = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); while (c >= '0' && c <= '9') { result = result * 10 + c - '0'; c = read(); } if (neg) return -result; return result; } public int nextLong() throws IOException { int result = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); while (c >= '0' && c <= '9') { result = result * 10 + c - '0'; c = read(); } if (neg) return -result; return result; } public String nextLine()throws IOException { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)==true); 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); } /** * Read the next byte of data from the input stream. * @return the next byte of data, or -1 if the end of the stream is reached. * @throws IOException if an I/O error occurs. */ public byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } /** * Read data from the input stream into the buffer * @throws IOException if an I/O error occurs. */ private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.math.BigInteger; 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); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { long n = in.nextLong(); long x = in.nextLong(); long y = in.nextLong(); long c = in.nextLong(); long tl, tr, tt = -1, t; tl = 0; tr = (long) 4e9; while(tl<tr){ t = (tl+tr)>>1; long cc = f(n, t, x, y); if(cc>=c){ tt = t; tr = t; }else tl = t+1; } out.writeln(tt); } public static long f(long n, long t, long x, long y){ long res = (t*t+t)/2 * 4 + 1; long s; if(x-t<1){ s = t-x+1; res -= s*s; } if(y-t<1){ s = t-y+1; res -= s*s; } if(x+t>n){ s = x+t-n; res -= s*s; } if(y+t>n){ s = y+t-n; res -= s*s; } s = t-(Math.abs(x-1)+Math.abs(y-1))-1; if(s>0) res+=(s*s+s)/2; s = t-(Math.abs(x-1)+Math.abs(n-y))-1; if(s>0) res+=(s*s+s)/2; s = t-(Math.abs(n-x)+Math.abs(n-y))-1; if(s>0) res+=(s*s+s)/2; s = t-(Math.abs(n-x)+Math.abs(y-1))-1; if(s>0) res+=(s*s+s)/2; return res; } } class InputReader{ private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); 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 long nextLong(){ return Long.parseLong(next()); } } class OutputWriter{ private PrintWriter out; public OutputWriter(Writer out){ this.out = new PrintWriter(out); } public OutputWriter(OutputStream out){ this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out))); } public void write(Object ... o){ for(Object x : o) out.print(x); } public void writeln(Object ... o){ write(o); out.println(); } public void close(){ out.close(); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Arrays; public class CF1209E2 { public static void main(String[] args) throws Exception { boolean local = System.getSecurityManager() == null; boolean async = false; Charset charset = Charset.forName("ascii"); FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset); Task task = new Task(io, new Debug(local)); if (async) { Thread t = new Thread(null, task, "dalt", 1 << 27); t.setPriority(Thread.MAX_PRIORITY); t.start(); t.join(); } else { task.run(); } if (local) { io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M"); } io.flush(); } public static class Task implements Runnable { final FastIO io; final Debug debug; int inf = (int) 1e8; public Task(FastIO io, Debug debug) { this.io = io; this.debug = debug; } @Override public void run() { int t = io.readInt(); while (t-- > 0) solve(); } int[][] prefix = new int[12][1 << 12]; int[][] profits = new int[12][1 << 12]; Col[] cols = new Col[2000]; { for (int i = 0; i < 2000; i++) { cols[i] = new Col(12); } } public void solve() { int n = io.readInt(); int m = io.readInt(); for (int i = 0; i < m; i++) { cols[i].max = 0; cols[i].n = n; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cols[j].data[i] = io.readInt(); cols[j].max = Math.max(cols[j].max, cols[j].data[i]); } } Arrays.sort(cols, 0, m, (a, b) -> -(a.max - b.max)); Col[] cols = Arrays.copyOf(this.cols, Math.min(m, n)); int mask = (1 << n) - 1; SubsetGenerator sg = new SubsetGenerator(); SubsetGenerator2 sg2 = new SubsetGenerator2(); BitOperator bo = new BitOperator(); for (int i = 0; i < cols.length; i++) { Arrays.fill(profits[i], 0); for (int j = 0; j < n; j++) { cols[i].rotate(); for (int k = 0; k < n; k++) { sg2.values[k] = cols[i].data[k]; } sg2.setSet(mask); while (sg2.hasNext()) { profits[i][sg2.next] = Math.max(profits[i][sg2.next], sg2.val); sg2.next(); } } } prefix[0] = profits[0]; for (int i = 1; i < cols.length; i++) { for (int j = 0; j <= mask; j++) { sg.setSet(j); prefix[i][j] = prefix[i - 1][j]; while (sg.hasNext()) { int next = sg.next(); prefix[i][j] = Math.max(prefix[i][j], profits[i][next] + prefix[i - 1][j ^ next]); } } } io.cache.append(prefix[cols.length - 1][mask]).append('\n'); } } /** * Bit operations */ public static class BitOperator { public int bitAt(int x, int i) { return (x >> i) & 1; } public int bitAt(long x, int i) { return (int) ((x >> i) & 1); } public int setBit(int x, int i, boolean v) { if (v) { x |= 1 << i; } else { x &= ~(1 << i); } return x; } public long setBit(long x, int i, boolean v) { if (v) { x |= 1L << i; } else { x &= ~(1L << i); } return x; } /** * Determine whether x is subset of y */ public boolean subset(long x, long y) { return intersect(x, y) == x; } /** * Merge two set */ public long merge(long x, long y) { return x | y; } public long intersect(long x, long y) { return x & y; } public long differ(long x, long y) { return x - intersect(x, y); } } public static class SubsetGenerator2 { private int[] meanings = new int[33]; private int[] values = new int[33]; private int[] bits = new int[33]; private int remain; private int next; private int val; public void setSet(int set) { int bitCount = 0; while (set != 0) { meanings[bitCount] = set & -set; bits[bitCount] = 0; set -= meanings[bitCount]; bitCount++; } remain = 1 << bitCount; next = 0; val = 0; } public boolean hasNext() { return remain > 0; } private void consume() { remain = remain - 1; int i; for (i = 0; bits[i] == 1; i++) { bits[i] = 0; next -= meanings[i]; val -= values[i]; } bits[i] = 1; next += meanings[i]; val += values[i]; } public int next() { int returned = next; consume(); return returned; } } public static class SubsetGenerator { private int[] meanings = new int[33]; private int[] bits = new int[33]; private int remain; private int next; public void setSet(int set) { int bitCount = 0; while (set != 0) { meanings[bitCount] = set & -set; bits[bitCount] = 0; set -= meanings[bitCount]; bitCount++; } remain = 1 << bitCount; next = 0; } public boolean hasNext() { return remain > 0; } private void consume() { remain = remain - 1; int i; for (i = 0; bits[i] == 1; i++) { bits[i] = 0; next -= meanings[i]; } bits[i] = 1; next += meanings[i]; } public int next() { int returned = next; consume(); return returned; } } public static class Col { int[] data; int max; int n; public void rotate() { int end = data[n - 1]; System.arraycopy(data, 0, data, 1, n - 1); data[0] = end; } public Col(int n) { data = new int[n]; } } public static class FastIO { public final StringBuilder cache = new StringBuilder(1 << 13); private final InputStream is; private final OutputStream os; private final Charset charset; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastIO(InputStream is, OutputStream os, Charset charset) { this.is = is; this.os = os; this.charset = charset; } public FastIO(InputStream is, OutputStream os) { this(is, os, Charset.forName("ascii")); } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public long readLong() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } long val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public double readDouble() { boolean sign = true; skipBlank(); if (next == '+' || next == '-') { sign = next == '+'; next = read(); } long val = 0; while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } if (next != '.') { return sign ? val : -val; } next = read(); long radix = 1; long point = 0; while (next >= '0' && next <= '9') { point = point * 10 + next - '0'; radix = radix * 10; next = read(); } double result = val + (double) point / radix; return sign ? result : -result; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } public int readLine(char[] data, int offset) { int originalOffset = offset; while (next != -1 && next != '\n') { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(byte[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (byte) next; next = read(); } return offset - originalOffset; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } public void flush() throws IOException { os.write(cache.toString().getBytes(charset)); os.flush(); cache.setLength(0); } public boolean hasMore() { skipBlank(); return next != -1; } } public static class Debug { private boolean allowDebug; public Debug(boolean allowDebug) { this.allowDebug = allowDebug; } public void assertTrue(boolean flag) { if (!allowDebug) { return; } if (!flag) { fail(); } } public void fail() { throw new RuntimeException(); } public void assertFalse(boolean flag) { if (!allowDebug) { return; } if (flag) { fail(); } } private void outputName(String name) { System.out.print(name + " = "); } public void debug(String name, int x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, long x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, double x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, int[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, long[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, double[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, Object x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, Object... x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.deepToString(x)); } } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.io.*; import java.util.*; public class E2 { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader in; StringTokenizer tok; public void go() throws IOException { // long start = System.nanoTime(); // in = new BufferedReader(new FileReader(new File("input.txt"))); StringTokenizer tok = new StringTokenizer(in.readLine()); int zzz = Integer.parseInt(tok.nextToken()); for (int zz = 0; zz < zzz; zz++) { ntok(); int n = ipar(); int m = ipar(); int[][] mat = new int[m][n+1]; for (int i = 0; i < n; i++) { ntok(); for (int e = 0; e < m; e++) { mat[e][i] = ipar(); } } for (int i = 0; i < m; i++) { for (int e = 0; e < n; e++) { mat[i][n] = Math.max(mat[i][n], mat[i][e]); } } ArrayList<int[]> list = new ArrayList<>(); for (int i = 0; i < m; i++) { list.add(mat[i]); } Collections.sort(list, (a, b) -> { return -Integer.compare(a[n], b[n]); }); for (int i = 0; i < m; i++) { mat[i] = list.get(i); } m = Math.min(m, n); int[][] dp = new int[1 << n][m+1]; for (int i = m-1; i >= 0; i--) { int[] temp = new int[1 << n]; for (int r = 0; r < n; r++) { for (int j = 0; j < 1 << n; j++) { temp[j] = dp[j][i+1]; } for (int j = 0; j < n; j++) { int val = mat[i][(j+r)%n]; for (int k = 0; k < 1 << n; k++) { if ((k & (1 << j)) == 0) { temp[k | (1 << j)] = Math.max(temp[k | (1 << j)], temp[k] + val); } } } for (int j = 0; j < 1 << n; j++) { dp[j][i] = Math.max(dp[j][i], temp[j]); } } } out.println(dp[(1 << n) - 1][0]); // int[][] best = new int[1 << n][m]; // for (int i = 0; i < 1 << n; i++) // { // for (int e = 0; e < m; e++) // { // best[i][e] = best(i, mat, e); // } // } // int[][] dp = new int[1 << n][m+1]; // for (int i = 0; i < 1 << n; i++) // { // dp[i][m] = -1000000000; // } // dp[(1 << n) - 1][m] = 0; // for (int i = m-1; i >= 0; i--) // { // for (int e = 0; e < 1 << n; e++) // { // dp[e][i] = dp[e][i+1]; // int opposite = ~e & ((1 << n) - 1); // for (int w = opposite; w != 0; w = (w-1) & opposite) // { // dp[e][i] = Math.max(dp[e][i], best[w][i] + dp[e|w][i+1]); // } // } // } // out.println(dp[0][0]); } // out.printf("%.3f%n", (System.nanoTime() - start) / 1000000.0); out.flush(); in.close(); } public int best(int mask, int[][] mat, int col) { int max = 0; for (int t = 0; t < mat[0].length-1; t++) { int sum = 0; int mk = mask; for (int i = 0; i < mat[0].length-1; i++) { if (mk % 2 == 1) { sum += mat[col][(i+t)%(mat[0].length-1)]; } mk /= 2; } max = Math.max(max, sum); } return max; } public void cycle(int[][] mat, int col) { int temp = mat[col][0]; for (int i = 0; i < mat[0].length-2; i++) { mat[col][i] = mat[col][i+1]; } mat[col][mat[0].length-2] = temp; } public void ntok() throws IOException { tok = new StringTokenizer(in.readLine()); } public int ipar() { return Integer.parseInt(tok.nextToken()); } public int[] iapar(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ipar(); } return arr; } public long lpar() { return Long.parseLong(tok.nextToken()); } public long[] lapar(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = lpar(); } return arr; } public double dpar() { return Double.parseDouble(tok.nextToken()); } public String spar() { return tok.nextToken(); } public static void main(String[] args) throws IOException { new E2().go(); } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { public static void main(String args[]) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); IntStream.range(0, 1).forEach(tc -> { new Solver(tc, in, out).solve(); out.flush(); }); out.close(); } } class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.valueOf(next()); } double nextDouble() { return Double.valueOf(next()); } String nextLine() { try { return reader.readLine(); } catch (Exception e) { throw new RuntimeException(e); } } } class Solver { private InputReader in; private PrintWriter out; private Integer tc; Solver(Integer tc, InputReader in, PrintWriter out) { this.in = in; this.out = out; this.tc = tc; } void solve() { Integer n = in.nextInt(); TreeSet<Integer> list = IntStream.range(0, n) .map(i -> in.nextInt()) .boxed() .collect(Collectors.toCollection(TreeSet::new)); Integer answer = 0; while (!list.isEmpty()) { Integer x = list.pollFirst(); list = list.stream().filter(y -> y % x != 0).collect(Collectors.toCollection(TreeSet::new)); answer++; } out.println(answer); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; public class Task267A { public static void main(String... args) throws NumberFormatException, IOException { Solution.main(System.in, System.out); } static class Scanner { private final BufferedReader br; private String[] cache; private int cacheIndex; Scanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); cache = new String[0]; cacheIndex = 0; } int nextInt() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return Integer.parseInt(cache[cacheIndex++]); } String next() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return cache[cacheIndex++]; } void close() throws IOException { br.close(); } } static class Solution { public static void main(InputStream is, OutputStream os) throws NumberFormatException, IOException { PrintWriter pw = new PrintWriter(os); Scanner sc = new Scanner(is); int n = sc.nextInt(); while (n-- > 0) { int ai = sc.nextInt(); int bi = sc.nextInt(); int retVal = 0; while (ai > 0 && bi > 0) { if (ai > bi) { retVal += ai / bi; ai = ai % bi; } else { retVal += bi / ai; bi = bi % ai; } } pw.println(retVal); } pw.flush(); sc.close(); } } }
constant
267_A. Subtractions
CODEFORCES
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Solution { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.solve()); } private int solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[m]; for (int i = 0; i < m; ++i) a[i] = in.nextInt(); if (n > m) return 0; Map<Integer, Integer> map = new HashMap<>(); for (int k: a) map.put(k, map.getOrDefault(k, 0) + 1); List<Integer> keySet = new ArrayList<>(map.keySet()); int end = m / n; keySet.sort((u, v) -> -Integer.compare(u, v)); do { int count = 0; for (int k: keySet) { count += map.get(k) / end; if (count >= n) return end; } } while (--end > 0); return 0; } }
nlogn
1011_B. Planning The Expedition
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/14/11 * Time: 9:53 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.FileReader; import java.util.StringTokenizer; import java.io.IOException; import java.util.Arrays; public class Fish extends Thread { public Fish() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } static int getOnes(int mask) { int result = 0; while (mask != 0) { mask &= mask - 1; ++result; } return result; } private void solve() throws Throwable { int n = nextInt(); double[][] a = new double[n][n]; double[] dp = new double[(1 << n)]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { a[i][j] = nextDouble(); } } int limit = (1 << n) - 1; //dp[mask] = probability of current subset (mask) to remain in the end dp[limit] = 1.0; for (int mask = limit; mask > 0; --mask) { int cardinality = getOnes(mask); int probability = cardinality * (cardinality - 1) / 2; for (int first = 0; first < n; ++first) { if ((mask & powers[first]) != 0) { for (int second = first + 1; second < n; ++second) { if ((mask & powers[second]) != 0) { dp[mask - powers[first]] += dp[mask] * a[second][first] / probability; dp[mask - powers[second]] += dp[mask] * a[first][second] / probability; } } } } } for (int i = 0; i < n; ++i) { output.printf("%.10f ", dp[powers[i]]); } } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new Fish().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } static final int powers[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144}; private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
16_E. Fish
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class A { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String l[] = bf.readLine().split(" "); System.out.println(25); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.util.*; public class p343A { static long n = 0; static void resistance(long a, long b) { n += a/b; a %= b; if(a!=0) resistance(b, a); } public static void main(String[] args) { Scanner in = new Scanner(System.in); long a = in.nextLong(); long b = in.nextLong(); resistance(a, b); System.out.println(n); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.awt.*; import java.io.*; import java.math.*; import java.util.*; import static java.lang.Math.*; public class BetaRound81_B implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new BetaRound81_B(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } /** http://pastebin.com/j0xdUjDn */ static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static final int MAGIC_VALUE = 50; private static void mergeSort(int[] a, int leftIndex, int rightIndex) { if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } // solution int n, k, A; int[] b, l, c; void solve() throws IOException { n = readInt(); k = readInt(); A = readInt(); b = new int[n]; l = new int[n]; for (int i = 0; i < n; i++) { b[i] = readInt(); l[i] = readInt(); } c = new int[n]; rec(0, 0); out.printf("%.12f\n", ans); } double ans = 0; void rec(int sum, int i) { if (i > n) return; if (sum > k) return; if (i == n) { ans = max(ans, p()); return; } if (l[i] + c[i]*10 <= 100) { int can = min(k - sum, (100 - (l[i] + c[i]*10)) / 10); for (int set = can; set >= 0; set--) { c[i] += set; rec(sum + set, i + 1); c[i] -= set; } } } double p() { int n = c.length; int need = n / 2 + 1; int[] L = new int[n]; for (int i = 0; i < n; i++) { L[i] = l[i] + c[i]*10; if (L[i] > 100) { throw new RuntimeException(); } } double p = 0; for (int mask = 0; mask < (1 << n); mask++) { double q = 1; for (int i = 0; i < n; i++) { if (((1 << i) & mask) != 0) { q *= L[i] / 100.0; } else { q *= 1 - (L[i] / 100.0); } } if (q == 0) continue; if (Integer.bitCount(mask) >= need) { p += q; } else { int B = 0; for (int i = 0; i < n; i++) { if (((1 << i) & mask) == 0) { B += b[i]; } } double q2 = ((double) A) / (A + B); p += q * q2; } } return p; } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class C { private static double r, EPS=1e-10; public static void solve(FastScanner fs) { int n=fs.nextInt(); r=fs.nextInt(); int[] xCoords=fs.readArray(n); ArrayList<Point> placed=new ArrayList<>(); for (int x:xCoords) { double maxY=r; for (Point p:placed) maxY=Math.max(maxY, getNewY(p, x)); placed.add(new Point(x, maxY)); } for (Point p:placed) { System.out.printf("%.9f ", p.y); } } private static double getNewY(Point circleCenter, int x) { double dx=Math.abs(x-circleCenter.x); if (dx>r+r) return 0; if (dx<EPS) return circleCenter.y+r+r; double hypot=r+r; return circleCenter.y+Math.sqrt(hypot*hypot-(double)dx*dx); } static class Point { double x; double y; public Point(double x, double y) { this.x=x; this.y=y; } } public static void main(String[] args) throws NumberFormatException, IOException { FastScanner scanner = new FastScanner(System.in); solve(scanner); } private static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(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; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
quadratic
908_C. New Year and Curling
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 Liavontsi Brechka */ 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); DEhabIEsheOdnaOcherednayaZadachaNaXor solver = new DEhabIEsheOdnaOcherednayaZadachaNaXor(); solver.solve(1, in, out); out.close(); } static class DEhabIEsheOdnaOcherednayaZadachaNaXor { public void solve(int testNumber, InputReader in, PrintWriter out) { int c = 0; int d = 0; int prevSign = 0; int nextSign; boolean zeroOut = true; for (int i = 29; i >= 0; i--) { if (zeroOut) { print(c, d, out); prevSign = read(in); } print((1 << i) | c, (1 << i) | d, out); nextSign = read(in); if (prevSign == nextSign) { zeroOut = false; print((1 << i) | c, d, out); nextSign = read(in); if (nextSign < 0) { c = (1 << i) | c; d = (1 << i) | d; } } else { zeroOut = true; if (nextSign < 0) c = (1 << i) | c; else d = (1 << i) | d; } } out.printf("! %d %d", c, d); out.flush(); } private void print(int c, int d, PrintWriter out) { out.printf("? %d %d\n", c, d); out.flush(); } private int read(InputReader in) { return in.nextInt(); } } static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
logn
1088_D. Ehab and another another xor problem
CODEFORCES
import javafx.util.*; import java.util.*; import java.io.*; import java.math.*; public class Test4 { PrintWriter pw = new PrintWriter(System.out); InputStream is = System.in; Random rnd = new Random(); int a; void run(){ a = ni(); for(int q=0; q<a; q++){ long nj = ni(), kj = nl(); BigInteger n = BigInteger.valueOf(nj), k = BigInteger.valueOf(kj); if((nj<40 && (k.compareTo(BigInteger.valueOf(2).pow(2*(int)nj).divide(BigInteger.valueOf(3)))>0))){ System.out.println("NO"); continue; } if(nj>=40){ System.out.println("YES "+(nj-1)); continue; } long log=nj; BigInteger maxop = BigInteger.valueOf(2).pow(2*(int)nj).divide(BigInteger.valueOf(3)), pth = BigInteger.ONE; for(BigInteger c = BigInteger.ONE; log>0; log--, c=c.multiply(BigInteger.valueOf(2)).add(BigInteger.ONE)){ if(k.compareTo(c)<0) break; pth = c.multiply(BigInteger.valueOf(2)).add(BigInteger.ONE); k=k.subtract(c); maxop=maxop.subtract(c); } maxop = maxop.subtract(pth.multiply(BigInteger.valueOf(2).pow(2*(int)log).divide(BigInteger.valueOf(3)))); if(k.compareTo(maxop)<=0) System.out.println("YES "+log); else System.out.println("NO"); } pw.flush(); } static class PyraSort { private static int heapSize; public static void sort(int[] a) { buildHeap(a); while (heapSize > 1) { swap(a, 0, heapSize - 1); heapSize--; heapify(a, 0); } } private static void buildHeap(int[] a) { heapSize = a.length; for (int i = a.length / 2; i >= 0; i--) { heapify(a, i); } } private static void heapify(int[] a, int i) { int l = 2 * i + 2; int r = 2 * i + 1; int largest = i; if (l < heapSize && a[i] < a[l]) { largest = l; } if (r < heapSize && a[largest] < a[r]) { largest = r; } if (i != largest) { swap(a, i, largest); heapify(a, largest); } } private static void swap(int[] a, int i, int j) { a[i] ^= a[j] ^= a[i]; a[j] ^= a[i]; } } public static void main(String[] args) { new Test4().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private 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++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { 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 * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int 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 * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.util.*; import java.math.*; // **** B. Sport Mafia **** public class B { static char [] in = new char [1000000]; public static void main (String [] arg) throws Throwable { int n = nextInt(); int k = nextInt(); long ate = 0; long ans = -1; for (long i = 1; ans < 0; ++i) { long test = (i * (i+1)) / 2; if (test < k) continue; long adding_moves = i; long eating_moves = n-i; if (test - eating_moves == k) ans = eating_moves; } System.out.println(ans); } /************** HELPER CLASSES ***************/ //static class HS extends HashSet<Integer>{public HS(){super();}public HS(int a){super(a);}}; //static class AL extends ArrayList<Integer>{public AL(){super();}public AL(int a){super (a);}}; static class Pair implements Comparable<Pair> { int i,j;long L; public Pair(int xx, int yy, long LL){i=xx;j=yy;L=LL;} public int compareTo(Pair p) { return (this.L < p.L) ? -1 : ((this.L == p.L && this.i < p.i) ? -1 : 1);} } /************** FAST IO CODE FOLLOWS *****************/ public static long nextLong() throws Throwable { long i = System.in.read();boolean neg = false;while (i < 33) i = System.in.read();if (i == 45) {neg=true;i=48;}i = i - 48; int j = System.in.read();while (j > 32) {i*=10;i+=j-48;j = System.in.read();}return (neg) ? -i : i; } public static int nextInt() throws Throwable {return (int)nextLong();} public static String next() throws Throwable { int i = 0; while (i < 33 && i != -1) i = System.in.read(); int cptr = 0; while (i >= 33) { in[cptr++] = (char)i; i = System.in.read();} return new String(in, 0,cptr); } /**** LIBRARIES ****/ public static long gcdL(long a, long b) {while (b != 0) {long tmp = b;b = (a % b);a = tmp;}return a;} public static int gcd(int a, int b) {while (b != 0) {int tmp = b;b = (a % b);a = tmp;}return a;} public static int[] sieve(int LIM) { int i,count = 0; boolean [] b = new boolean [LIM]; for (i = 2;i<LIM; ++i) if (!b[i]) {count++; for (int j = i<<1; j<LIM; j+=i) b[j] = true;} int [] primes = new int[count]; for (i = 2,count=0;i<LIM;++i) if (!b[i]) primes[count++] = i; return primes; } public static int[] numPrimeFactors(int LIM) { int i,count = 0; int [] b = new int [LIM]; for (i = 2;i<LIM; ++i) if (b[i] == 0) {count++; for (int j = i; j<LIM; j+=i) b[j]++;} return b; } public static StringBuilder stringFromArray(int [] a) { StringBuilder b = new StringBuilder(9*a.length); for (int i = 0; i<a.length; ++i) { if (i != 0) b = b.append(' '); b = b.append(a[i]); } return b; } public static long modPow (long a, long n, long MOD) { long S = 1; for (;n > 0; n>>=1, a=(a*a)%MOD) if ((n & 1) != 0) S = (a*S) % MOD; return S;} } /* Full Problem Text: Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia. For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs n actions. The first action performed is to put a single candy into the box. For each of the remaining moves she can choose from two options: the first option, in case the box contains at least one candy, is to take exactly one candy out and eat it. This way the number of candies in the box decreased by 1; the second option is to put candies in the box. In this case, Alya will 1 more candy, than she put in the previous time. Thus, if the bank is empty, then it can only use the second option. For example, one possible sequence of Alya's actions look as follows: put one candy into the box; put two candies into the box; eat one candy from the box; eat one candy from the box; put three candies into the box; eat one candy from the box; put four candies into the box; eat one candy from the box; put five candies into the box; This way she will perform 9 actions, the of candies at the end will be 11, while Alya will eat 4 candies in total. You know the total number of actions n and the number of candies at the end k. You need to find the total number of sweets Alya ate. That is the number of moves of the second option. It's guaranteed, that for the given n and k the answer always exists. Please note, that during an action of the first option, Alya takes out and eats exactly one candy. */
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.*; public class Main { static int MAX = 1000; static BitSet P = new BitSet(MAX + 1); public static boolean Noldbach(int n) { n--; int j; for(int i=2; i<=n; i++) { if(!P.get(i)) { j = i + 1; while(P.get(j)) j++; if(i+j == n) { if(!P.get(i+j+1)) { //System.out.println((n+1)+" = "+i+" + "+(n-i)+" + 1"); return true; } } } } return false; } public static void main(String[] args) { Scanner lee = new Scanner(System.in); for(int i=2; i*i<=MAX; i++) { if(!P.get(i)) { for(int j=i+i; j<=MAX; j+=i) P.set(j); } } int n, k, c; n = lee.nextInt(); k = lee.nextInt(); c = 0; for(int i=2; i<=n; i++) { if(Noldbach(i)) c++; if(c == k) break; } if(c == k) System.out.println("YES"); else System.out.println("NO"); } }
linear
17_A. Noldbach problem
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/13/11 * Time: 6:10 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.io.IOException; public class DarkAssembly extends Thread { public DarkAssembly() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } static class Senator { int loyalty; int level; public Senator(int level, int loyalty) { this.level = level; this.loyalty = loyalty; } } private static double doIt(Senator[] senators, int A) { double probability = .0; for (int mask = 0; mask < (1 << senators.length); ++mask) { int sum = A; double current = 1.0; for (int i = 0; i < senators.length; ++i) { if ((mask & (1 << i)) != 0) { current *= .01 * senators[i].loyalty; } else { current *= .01 * (100 - senators[i].loyalty); sum += senators[i].level; } } if (getOnes(mask) > senators.length / 2) { probability += current; } else { probability += current * (double)A / sum; } } return probability; } private static double go(Senator []senators, int candies, int A, int current) { if (current == senators.length) { return doIt(senators, A); } else { double result = go(senators, candies, A, current + 1); if (candies > 0 && senators[current].loyalty < 100) { senators[current].loyalty += 10; result = Math.max(result, go(senators, candies - 1, A, current)); senators[current].loyalty -= 10; } return result; } } static int getOnes(int mask) { int result = 0; while (mask != 0) { mask &= mask - 1; ++result; } return result; } public void run() { try { int n = nextInt(); int k = nextInt(); int A = nextInt(); Senator[] senators = new Senator[n]; for (int i = 0; i < n; ++i) { senators[i] = new Senator(nextInt(), nextInt()); } output.printf("%.10f", go(senators, k, A, 0)); output.flush(); output.close(); } catch (Throwable e) { System.err.println(e.getMessage()); System.err.println(Arrays.deepToString(e.getStackTrace())); } } public static void main(String[] args) { new DarkAssembly().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class Main { public static void main(String[] args) throws IOException { // write your code here BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] s = reader.readLine().split(" "); int n = Integer.parseInt(s[0]); int d = Integer.parseInt(s[1]); List<Integer> list = new ArrayList<>(); s = reader.readLine().split(" "); for (int i = 0; i < n; i++) { list.add(Integer.parseInt(s[i])); } HashSet<Integer> set = new HashSet<>(); for (Integer i : list) { set.add(i - d); set.add(i + d); } HashSet<Integer> set2 = new HashSet<>(); for (Integer i : set) { for (Integer x : list) { if (Math.abs(i - x) < d) { set2.add(i); } } } set.removeAll(set2); System.out.println(set.size()); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.System.out; public class Main { private FastScanner scanner = new FastScanner(); public static void main(String[] args) { new Main().solve(); } private List<Integer>[] gr = new ArrayList[1000_000+5]; private int dp[][] = new int[21][1000_000+5]; private boolean used[] = new boolean[1000_000+5]; void init(int v, int p) { Stack<Integer> st = new Stack<>(); st.push(v); st.push(p); while (!st.isEmpty()) { p = st.pop(); v = st.pop(); used[v] = true; dp[0][v] = p; for (int i = 1; i <= 20; i++) { if (dp[i - 1][v] != -1) { dp[i][v] = dp[i - 1][dp[i - 1][v]]; } } for (int next : gr[v]) { if (!used[next]) { st.push(next); st.push(v); } } } } private void solve() { int n = scanner.nextInt(), k = scanner.nextInt(); boolean[] ans = new boolean[1000_000 + 5]; for (int i = 0; i < n; i++) { gr[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i ++) { int u = scanner.nextInt() - 1, v = scanner.nextInt() - 1; gr[u].add(v); gr[v].add(u); } k = n - k - 1; ans[n - 1] = true; init(n - 1 , n - 1); int t, d, next; for (int i = n - 2; i >= 0; i--) { t = i; d = 1; if (ans[i]) { continue; } for (int j = 20; j >= 0; j--){ next = dp[j][t]; if (next != -1 && !ans[next]) { t = next; d += 1 << j; } } if (d <= k) { k -=d; t = i; while (!ans[t]) { ans[t] = true; t = dp[0][t]; } } if (k == 0) { break; } } StringBuilder sb = new StringBuilder(""); for (int i = 0; i < n; i++) { if (!ans[i]) { sb.append(i + 1).append(" "); } } System.out.println(sb.toString()); } class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } }
nlogn
980_E. The Number Games
CODEFORCES
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.TreeSet; public class Main { public static void main(String [] args ) { try{ String str; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedOutputStream bos = new BufferedOutputStream(System.out); String eol = System.getProperty("line.separator"); byte [] eolb = eol.getBytes(); byte[] spaceb= " ".getBytes(); str = br.readLine(); int blank = str.indexOf( " "); int n = Integer.parseInt(str.substring(0,blank)); int m = Integer.parseInt(str.substring(blank+1)); long [] num = new long[n]; int j=0; int s=0; int k =0; str = br.readLine(); int length = str.length(); while(j<length) { while(j<length) { if(str.charAt(j) == ' ') { break; }else { j++; } } num[k] = Long.parseLong(str.substring(s,j)) ; k++; j++; s=j; } Arrays.sort(num); int count = 0; if(m==1) { count = 1; for(int i = 1 ; i < n ; i++) { if(num[i]!=num[i-1]) { count++; } } } else { TreeSet<Long> take = new TreeSet<Long>(); TreeSet<Long> notTake = new TreeSet<Long>(); for(int i = 0 ; i < n ; i++) { long temp = num[i]; if(!notTake.contains(temp)){ take.add(temp); temp *= ((long)m); notTake.add(temp); } } count = take.size(); } bos.write(new Integer(count).toString().getBytes()); bos.write(eolb); bos.flush(); } catch(IOException ioe) { ioe.printStackTrace(); } } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
/** * Mx 04:06:52 ص 14/01/2014 */ import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringBuilder line = new StringBuilder(reader.readLine()); int length = 0; for (int head = 0; head < line.length(); head++) { for (int tail = line.length() - 1; tail > head; tail--) { String subString = line.substring(head, tail); if(line.indexOf(subString,head+1)>-1){ length = Math.max(subString.length(), length); } } } System.out.println(length); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner cin = new Scanner(System.in); int n; n = cin.nextInt(); String s = cin.next(); int ans = n; int cntH = 0,cntT = 0; for(int i=0;i<n;i++) { if(s.charAt(i)=='H')cntH++; } cntT = n - cntH; for(int i=0;i+cntH<n;i++) { int tmp = 0; for(int j=i;j<i+cntH;j++) if(s.charAt(j)=='T')tmp++; if(ans>tmp)ans = tmp; } for(int i=0;i+cntT<n;i++) { int tmp = 0; for(int j=i;j<i+cntT;j++) if(s.charAt(j)=='H')tmp++; if(ans>tmp)ans = tmp; } System.out.println(ans); } }
linear
46_C. Hamsters and Tigers
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.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Objects; import java.util.Stack; import java.util.StringTokenizer; public class Test { static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args)throws Exception { Reader.init(System.in); int n = Reader.nextInt(); int p = Reader.nextInt(); int L = Reader.nextInt(); int R = Reader.nextInt(); int a = 1; int b = n; int res = 0; if(a == L && b == R) { res = 0; } else if(L != a && R != b && p >= L && p <= R) { res = Math.min(p-L, R-p); res += R- L + 2; } else if(L != a && R != b && p < L ) { res += L-p + 1; res += R - L +1; } else if(L != a && R != b && p > R) { res += p-R + 1; res += R - L +1; } else if(a == L && p >=L && p<=R) { res += R - p + 1; } else if(R == b && p>=L && p<=R) { res += p - L + 1; } else if(a == L && p > R) { res += p - R + 1; } else if(R == b && p<L) { res += L - p + 1; } pw.print(res); pw.close(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; public static int pars(String x) { int num = 0; int i = 0; if (x.charAt(0) == '-') { i = 1; } for (; i < x.length(); i++) { num = num * 10 + (x.charAt(i) - '0'); } if (x.charAt(0) == '-') { return -num; } return num; } static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static void init(FileReader input) { reader = new BufferedReader(input); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return pars(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
constant
915_B. Browser
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; import java.awt.*; public class PracticeProblem { /* * This FastReader code is taken from GeeksForGeeks.com * https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/ * * The article was written by Rishabh Mahrsee */ public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() throws FileNotFoundException { br = new BufferedReader(new FileReader(new File("input.txt"))); } 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 FastReader in; public static PrintWriter out; public static final int INF = Integer.MAX_VALUE; public static int n, m; public static final int[] dr = {-1, 0, 0, +1}; public static final int[] dc = {0, -1, +1, 0}; public static void main(String[] args) throws FileNotFoundException { in = new FastReader(); out = new PrintWriter(new File("output.txt")); solve(); out.close(); } private static void solve() { n = in.nextInt(); m = in.nextInt(); int k = in.nextInt(); int[][] timeToBurn = new int[n][m]; for (int i = 0; i < n; i++) Arrays.fill(timeToBurn[i], INF); for (int i = 0; i < k; i++) { int r = in.nextInt() - 1; int c = in.nextInt() - 1; for (int j = 0; j < n; j++) { for (int l = 0; l < m; l++) { timeToBurn[j][l] = min(timeToBurn[j][l], abs(r - j) + abs(c - l)); } } } int max = -1; Point p = null; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (timeToBurn[i][j] > max) { max = timeToBurn[i][j]; p = new Point(i, j); } } } out.println((p.x + 1) + " " + (p.y + 1)); } }
cubic
35_C. Fire Again
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.util.Scanner; import java.util.InputMismatchException; import java.util.HashMap; import java.io.IOException; import java.util.ArrayList; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ilyakor */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { ArrayList<PointInt[]> al; TaskB.Interactor interactor; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); //for (int itt = 0; itt < 100; ++itt) { interactor = new TaskB.IOInteractor(new Scanner(in.getStream()), out.getWriter());//new TestInteractor(n); Assert.assertTrue(interactor.query(1, 1, n, n) == 2); int lx = 1, rx = n, ly = 1, ry = n; for (int it = 0; it < 20; ++it) { int tx = (lx + rx) / 2; if (interactor.query(1, 1, tx, n) >= 1) rx = tx; else lx = tx; int ty = (ly + ry) / 2; if (interactor.query(1, 1, n, ty) >= 1) ry = ty; else ly = ty; } al = new ArrayList<>(); if (interactor.query(1, 1, lx, n) == 1 && interactor.query(lx + 1, 1, n, n) == 1) { dfs(1, 1, lx, n); dfs(lx + 1, 1, n, n); } else if (interactor.query(1, 1, rx, n) == 1 && interactor.query(rx + 1, 1, n, n) == 1) { dfs(1, 1, rx, n); dfs(rx + 1, 1, n, n); } else if (interactor.query(1, 1, n, ly) == 1 && interactor.query(1, ly + 1, n, n) == 1) { dfs(1, 1, n, ly); dfs(1, ly + 1, n, n); } else if (interactor.query(1, 1, n, ry) == 1 && interactor.query(1, ry + 1, n, n) == 1) { dfs(1, 1, n, ry); dfs(1, ry + 1, n, n); } else { throw new RuntimeException("WTF"); } Assert.assertTrue(al.size() == 2); interactor.answer(al.get(0)[0].x, al.get(0)[0].y, al.get(0)[1].x, al.get(0)[1].y, al.get(1)[0].x, al.get(1)[0].y, al.get(1)[1].x, al.get(1)[1].y); //} } private void dfs(int x1, int y1, int x2, int y2) { int t; t = x1; for (int i = 0; i < 20; ++i) { int x = (t + x2) / 2; if (interactor.query(x1, y1, x, y2) == 1) x2 = x; else t = x; } if (interactor.query(x1, y1, t, y2) == 1) x2 = t; t = x2; for (int i = 0; i < 20; ++i) { int x = (t + x1) / 2; if (interactor.query(x, y1, x2, y2) == 1) x1 = x; else t = x; } if (interactor.query(t, y1, x2, y2) == 1) x1 = t; t = y1; for (int i = 0; i < 20; ++i) { int y = (t + y2) / 2; if (interactor.query(x1, y1, x2, y) == 1) y2 = y; else t = y; } if (interactor.query(x1, y1, x2, t) == 1) y2 = t; t = y2; for (int i = 0; i < 20; ++i) { int y = (t + y1) / 2; if (interactor.query(x1, y, x2, y2) == 1) y1 = y; else t = y; } if (interactor.query(x1, t, x2, y2) == 1) y1 = t; al.add(new PointInt[]{new PointInt(x1, y1), new PointInt(x2, y2)}); } interface Interactor { int query(int x1, int y1, int x2, int y2); void answer(int x11, int y11, int x12, int y12, int x21, int y21, int x22, int y22); } static class Query { int x1; int y1; int x2; int y2; public Query(int x1, int y1, int x2, int y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TaskB.Query query = (TaskB.Query) o; if (x1 != query.x1) return false; if (y1 != query.y1) return false; if (x2 != query.x2) return false; return y2 == query.y2; } public int hashCode() { int result = x1; result = 31 * result + y1; result = 31 * result + x2; result = 31 * result + y2; return result; } } static class IOInteractor implements TaskB.Interactor { Scanner in; PrintWriter out; HashMap<TaskB.Query, Integer> cache; public IOInteractor(Scanner in, PrintWriter out) { this.in = in; this.out = out; cache = new HashMap<>(); } public int query(int x1, int y1, int x2, int y2) { TaskB.Query q = new TaskB.Query(x1, y1, x2, y2); if (cache.containsKey(q)) return cache.get(q); if (x1 > x2 || y1 > y2) return 0; Assert.assertTrue(x1 >= 1 && y1 >= 1); out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2); out.flush(); int res = in.nextInt(); cache.put(q, res); return res; } public void answer(int x11, int y11, int x12, int y12, int x21, int y21, int x22, int y22) { out.println("! " + x11 + " " + y11 + " " + x12 + " " + y12 + " " + x21 + " " + y21 + " " + x22 + " " + y22); out.flush(); } } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) return -1; } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } public InputStream getStream() { return stream; } } static class PointInt { public int x; public int y; public PointInt(int x, int y) { this.x = x; this.y = y; } public PointInt() { x = 0; y = 0; } } 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 PrintWriter getWriter() { return writer; } public void close() { writer.close(); } } static class Assert { public static void assertTrue(boolean flag) { // if (!flag) // while (true); if (!flag) throw new AssertionError(); } } }
logn
713_B. Searching Rectangles
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Solution implements Runnable { private BufferedReader in; private PrintWriter out; private StringTokenizer st; private Random rnd; double Vend; private double calcFirstSegment(double a, double Vmax, double Vend, double l) { double Vl = 0, Vr = Vmax; for(int it = 0; it < 256; it++) { double Vm = (Vl + Vr) / 2.0; double tFirst = Vm / a; double tSecond = 0; if(Vend < Vm) tSecond = (Vm - Vend) / a; double firstPart = a * tFirst * tFirst / 2.0; double secondPart = Vm * tSecond - a * tSecond * tSecond / 2.0; double res = firstPart + secondPart; if(res < l) Vl = Vm; else Vr = Vm; } this.Vend = Math.min(Vl, Vend); double res = 0.0; { double Vm = Vl; double tFirst = Vm / a; double tSecond = 0; if(Vend < Vm) tSecond = (Vm - Vend) / a; //out.println(tSecond); double firstPart = a * tFirst * tFirst / 2.0; double secondPart = Vm * tSecond - a * tSecond * tSecond / 2.0; double remain = l - firstPart - secondPart; res = tFirst + tSecond + (remain / Vm); } return res; } private double calcSecondPart(double a, double Vmax, double Vstart, double l) { double Vl = Vstart, Vr = Vmax; //out.println(Vstart); for(int it = 0; it < 256; it++) { double Vm = (Vl + Vr) / 2.0; double t = (Vm - Vstart) / a; double s = Vstart * t + a * t * t / 2.0; if(s < l) Vl = Vm; else Vr = Vm; } double res = 0.0; { double Vm = (Vl + Vr) / 2.0; double t = (Vm - Vstart) / a; double s = Vstart * t + a * t * t / 2.0; double remain = l - s; res = t + (remain / Vmax); } return res; } public void solve() throws IOException { double a = nextDouble(), v = nextDouble(), l = nextDouble(), d = nextDouble(), w = nextDouble(); double res = calcFirstSegment(a, v, w, d); res += calcSecondPart(a, v, Vend, l - d); out.println(res); } public static void main(String[] args) { new Solution().run(); } public void run() { try { //in = new BufferedReader(new FileReader("input.txt")); //out = new PrintWriter(new FileWriter("output.txt")); in = new BufferedReader(new InputStreamReader((System.in))); out = new PrintWriter(System.out); st = null; rnd = new Random(); solve(); out.close(); } catch(IOException e) { e.printStackTrace(); } } private String nextToken() throws IOException, NullPointerException { while(st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.util.*; public class Rules { public static void main(String[] args) { Scanner in = new Scanner(System.in); int a = in.nextInt(); double maxSpeed = in.nextInt(); double len = in.nextInt(); double delayDist = in.nextInt(); double delaySpeed = in.nextInt(); double timeToDelaySpeed = delaySpeed/a; double timeToDelay = travelS(a, 0.0, maxSpeed, delayDist); //System.out.printf("timeToDelaySpeed=%.5f, timeToDelay=%.5f\n", timeToDelaySpeed, timeToDelay); if (timeToDelay < timeToDelaySpeed) { // we won't reach delaySpeed before delay marker // 2 cases: we don't reach max by time we reach end timeToDelay = travelS(a, 0.0, maxSpeed, len); double timeToMax = maxSpeed/a; if (timeToDelay < timeToMax) { System.out.printf("%.9f\n", timeToDelay); return; } // we do reach max, then travel at max double[] parts = travelA(a, 0.0, maxSpeed); double remainingDist = len - parts[1]; double time = parts[0] + remainingDist / maxSpeed; System.out.printf("%.9f\n", time); return; } if (delaySpeed > maxSpeed) { double time = travelS(a, 0.0, maxSpeed, len); System.out.printf("%.9f\n", time); return; } // binary search to find best velocity to stop acceleration in beginning double lowV = delaySpeed; double highV = maxSpeed; int loopCount = 1000; double[] initial = null; double[] secondary = null; while (loopCount-->0) { double guessV = (lowV+highV)/2.0; initial = travelA(a, 0.0, guessV); secondary = travelA(a, guessV, Math.min(delaySpeed, maxSpeed)); if (initial[1] + secondary[1] < delayDist) { // okay, we can go faster lowV = guessV; } else { highV = guessV; } } double totalTime = 0.0; double finalSpeed = 0.0; initial = travelA(a, 0.0, lowV); secondary = travelA(a, lowV, delaySpeed); totalTime = initial[0] + secondary[0]; double totalDist = initial[1] + secondary[1]; totalTime += (delayDist-totalDist)/maxSpeed; // now we have delayDist to go, and we are at delaySpeed totalTime += travelS(a, delaySpeed, maxSpeed, len-delayDist); System.out.printf("%.9f\n", totalTime); } // [0] = time in h, [1] = dist travelled, in km // input units are in km/h^2, km/h, km/h public static double[] travelA(int a, double startSpeed, double endSpeed) { if (startSpeed > endSpeed) a = -a; double time = (endSpeed - startSpeed) / a; double dist = 0.5*a*time*time + startSpeed*time; return new double[] {time, dist}; } // returns time it takes to travel dist, with given inputs public static double travelS(int a, double startSpeed, double maxSpeed, double dist) { double timeToMax = (maxSpeed - startSpeed) / a; double targetTime = (-startSpeed + Math.sqrt(startSpeed*startSpeed + 2*a*dist)) / a; if (targetTime < timeToMax) return targetTime; double partialDist = 0.5*timeToMax*timeToMax*a + startSpeed*timeToMax; double remainingDist = dist - partialDist; targetTime = remainingDist / maxSpeed; return targetTime + timeToMax; } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.io.*; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { long n = in.nextLong(); long s = in.nextLong(); if(diff(n) < s) { System.out.println(0); out.close(); return; } long lo = 1; long hi = n; while(lo < hi) { long mid = lo + (hi - lo) / 2; if(diff(mid) >= s) hi = mid; else lo = mid + 1; } System.out.println(n - lo + 1); out.close(); } static long diff(long n) { char[] ca = (n + "").toCharArray(); int sum = 0; for(char c : ca) sum += (c - '0'); return n - sum; } } 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; } }
logn
817_C. Really Big Numbers
CODEFORCES
/** * @author Juan Sebastian Beltran Rojas * @mail jsbeltran.valhalla@gmail.com * @veredict * @url https://codeforces.com/problemset/problem/1238/E * @category dp * @date 19/10/2019 **/ import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import static java.lang.Integer.bitCount; import static java.lang.Integer.parseInt; public class CF1238E { static long[][] Q; static int N; static int M; static long[] mem; static long[] sums; public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (String ln; (ln = in.readLine()) != null; ) { StringTokenizer st = new StringTokenizer(ln); N = parseInt(st.nextToken()); M = parseInt(st.nextToken()); char[] S = in.readLine().toCharArray(); Q = new long[M][M]; mem = new long[1 << M]; Arrays.fill(mem, -1); for (int i = 1; i < N; i++) Q[S[i - 1] - 'a'][S[i] - 'a'] = Q[S[i] - 'a'][S[i - 1] - 'a'] = Q[S[i - 1] - 'a'][S[i] - 'a'] + 1; calculateSums(); for (int i = (1 << M) - 1; i >= 0; i--) f(i); System.out.println(f(0)); } } static void calculateSums() { sums = new long[1 << M]; Arrays.fill(sums, -1); for (int u = 0; u < (1 << M); u++) { if (sums[u] == -1) { sums[u] = 0; for (int j = 0; j < M; j++) for (int k = j + 1; k < M; k++) if (((u & (1 << j)) == 0 && (u & (1 << k)) != 0) || ((u & (1 << j)) != 0 && (u & (1 << k)) == 0)) sums[u] += Q[j][k]; int neg = (~u) & ((1 << M) - 1); sums[neg] = sums[u]; } } } static long f(int u) { if (bitCount(u) == M) return 0; if (mem[u] >= 0) return mem[u]; long min = 10000000000L; for (int i = 0; i < M; i++) if ((u & (1 << i)) == 0) { u = u | (1 << i); min = Math.min(f(u) + sums[u], min); u = u ^ (1 << i); } return mem[u] = min; } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.util.*; import java.io.*; public class _1004_A { public static void main(String[] args) throws IOException { int N = readInt(), D = readInt(); long arr[] = new long[N+2]; arr[0] = -3000000000L; arr[N+1] = -arr[0]; for(int i = 1; i<=N; i++) arr[i] = readInt(); int cnt = 1; if(Math.abs(arr[2]-(arr[1] + D)) >= D) cnt++; for(int i = 2; i<=N; i++) { if(Math.abs(arr[i-1]-(arr[i] - D)) > D) cnt++; if(Math.abs(arr[i+1]-(arr[i] + D)) >= D) cnt++; } println(cnt); exit(); } final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static 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 static String read() throws IOException { byte[] ret = new byte[1024]; int idx = 0; byte c = Read(); while (c <= ' ') { c = Read(); } do { ret[idx++] = c; c = Read(); } while (c != -1 && c != ' ' && c != '\n' && c != '\r'); return new String(ret, 0, idx); } public static int readInt() 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 static long readLong() 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 static double readDouble() 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 static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte Read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } static void print(Object o) { pr.print(o); } static void println(Object o) { pr.println(o); } static void flush() { pr.flush(); } static void println() { pr.println(); } static void exit() throws IOException { din.close(); pr.close(); System.exit(0); } }
linear
1004_A. Sonya and Hotels
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.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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int ct = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (a[i] > a[j]) ++ct; } } ct &= 1; int Q = in.nextInt(); for (int q = 0; q < Q; ++q) { int l = in.nextInt(); int r = in.nextInt(); int size = (r - l + 1) * (r - l) >> 1; ct ^= size & 1; out.println(ct % 2 == 0 ? "even" : "odd"); } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
911_D. Inversion Counting
CODEFORCES
//package contest10D; import java.math.*; import java.util.*; import static java.math.BigInteger.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main { static void debug(Object... os) { System.err.println(deepToString(os)); } public static void main(String[] args) { new Main().run(); } void run() { Scanner sc = new Scanner(System.in); int n=sc.nextInt(),m=sc.nextInt(); boolean[][] bs=new boolean[n][n]; for (int i = 0; i < m; i++) { int s=sc.nextInt()-1,t=sc.nextInt()-1; bs[s][t] = bs[t][s] = true; } long res = 0; for(int i=0;i<n;i++){ res += calc(bs,n-1-i); } System.out.println(res/2); } long calc(boolean[][] bs,int n){//start is n. long[][] dp=new long[1<<n][n]; // set,last -> number of path n -> last. for(int i=0;i<n;i++){ if(bs[i][n]) dp[1<<i][i] ++; } for(int i=1;i<1<<n;i++){ for(int j=0;j<n;j++)if(((i>>j)&1)==1) for(int k=0;k<n;k++)if(((i>>k)&1)==0 && bs[j][k]){//add dp[i|(1<<k)][k] += dp[i][j]; } } long res=0; for(int i=0;i<1<<n;i++)for(int j=0;j<n;j++)if(Integer.bitCount(i)>=2&&bs[j][n])res+=dp[i][j]; return res; } }
np
11_D. A Simple Task
CODEFORCES
// Author : RegalBeast import java.io.*; import java.util.*; public class Main { static final FastReader FR = new FastReader(); static final PrintWriter PW = new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) { StringBuilder solution = new StringBuilder(); int rows = FR.nextInt(); int cols = FR.nextInt(); int moves = FR.nextInt(); int[][] horizontalEdgeWeights = new int[rows][cols-1]; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols - 1; c++) { horizontalEdgeWeights[r][c] = FR.nextInt(); } } int[][] verticalEdgeWeights = new int[rows-1][cols]; for (int r = 0; r < rows - 1; r++) { for (int c = 0; c < cols; c++) { verticalEdgeWeights[r][c] = FR.nextInt(); } } int[][] result = getResult(rows, cols, moves, horizontalEdgeWeights, verticalEdgeWeights); for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { solution.append(result[r][c] + " "); } solution.append("\n"); } PW.print(solution.toString()); PW.close(); } static int[][] getResult(int rows, int cols, int moves, int[][] horizontalEdgeWeights, int[][] verticalEdgeWeights) { int[][] result = new int[rows][cols]; if ((moves & 1) == 1) { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { result[r][c] = -1; } } return result; } int mid = moves >> 1; int[][][] minForDistance = new int[rows][cols][mid+1]; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { for (int m = 1; m <= mid; m++) { minForDistance[r][c][m] = Integer.MAX_VALUE; } } } for (int m = 1; m <= mid; m++) { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { int minBoredom = minForDistance[r][c][m]; if (r > 0) { int candidateBoredom = minForDistance[r-1][c][m-1] + verticalEdgeWeights[r-1][c]; minBoredom = Math.min(minBoredom, candidateBoredom); } if (c > 0) { int candidateBoredom = minForDistance[r][c-1][m-1] + horizontalEdgeWeights[r][c-1]; minBoredom = Math.min(minBoredom, candidateBoredom); } if (r + 1 < rows) { int candidateBoredom = minForDistance[r+1][c][m-1] + verticalEdgeWeights[r][c]; minBoredom = Math.min(minBoredom, candidateBoredom); } if (c + 1 < cols) { int candidateBoredom = minForDistance[r][c+1][m-1] + horizontalEdgeWeights[r][c]; minBoredom = Math.min(minBoredom, candidateBoredom); } minForDistance[r][c][m] = minBoredom; } } } for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { result[r][c] = minForDistance[r][c][mid] << 1; } } return result; } 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; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Prob015A { public static void main( String[] Args ) { Scanner scan = new Scanner( System.in ); int numHouses = scan.nextInt(); int side = scan.nextInt() * 2; ArrayList<Integer> sides = new ArrayList<Integer>(); for ( int x = 0; x < numHouses; x++ ) { int c = scan.nextInt() * 2; int s = scan.nextInt(); int l = c - s; int r = c + s; int li = Collections.binarySearch( sides, l ); int ri = Collections.binarySearch( sides, r ); if ( li >= 0 && ri >= 0 ) { sides.remove( li ); sides.remove( li ); } else if ( li >= 0 ) sides.set( li, r ); else if ( ri >= 0 ) sides.set( ri, l ); else { sides.add( -li - 1, r ); sides.add( -li - 1, l ); } } int possibilities = 2; for ( int x = 1; x < sides.size() - 1; x += 2 ) if ( sides.get( x + 1 ) - sides.get( x ) > side ) possibilities += 2; else if ( sides.get( x + 1 ) - sides.get( x ) == side ) possibilities += 1; System.out.println( possibilities ); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.Scanner; public class A{ public static void main(String[] args){ Scanner s = new Scanner(System.in); int n = s.nextInt(); int prev2=0; int prev1=1; int prev=1; int curr = 2; if(n == 0) {System.out.println("0 0 0"); return;} else if(n == 1) {System.out.println("0 0 1");return;} while(true){ if(curr == n) break; prev2 = prev1; prev1 = prev; int temp = prev + curr; prev = curr; curr = temp; } System.out.println(prev2 + " " + prev1 + " " + prev1); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Xinyi Tao */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskBR574D2 solver = new TaskBR574D2(); solver.solve(1, in, out); out.close(); } static class TaskBR574D2 { public void solve(int testNumber, Scanner in, PrintWriter out) { long n = in.nextLong(); long k = in.nextLong(); long r = (long) (Math.sqrt(9 + 8 * (n + k)) - 3) / 2; out.println(n - r); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.*; import java.util.*; public class Main{ static int[][][]memo; static int inf=(int)1e9; static int n,m,down[][],right[][]; static int dp(int i,int j,int k) { if(k<=0)return 0; if(memo[i][j][k]!=-1)return memo[i][j][k]; int ans=inf; if(i+1<n) { ans=Math.min(ans, down[i][j]+dp(i+1, j, k-1)); } if(i-1>=0) { ans=Math.min(ans, down[i-1][j]+dp(i-1, j, k-1)); } if(j+1<m) { ans=Math.min(ans, right[i][j]+dp(i, j+1, k-1)); } if(j-1>=0) { ans=Math.min(ans, right[i][j-1]+dp(i, j-1, k-1)); } return memo[i][j][k]=ans; } static void main() throws Exception{ n=sc.nextInt();m=sc.nextInt();int k=sc.nextInt(); if((k&1)==1) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { pw.print((-1)+" "); } pw.println(); } return; } k>>=1; right=new int[n][]; down=new int[n-1][]; for(int i=0;i<n;i++) { right[i]=sc.intArr(m-1); } for(int i=0;i<n-1;i++) { down[i]=sc.intArr(m); } memo = new int[n][m][k+1]; int inf=(int)1e9; for(int i=0;i<=k;i++) { for(int j=0;j<n;j++) { for(int o=0;o<m;o++) { memo[j][o][i]=-1; } } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { pw.print((dp(i, j, k)<<1)+" "); } pw.println(); } } public static void main(String[] args) throws Exception{ sc=new MScanner(System.in); pw = new PrintWriter(System.out); int tc=1; // tc=sc.nextInt(); for(int i=1;i<=tc;i++) { // pw.printf("Case #%d:", i); main(); } pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(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 int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } 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); } } static void sort(int[]in) { shuffle(in); Arrays.sort(in); } static void sort(long[]in) { shuffle(in); Arrays.sort(in); } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.Scanner; public class Digits_Sequence_Hard_Edition_Kamel { public static void main(String [] args) { Scanner sc = new Scanner(System.in); long k = sc.nextLong(); getResult(k); sc.close(); } static void getResult(long k) { long val = 0;; long ten = 1; int i = 1; while(true) { val = 9l*ten*i; if(k<=val) { decompose(k, ten, i); System.exit(0); } else { k-=val; ten = ten*10l; i++; } } } static void decompose(long offset, long ten, int size) { long val = ten - 1 +(long) Math.ceil((double)offset/size); int digit = (int)(((offset%size))-1 + size)%size; String result = String.valueOf(val).substring(digit, digit+1); System.out.print(result); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class B implements Runnable { int a; int[] b; int[] l; public void solve() throws IOException { int n = in.nextInt(); int k = in.nextInt(); a = in.nextInt(); b = new int[n]; l = new int[n]; for ( int i = 0; i < n; i ++ ) { b[i] = in.nextInt(); l[i] = in.nextInt(); } out.println( best( 0, k )); } double best( int cur, int left ) { double r = 0.0; if ( cur < l.length ) { for ( int i = 0; i <= left && l[cur] + 10 * i <= 100; i ++ ) { l[cur] += i * 10; r = Math.max( r, best( cur + 1, left - i ) ); l[cur] -= i * 10; } } else { for ( int m = 0; m < ( 1 << l.length ); m ++ ) { int sum = 0; double p = 1.0; int pro = 0; for ( int i = 0; i < l.length; i ++ ) { if ( ( m & ( 1 << i ) ) == 0 ) { p *= 1.0 - l[i] * 0.01; sum += b[i]; } else { p *= l[i] * 0.01; pro ++; } } if ( pro * 2 > l.length ) { r += p; } else { r += ( p * a ) / ( a + sum ); } } } return r; } public Scanner in; public PrintWriter out; B() throws IOException { in = new Scanner(System.in); // in = new StreamTokenizer( new InputStreamReader( System.in ) ); out = new PrintWriter(System.out); } // int nextInt() throws IOException { // in.nextToken(); // return ( int ) in.nval; // } void check(boolean f, String msg) { if (!f) { out.close(); throw new RuntimeException(msg); } } void close() throws IOException { out.close(); } public void run() { try { solve(); close(); } catch (Exception e) { e.printStackTrace(out); out.flush(); throw new RuntimeException(e); } } public static void main(String[] args) throws IOException { new Thread(new B()).start(); } }
np
105_B. Dark Assembly
CODEFORCES
import static java.util.Arrays.*; import static java.util.Collections.*; import java.io.*; import java.lang.reflect.*; public class A { final int MOD = (int)1e9 + 7; final double eps = 1e-12; final int INF = (int)1e9; public A () { int N = sc.nextInt(); int M = sc.nextInt(); int K = sc.nextInt(); Integer [] S = sc.nextInts(); sort(S, reverseOrder()); int cnt = K, res; for (res = 0; res < N && cnt < M; ++res) cnt += S[res] - 1; exit(cnt < M ? -1 : res); } //////////////////////////////////////////////////////////////////////////////////// static MyScanner sc; static class MyScanner { public String next() { newLine(); return line[index++]; } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { line = null; return readLine().split(" "); } public char [] nextChars() { return next().toCharArray(); } public Integer [] nextInts() { String [] L = nextStrings(); Integer [] res = new Integer [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } public Long [] nextLongs() { String [] L = nextStrings(); Long [] res = new Long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } public Double [] nextDoubles() { String [] L = nextStrings(); Double [] res = new Double [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Double.parseDouble(L[i]); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error(e); } } private final BufferedReader r; MyScanner () { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = readLine().split(" "); index = 0; } } } static void print (Object o, Object... a) { pw.println(build(o, a)); } static void exit (Object o, Object... a) { print(o, a); exit(); } static void exit () { pw.close(); System.out.flush(); System.err.println("------------------"); System.err.println("Time: " + ((millis() - t) / 1000.0)); System.exit(0); } void NO() { throw new Error("NO!"); } //////////////////////////////////////////////////////////////////////////////////// static String build(Object... a) { StringBuilder b = new StringBuilder(); for (Object o : a) append(b, o); return b.toString().trim(); } static void append(StringBuilder b, Object o) { if (o.getClass().isArray()) { int L = Array.getLength(o); for (int i = 0; i < L; ++i) append(b, Array.get(o, i)); } else if (o instanceof Iterable<?>) { for (Object p : (Iterable<?>)o) append(b, p); } else b.append(" ").append(o); } //////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { sc = new MyScanner (); new A(); exit(); } static void start() { t = millis(); } static PrintWriter pw = new PrintWriter(System.out); static long t; static long millis() { return System.currentTimeMillis(); } }
nlogn
257_A. Sockets
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static long func(long a, long b) { if (a < b) return func(b, a); if (b < 2) return a; long q = a / b; long r = a - q * b; return q + func(b, r); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] ss = br.readLine().split(" +"); long a = Long.parseLong(ss[0]); long b = Long.parseLong(ss[1]); System.out.println(func(a, b)); } }
constant
343_A. Rational Resistance
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 Rustam Musin (t.me/musin_acm) */ 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); BSportivnayaMafiya solver = new BSportivnayaMafiya(); solver.solve(1, in, out); out.close(); } static class BSportivnayaMafiya { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int k = in.readInt(); int have = 0; for (int x = 1; ; x++) { have += x; if (have < k) { continue; } if (have - (n - x) == k) { out.print(n - x); return; } } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public 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 { public boolean isSpaceChar(int ch); } } 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 print(int i) { writer.print(i); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.LinkedList; import java.io.FileInputStream; import java.util.Arrays; import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.Collection; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Queue; import java.io.IOException; import java.io.FileOutputStream; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author nasko */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("input.txt"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("output.txt"); } catch (IOException e) { throw new RuntimeException(e); } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int M = in.nextInt(); int K = in.nextInt(); int[][] dist = new int[N+1][M+1]; for(int[] ini : dist) Arrays.fill(ini,1 << 30); int best = 0; ArrayList<Integer> result = new ArrayList<Integer>(); Queue<Integer> q = new LinkedList<Integer>(); for(int k = 0; k < K; ++k) { int x = in.nextInt(); int y = in.nextInt(); dist[x][y] = 0; q.offer(x); q.offer(y); } int[] dx = new int[] { 1,-1,0,0 }; int[] dy = new int[] {0,0,1,-1}; while(!q.isEmpty()) { int a = q.poll(); int b = q.poll(); for(int r = 0; r < 4; ++r) { int x = a + dx[r]; int y = b + dy[r]; if(x >= 1 && x <= N && y >=1 && y <= M && dist[x][y] > dist[a][b] + 1) { dist[x][y] = dist[a][b] + 1; q.offer(x); q.offer(y); } } } for(int i = 1; i <= N; ++i) for(int j = 1; j <= M; ++j) best = Math.max(best,dist[i][j]); for(int a = 1; a <= N; ++a) for(int b = 1; b <= M; ++b) if(dist[a][b] == best) { result.add(a); result.add(b); } if(result.size() > 0) { out.print(result.get(0) + " " + result.get(1)); } out.println(); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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()); } }
cubic
35_C. Fire Again
CODEFORCES
import static java.util.Arrays.deepToString; import java.io.*; import java.math.*; import java.util.*; public class A { static int [] solve(int [] a) { int n = a.length; Arrays.sort(a); a[n - 1] = (a[n - 1] > 1 ? 1 : 2); int [] b = Arrays.copyOf(a, n); Arrays.sort(b); return b; } public static void main(String[] args) throws Exception { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); setTime(); int n = nextInt(); int [] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } int [] b = solve(a); for (int v: b) { writer.print(v + " "); } printTime(); printMemory(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer tok = new StringTokenizer(""); static long systemTime; static void debug(Object... o) { System.err.println(deepToString(o)); } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + "kb"); } static String next() { while (!tok.hasMoreTokens()) { String w = null; try { w = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } if (w == null) return null; tok = new StringTokenizer(w); } return tok.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static BigInteger nextBigInteger() { return new BigInteger(next()); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class PaintTheNumbers { public static void main(String[] args) throws IOException { int[] colors = new int[101]; BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); int N = Integer.parseInt(st.nextToken()); st = new StringTokenizer(f.readLine()); for (int i = 0; i < N; i++) { colors[Integer.parseInt(st.nextToken())]++; } int colorCount = 0; for (int i = 1; i <= 100; i++) { if (colors[i] != 0) { colors[i] = 0; for (int multiple = 2; multiple * i <= 100; multiple++) { colors[i*multiple] = 0; } colorCount++; } } System.out.println(colorCount); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; public class Village { private class House implements Comparable<House> { Double Coordinate; Double Sidelength; private House(double coordinate, double sidelength) { Coordinate = coordinate; Sidelength = sidelength; } public int compareTo(House o) { return Coordinate.compareTo(o.Coordinate); } } private void solve() { Scanner in = new Scanner(System.in); in.next(); double requireside = in.nextDouble(); ArrayList<House> coordinate = new ArrayList<House>(); while (in.hasNext()) { double coo = in.nextDouble(); double side = in.nextDouble(); coordinate.add(new House(coo, side)); } Collections.sort(coordinate); ArrayList<Double> edges = new ArrayList<Double>(); int count = 2; for (int i = 0; i < coordinate.size(); i++) { edges.add(coordinate.get(i).Coordinate - (double) coordinate.get(i).Sidelength / (double) 2); edges.add(coordinate.get(i).Coordinate + (double) coordinate.get(i).Sidelength / (double) 2); } ArrayList<Double> difference = new ArrayList<Double>(); for (int i = 1; i < edges.size() - 1; i++) { difference.add(Math.abs(edges.get(i) - edges.get(i + 1))); } for (int i = 0; i < difference.size(); i += 2) { if (difference.get(i) == requireside) count++; else if (difference.get(i) > requireside) count += 2; } System.out.println(count); } public static void main(String args[]) { Village v = new Village(); v.solve(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class E { public static void main(String[] args) throws Exception { new Thread(null ,new Runnable(){ public void run(){ try{solveIt();} catch(Exception e){e.printStackTrace(); System.exit(1);} } },"Main",1<<28).start(); } static int dp[][], a[][], rows, cols; public static void solveIt() throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); int test = in.nextInt(); for (int t = 1; t <= test; t++) { rows = in.nextInt(); cols = in.nextInt(); dp = new int[cols][1 << rows]; for (int x[] : dp) Arrays.fill(x, -1); a = new int[cols][rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { a[j][i] = in.nextInt(); } } debug(a); pw.println(solve(0, 0)); } pw.close(); } static int solve(int pos, int mask) { if (pos >= cols) return 0; if (dp[pos][mask] != -1) return dp[pos][mask]; int res = 0; for (int i = 0; i < rows; i++) { for (int k = 0; k < (1 << rows); k++) { if ((mask & k) != 0) continue; int sum = 0; for (int bit = 0; bit < rows; bit++) { if (check(k, bit)) sum += a[pos][bit]; } res = max(res, sum + solve(pos + 1, mask | k)); } cyclicShift(pos); } return dp[pos][mask] = res; } static boolean check(int N, int pos) { return (N & (1 << pos)) != 0; } static void cyclicShift(int col) { int m = a[col].length; int last = a[col][m - 1]; for (int i = m - 1; i >= 1; i--) { a[col][i] = a[col][i - 1]; } a[col][0] = last; } 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 boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } public String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public String nextLine() { int c = skip(); StringBuilder sb = new StringBuilder(); while (!isEndOfLine(c)) { sb.appendCodePoint(c); c = readByte(); } return sb.toString(); } 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(); } } public long nextLong() { long num = 0; int 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(); } } public double nextDouble() { return Double.parseDouble(next()); } public char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } public char readChar() { return (char) skip(); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class D11 { static boolean[][] g; static int n, m; public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); n = input.nextInt(); m = input.nextInt(); g = new boolean[n][n]; for(int i = 0; i<m; i++) { int a = input.nextInt()-1, b = input.nextInt()-1; g[a][b] = g[b][a] = true; } long res = 0; map = new HashMap<Integer, Long>(); for(int i = n-1; i>=0; i--) { memo = new long[i+1][1<<(i+1)]; for(long[] A : memo) Arrays.fill(A, -1); res += count(i, i, 1<<i)/2; } out.println(res); out.close(); } static long[][] memo; static HashMap<Integer, Long> map; static long count(int at, int start, int mask) { if(memo[at][mask] != -1) return memo[at][mask]; int bits = Integer.bitCount(mask); if(at == start && bits > 2) return 1; long res = 0; for(int i = 0; i<=start; i++) { if(!g[at][i]) continue; if(i != start && (mask & (1<<i)) > 0) continue; if(i == start && bits <= 2) continue; res += count(i, start, mask | (1<<i)); } return memo[at][mask] = res; } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } }
np
11_D. A Simple Task
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; /* * 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. */ /** * * @author Andy Phan */ public class p1096f { static long MOD = 998244353; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); BIT invert = new BIT(n+5); BIT neg = new BIT(n+5); long res = 0; int[] arr = new int[n]; boolean[] has = new boolean[n+1]; long num1 = 0; for(int i = 0; i < n; i++) { arr[i] = in.nextInt(); if(arr[i] != -1) { res += invert.read(n+5)-invert.read(arr[i]); res %= MOD; invert.update(arr[i], 1); has[arr[i]] = true; } else num1++; } if(num1 == 0) { System.out.println(res); return; } for(int i = 1; i <= n; i++) if(!has[i]) neg.update(i, 1); long invertNum1 = modInv(num1, MOD); res += ((num1*(num1-1))%MOD)*modInv(4, MOD); res %= MOD; long cnt = 0; for(int i = 0; i < n; i++) { if(arr[i] == -1) { cnt++; continue; } res += (((neg.read(n+5)-neg.read(arr[i]))*cnt)%MOD)*invertNum1; res %= MOD; } cnt = 0; for(int i = n-1; i >= 0; i--) { if(arr[i] == -1) { cnt++; continue; } res += (((neg.read(arr[i]))*cnt)%MOD)*invertNum1; res %= MOD; } System.out.println(res); } //@ static class BIT { int n; int[] tree; public BIT(int n) { this.n = n; tree = new int[n + 1]; } int read(int i) { int sum = 0; while (i > 0) { sum += tree[i]; i -= i & -i; } return sum; } void update(int i, int val) { while (i <= n) { tree[i] += val; i += i & -i; } } //$ } //@ // Computes the modular inverse of x // Returns 0 if the GCD of x and mod is not 1 // O(log n) : Can be converted to use BigIntegers static long modInv(long x, long mod) { return (BigInteger.valueOf(x).modInverse(BigInteger.valueOf(mod))).longValue(); } static long modInv(long a, long b, long y0, long y1, long q0, long q1) { long y2 = y0 - y1*q0; return b == 0 ? y2 : modInv(b, a % b, y1, y2, q1, a / b); } //@ static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a / gcd(a, b) * b; } }
nlogn
1096_F. Inversion Expectation
CODEFORCES
import java.io.*; import java.util.*; public class TaskE { static int[][] transpose(int[][] a, int n, int m) { int[][] t = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { t[j][i] = a[i][j]; } } return t; } public static void main(String[] args) { FastReader in = new FastReader(System.in); // FastReader in = new FastReader(new FileInputStream("input.txt")); PrintWriter out = new PrintWriter(System.out); // PrintWriter out = new PrintWriter(new FileOutputStream("output.txt")); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n + 1][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); a[n][j] = Math.max(a[n][j], a[i][j]); } } a = transpose(a, n, m); Arrays.sort(a, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { int max1 = 0; for (int i = 0; i < o1.length; i++) { max1 = Math.max(max1, o1[i]); } int max2 = 0; for (int i = 0; i < o2.length; i++) { max2 = Math.max(max2, o2[i]); } return max2 - max1; } }); a = transpose(a, m, n); int[] dp = new int[1 << n]; for (int i = 0; i < Math.min(n, m); i++) { int[] best = new int[1 << n]; for (int j = 1; j < (1 << n); j++) { for (int k = 0; k < n; k++) { int sum = 0; for (int l = 0; l < n; l++) { if ((j & (1 << l)) != 0) sum += a[(l + k) % n][i]; } best[j] = Math.max(best[j], sum); } } int[] dp1 = dp.clone(); for (int j = 0; j < (1 << n); j++) { for (int k = j; k > 0; k = (k - 1) & j) { dp[j] = Math.max(dp[j], dp1[k ^ j] + best[k]); } } } out.println(dp[(1 << n) - 1]); } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.lang.Math; import java.io.*; import java.util.*; public class Main { static BufferedReader in; static PrintStream out; static StringTokenizer tok; @SuppressWarnings("empty-statement") public static void main(String[] args) throws NumberFormatException, IOException, Exception { in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new FileReader("metro.txt")); out = System.out; long mod = (long)1e9 + 7; int n = nextInt(); long[][] dp = new long[n+1][n+1]; Character[] line = new Character[n+1]; line[0] = 'a'; for (int i = 1; i <= n; i++) { line[i] = nextToken().charAt(0); if(line[i-1] == 'f')//for { for (int j = 0; j < i; j++) { dp[i][j+1] = dp[i-1][j]; } } else if(line[i-1] == 's')//simple { long temp = 0; for(int j = i; j >=0; j--) { temp = (temp + dp[i-1][j]) % mod; dp[i][j] = temp; } } else dp[i][0] = 1; } long total = 0; for(int j = 0; j <= n; j++) total = (total + dp[n][j]) % mod; out.println(total); } static String nextToken() throws IOException { String line = ""; while(tok == null || !tok.hasMoreTokens()) { if((line = in.readLine()) != null) tok = new StringTokenizer(line); else return null; } return tok.nextToken(); } static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.util.Arrays; /** * @author piuspratik (Piyush Das) */ public class TaskA { class Contest implements Comparable<Contest> { int problems; int penalty; Contest (int problems, int penalty) { this.problems = problems; this.penalty = penalty; } public int compareTo(Contest contest) { if(problems != contest.problems) return contest.problems - problems; return penalty - contest.penalty; } } void run(){ int n = nextInt(), k = nextInt(); Contest[] c = new Contest[n]; for(int i = 0; i < n; i++) { c[i] = new Contest(nextInt(), nextInt()); } Arrays.sort(c); int cproblem = c[k - 1].problems, cpenalty = c[k - 1].penalty; int ans = 0; for(int i = 0; i < n; i++) { if(c[i].problems == cproblem && c[i].penalty == cpenalty) ans++; } System.out.println(ans); } int nextInt(){ try{ int c = System.in.read(); if(c == -1) return c; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return c; } if(c == '-') return -nextInt(); int res = 0; do{ res *= 10; res += c - '0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c = System.in.read(); if(c == -1) return -1; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return -1; } if(c == '-') return -nextLong(); long res = 0; do{ res *= 10; res += c-'0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(Character.isWhitespace(c)) c = System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(c == '\r' || c == '\n') c = System.in.read(); do{ res.append((char)c); c = System.in.read(); }while(c != '\r' && c != '\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new TaskA().run(); } }
nlogn
166_A. Rank List
CODEFORCES
import java.util.Scanner; public class d_169 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long x=sc.nextLong(); long y=sc.nextLong(); String s=Long.toBinaryString(x); String p=Long.toBinaryString(y); int id=p.length()-s.length(); for (int i =1; i <=id; i++) { s="0"+s; } if(x==y){ System.out.println(0); return; } for (int i = 0; i <p.length(); i++) { if(s.charAt(i)!=p.charAt(i)){ System.out.println((long)Math.pow(2, s.length()-i)-1); return; } } } }
logn
276_D. Little Girl and Maximum XOR
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 */ 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); atskb solver = new atskb(); solver.solve(1, in, out); out.close(); } static class atskb { long s; public void solve(int testNumber, InputReader in, PrintWriter out) { long n = in.nextLong(); s = in.nextLong(); long ans = binarysearch(0, (long) Math.pow(10, 18) + 20 * 9); if (ans > n) { out.print(0); } else { out.print(n - ans + 1); } } public long binarysearch(long l, long r) { if (l == r) { if (check(l)) return l; return -1; } if (l - r == -1) { if (check(l)) return l; if (check(r)) { return r; } //return -1; } long mid = l + (r - l) / 2; if (check(mid)) return binarysearch(l, mid); return binarysearch(mid + 1, r); } public boolean check(long m) { String str = m + ""; long sum = 0; for (int i = 0; i < str.length(); i++) { sum += str.charAt(i) - '0'; } if (sum + s <= m) return true; return false; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar; private int 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 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; public class palin { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(System.out); Scanner scan = new Scanner(System.in); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { long n = in.nextLong() - 1; long k = in.nextLong() - 1; if (n == 0) { out.print("0"); } else { if (k >= n) { out.print("1"); } else { if (k * (k + 1) / 2 < n) { out.print("-1"); } else { long t = binsearch(n, k, 1, k); long ans = k - t + 1; if (k * (k + 1) / 2 - t * (t - 1) / 2 != n) ans++; System.out.println(ans); } } } } public static long binsearch(long n, long k, long from, long to) { if (from == to) { return from; } long mid = (from + to) / 2; if ((k * (k + 1)) / 2 - (mid * (mid - 1)) / 2 > n) return binsearch(n, k, mid + 1, to); else return binsearch(n, k, from, mid); } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
logn
287_B. Pipeline
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Contest200C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("200C.in")); StringTokenizer st = new StringTokenizer(in.readLine()); long a = Long.parseLong(st.nextToken()); long b = Long.parseLong(st.nextToken()); System.out.println(min(a,b)); } static long min(long a, long b) { if (a <= 0 || b <= 0) return 0; return a/b+min(b,a%b); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class phoenix_and_computers { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] st = br.readLine().split(" "); int n = Integer.parseInt(st[0]); int m = Integer.parseInt(st[1]); long[][] ncr = ncrcoll(405, 405, m); int[] p2 = new int[n + 1]; p2[0] = 1; for (int i = 1; i < p2.length; i++) { p2[i] = 2 * p2[i - 1] % m; } long[][] dp = new long[405][405]; dp[0][0] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { for (int k = 1; i + k <= n; k++) { dp[i + k + 1][j + k] += ((dp[i][j] * p2[k - 1]) % m * ncr[j + k][k]); dp[i + k + 1][j + k] %= m; } } } long ans = 0; for (int i = 0; i <= n; i++) { ans = (ans + dp[n + 1][i]) % m; } System.out.println(ans); } static long[][] ncrcoll(int n, int k, int p) { long[][] arr = new long[n + 1][k + 1]; for (int i = 1; i < arr.length; i++) { arr[i][0] = 1; } for (int i = 1; i < arr.length; i++) { for (int j = 1; j <= i && j < arr[0].length; j++) { if (i == 1 && j == 1) { arr[i][j] = 1; } else { arr[i][j] = (arr[i - 1][j] + arr[i - 1][j - 1]) % (p); } } } return arr; } public static long xpown(long x, long n) { long res = 1; while (n > 0) { if (n % 2 != 0) { res = (res * x) % 1000000007; n--; } else { x = (x * x) % 1000000007; n = n / 2; } } return res; } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class OverlapedString { public static void main(String args[]) throws Exception { OverlapedString os = new OverlapedString(); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = stdin.readLine()) != null) { System.out.println(os.handleOverlap(line)); } } private int handleOverlap(String str) { int len = str.length(); int count = 0; for(int i=0;i<len;i++) for(int j=i+1;j<len;j++) { String _tmp = str.substring(i,j); if(_tmp!=null&&_tmp.length()>0) { if(getOverlapCount(str,_tmp)>1) { if(_tmp.length()>count) count = _tmp.length(); } } } return count; } private int getOverlapCount(String str,String sub) { int start = 0; int count = 0; while(start<str.length()) { start = str.indexOf(sub,start); if(start==-1) break; else { start++; count++; } } return count; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.awt.Point; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; import static java.lang.Math.*; import static java.lang.Integer.*; import static java.lang.Long.*; import static java.lang.Character.*; import static java.lang.String.*; @SuppressWarnings("unused") public class round169D { static PrintWriter out = new PrintWriter(System.out); static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer st = new StringTokenizer(""); static int nextInt() throws Exception { return Integer.parseInt(next()); } static String next() throws Exception { while (true) { if (st.hasMoreTokens()) { return st.nextToken(); } String s = br.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } } public static void main(String[] args)throws Exception { long l = parseLong(next()); long r = parseLong(next()); long [] min = new long [61]; for(int i = 1 ; i <= 60 ; ++i){//(2^i)-1 is obtained by min[i]^min[i]+1 min[i] = (long) pow(2, i - 1) - 1; } for(int i = 60 ; i >= 0 ; --i){//try to get 2^i-1 as answer. if(min[i] >= r) continue; if(min[i] >= l && min[i] + 1 <= r){ out.println((long) pow(2, i) - 1); out.flush(); return; } if(min[i] < l){ long one_jump = (long) pow(2, i); long jumps = (long) ceil((l - min[i]) / (one_jump * 1.0)); long cur = min[i] + (jumps * one_jump); if(cur >= l && cur + 1 <= r){ out.println((long) pow(2, i) - 1); out.flush(); return; } } } out.println(0); out.flush(); } }
logn
276_D. Little Girl and Maximum XOR
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.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; public class P { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); long N = sc.nextLong(), S = sc.nextLong(); long lo = 0, hi = N; long pivot = 0; while (lo <= hi) { long mid = lo + (hi - lo) / 2; int sumOfDigits = 0; long saveMid = mid; while (saveMid > 0) { sumOfDigits += saveMid % 10; saveMid /= 10; } if (mid - sumOfDigits < S) { pivot = mid; lo = mid + 1; } else hi = mid - 1; } System.out.println(N - pivot); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String f) throws FileNotFoundException { br = new BufferedReader(new FileReader(f)); } public String next() throws IOException { while (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 String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray1(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public int[] shuffle(int[] a, int n) { int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); int t = b[i]; b[i] = b[j]; b[j] = t; } return b; } public int[] nextIntArraySorted(int n) throws IOException { int[] a = nextIntArray(n); a = shuffle(a, n); Arrays.sort(a); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public long[] nextLongArray1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } public long[] nextLongArraySorted(int n) throws IOException { long[] a = nextLongArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); long t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); Long N = sc.nextLong(); Long ans; sc.close(); if(N <= 2) System.out.println(N); else{ if(N % 6 == 0){ ans = (N - 1) * (N - 2) * (N - 3);} else if(N % 2 == 0){ ans = N * (N - 1) * (N - 3); } else{ ans = N * (N - 1) * (N - 2); } System.out.println(ans); } } }
constant
235_A. LCM Challenge
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Scanner; /** UVA 10130 - SuperSale */ public class Main { /** totally n products, max Weight is w */ public static void main(String[] args) throws Exception { Scanner sc = null; PrintWriter pr = null; pr=new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); sc = new Scanner(new BufferedReader(new InputStreamReader(System.in))); //sc = new Scanner(new File("input.txt")); long n = sc.nextInt(); if (n > 0) pr.println(n); else { long n1 = n / 10; long n2 = n / 100 * 10 + n % 10; if (n1 < n2) pr.println(n2); else pr.println(n1); } pr.close(); sc.close(); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class SolutionE extends Thread { 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; } } private static final FastReader scanner = new FastReader(); private static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { new Thread(null, new SolutionE(), "Main", 1 << 26).start(); } static final int[] primeFactors = getSmallestPrimeFactorInIntervalInclusive(10_000_000); public void run() { int t = scanner.nextInt(); for (int i = 0; i < t; i++) { solve(); } out.close(); } //runs in roughly O(maxN * lg^2(maxN))) public static int[] getSmallestPrimeFactorInIntervalInclusive(int maxN) { int[] result = new int[maxN + 1]; result[1] = 1; for (int i = 2; i <= maxN; i++) { if (result[i] == 0) { for (int j = i; j <= maxN; j += i) { result[j] = (result[j / i] % i == 0) ? (result[j/i]/i) : (result[j/i]*i); } } } return result; } private static void solve() { int n = scanner.nextInt(); int k = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = primeFactors[scanner.nextInt()]; } Map<Integer, Integer> lastSeenIndex = new HashMap<>(); int[] revertPointers = new int[n]; for (int i = 0; i < n; i++) { if (lastSeenIndex.get(a[i]) != null) { revertPointers[i] = lastSeenIndex.get(a[i]); } else { revertPointers[i] = -1; } lastSeenIndex.put(a[i], i); } int[][] maxSegment = new int[n][k+1]; for (int j = 0; j <= k; j++) { int pointerLeft = 0; int pointerRight = 0; boolean[] changed = new boolean[n]; int amountChanged = 0; while (pointerLeft < n) { if (pointerRight < n && revertPointers[pointerRight] < pointerLeft) { pointerRight++; } else if (pointerRight < n && revertPointers[pointerRight] >= pointerLeft && amountChanged < j) { changed[revertPointers[pointerRight]] = true; pointerRight++; amountChanged++; } else { if (changed[pointerLeft]) { amountChanged--; } maxSegment[pointerLeft][j] = pointerRight; pointerLeft++; } } } int[][] dp = new int[n+1][k+1]; for (int j = 0; j <= k; j++) { dp[n][j] = 0; } for (int i = n - 1; i >= 0; i--) { for (int j = 0; j <= k; j++) { dp[i][j] = n + 1; for (int x = 0; x <= j; x++) { int nextJumpTo = maxSegment[i][x]; dp[i][j] = Math.min(dp[i][j], dp[nextJumpTo][j - x] + 1); } } } out.println(dp[0][k]); } //REMINDERS: //- CHECK FOR INTEGER-OVERFLOW BEFORE SUBMITTING //- CAN U BRUTEFORCE OVER SOMETHING, TO MAKE IT EASIER TO CALCULATE THE SOLUTION }
cubic
1497E2
CODEFORCES
import java.util.*; public class Main{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); Arrays.sort(a); //boolean int t=1,c=0; for(int i=1;i<n;i++){ if(a[i]==a[i-1]) { if(i-2>=0&&a[i-2]==a[i-1]-1){ System.out.println("cslnb"); return; } c++; } if(a[i]==a[i-1]&&a[i]==0){ System.out.println("cslnb"); return; } } if(c>1) { System.out.println("cslnb"); return; } for(int i=0;i<n;i++){ if((a[i]-i)%2!=0) t=t^1; } if(t==1) System.out.println("cslnb"); else System.out.println("sjfnb"); } }
linear
1190_B. Tokitsukaze, CSL and Stone Game
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main (String[] args) { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { String parameterStringList[] = reader.readLine().split(" "); int x = Integer.parseInt(parameterStringList[0]); int y = Integer.parseInt(parameterStringList[1]); int z = Integer.parseInt(parameterStringList[2]); int t1 = Integer.parseInt(parameterStringList[3]); int t2 = Integer.parseInt(parameterStringList[4]); int t3 = Integer.parseInt(parameterStringList[5]); int T1 = Math.abs(x-y) * t1; int T2 = Math.abs(x-z) * t2 + 3*t3 + Math.abs(x-y) * t2; if(T2 <= T1) System.out.println("YES"); else System.out.println("NO"); } catch (IOException e) { e.printStackTrace(); } } }
constant
1054_A. Elevator or Stairs?
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class B { public static void main(String[] args) throws Exception { new B().solve(System.in, System.out); // new FileInputStream(new File("input.txt")), // new PrintStream(new FileOutputStream(new File("output.txt")))); } void solve(InputStream _in, PrintStream out) throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader(_in)); // String[] sp; Scanner sc = new Scanner(_in); long n = sc.nextLong(); long x = sc.nextLong() - 1; long y = sc.nextLong() - 1; long c = sc.nextLong(); long ub = 2 * n; long lb = -1; while (lb + 1 < ub) { long k = (lb + ub) / 2; long l, u, r, d; l = Math.max(0, x - k); u = Math.max(0, y - k); r = Math.min(n - 1, x + k); d = Math.min(n - 1, y + k); long ss = 0; // lu long lu = x - (k - (y - u)); if (l < lu) { long a = lu - l; ss += a * (a + 1) / 2; } // ld long ld = x - (k - (d - y)); if (l < ld) { long a = ld - l; ss += a * (a + 1) / 2; } // ru long ru = x + (k - (y - u)); if (ru < r) { long a = r - ru; ss += a * (a + 1) / 2; } // rd long rd = x + (k - (d - y)); if (rd < r) { long a = r - rd; ss += a * (a + 1) / 2; } long cc = (r + 1 - l) * (d + 1 - u) - ss; if (c <= cc) { // ok ub = k; } else { // ng lb = k; } } out.println(ub); } } // // // // // // // // // // // // // // // // // // // // // // // //
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import static java.lang.Math.*; public class Main{ public void go(){ int n=sc.nextInt(), k=sc.nextInt(), A=sc.nextInt(); ArrayList< ArrayList< Integer > > waysGiveCandies = doit1(n, k, new ArrayList< Integer >()); /* System.out.printf("%d\n", waysGiveCandies.size()); for(ArrayList< Integer > x : waysGiveCandies){ for(int i : x) System.out.printf("%d ", i); System.out.printf("\n"); } */ int[] lvl = new int[n], loyal = new int[n]; for(int i=0; i<n; ++i){ lvl[i] = sc.nextInt(); loyal[i] = sc.nextInt(); } double ret = 0; for(ArrayList< Integer > distribution : waysGiveCandies){ double[] Loyal = new double[n]; for(int i=0; i<n; ++i) Loyal[i] = min(loyal[i]+10*distribution.get(i), 100)/100.0; double pWin = 0; for(int i=0; i<1<<n; ++i){ double pVoteOccurs = 1; for(int j=0; j<n; ++j) if((i&(1<<j))!=0) // if winner pVoteOccurs *= Loyal[j]; else // if loser pVoteOccurs *= 1-Loyal[j]; int B = 0; for(int j=0; j<n; ++j) if((i&(1<<j))==0) B += lvl[j]; double pWinFight = (double)A/(A+B); // if win vote, don't need to fight if(bit_count(i)*2 > n) pWinFight = 1; pWin += pVoteOccurs * pWinFight; } ret = max(ret, pWin); } System.out.printf("%.9f\n", ret); } ArrayList< ArrayList< Integer > > doit1(int n, int k, ArrayList< Integer > soFar){ ArrayList< ArrayList< Integer > > ret = new ArrayList< ArrayList< Integer > >(); // base case if(n==1){ soFar.add(k); ret.add(soFar); return ret; } // general case for(int i=0; i<k+1; ++i){ ArrayList< Integer > tmp = new ArrayList< Integer >(soFar); tmp.add(i); ret.addAll(doit1(n-1, k-i, tmp)); } return ret; } // syntax // ArrayList<Integer>[] myMat = (ArrayList<Integer>[]) new ArrayList[nB]; // Pairs public class ii implements Comparable< ii >{ int x, y; public ii(){} public ii(int xx, int yy){ x=xx; y=yy; } public int compareTo(ii p){ return x!=p.x ? x-p.x : y-p.y; } public int hashCode(){ return 31*x+y; } public boolean equals(Object o){ if(!(o instanceof ii)) return false; ii p = (ii) o; return x==p.x && y==p.y; } public String toString(){ return "("+x+", "+y+")"; } } /* public class pair< X extends Comparable< X >,Y extends Comparable< Y > > implements Comparable< pair< X,Y > >{ X x; Y y; public pair(){} public pair(X xx, Y yy){ x=xx; y=yy; } public int compareTo(pair< X,Y > p){ return x.compareTo(p.x)!=0 ? x.compareTo(p.x) : y.compareTo(p.y); } public int hashCode(){ return 31*x.hashCode()+y.hashCode(); } public boolean equals(Object o){ if((o.getClass() != this.getClass())) return false; pair< X,Y > p = (pair< X,Y >) o; return x.equals(p.x) && y.equals(p.y); } public String toString(){ return "("+x+", "+y+")"; } } */ // my stuff public static final int INF = 1000*1000*1000+7; public static final double EPS = 1e-9; public static final double PI = 2*acos(0.0); public void rev(Object[] a){ for(int i=0; i<a.length/2; ++i){ Object t=a[i]; a[i]=a[a.length-1-i]; a[a.length-1-i]=t; } } public void rev(int[] a){ for(int i=0; i<a.length/2; ++i){ int t=a[i]; a[i]=a[a.length-1-i]; a[a.length-1-i]=t; } } public int bit_count(long x){ return x==0 ? 0 : 1+bit_count(x&(x-1)); } public int low_bit(int x){ return x&-x; } // 0011 0100 returns 0000 0100 public int sign(int x){ return x<0 ? -1 : x>0 ? 1 : 0; } public int sign(double x){ return x<-EPS ? -1 : x>EPS ? 1 : 0; } int[] unpack(ArrayList< Integer > a){ int[] ret = new int[a.size()]; for(int i=0; i<a.size(); ++i) ret[i] = a.get(i); return ret; } // generic main stuff static myScanner sc; static PrintWriter pw; static long startTime; public static void main(String[] args) throws Exception{ // sc = new Scanner(System.in); sc = (new Main()).new myScanner(new BufferedReader(new InputStreamReader(System.in))); pw = new PrintWriter(System.out); startTime = System.nanoTime(); (new Main()).go(); // errprintln("nanoTime="+(System.nanoTime()-startTime)/1000000/1000.0); pw.flush(); System.exit(0); } // capable of reading 2.86M 6dp doubles per second // 2.16M 12dp doubles per second // 2.75M int per second public class myScanner{ private BufferedReader f; private StringTokenizer st; public myScanner(BufferedReader ff){ f=ff; st=new StringTokenizer(""); } public int nextInt(){ return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public String nextLine(){ st=new StringTokenizer(""); String ret=""; try{ ret=f.readLine(); }catch(Exception e){} return ret; } public String nextToken(){ while(!st.hasMoreTokens()) try{ st=new StringTokenizer(f.readLine()); } catch(Exception e){} return st.nextToken(); } } }
np
105_B. Dark Assembly
CODEFORCES
/** * * @author ishani */ import java.util.*; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); TreeSet<Integer> set = new TreeSet<Integer>(); for(int i=0;i<N;i++){ int a = sc.nextInt(); set.add(a); } if(set.size()==1)System.out.println("NO"); else{ set.remove(set.first()); System.out.println(set.first()); } } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class A implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new Thread(null, new A(), "", 128 * (1L << 20)).start(); } long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory(){ memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } void debug(Object... objects){ if (DEBUG){ for (Object o: objects){ System.err.println(o.toString()); } } } public void run(){ try{ timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); time(); memory(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } boolean DEBUG = false; void solve() throws IOException{ int n = readInt(); int[] a = new int[n]; Integer[] b = new Integer[n]; for (int i = 0; i < n; ++i){ a[i] = readInt(); b[i] = a[i]; } Arrays.sort(b); int count = 0; for (int i = 0; i < n; ++i){ if (a[i] != b[i]){ count++; } } if (count == 2 || count == 0){ out.println("YES"); }else{ out.println("NO"); } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
// CodeForces Round #914 B train done import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SportMafia { int n,k; int nCand; private void readData(BufferedReader bin) throws IOException { String s = bin.readLine(); String []ss = s.split(" "); n = Integer.parseInt(ss[0]); k = Integer.parseInt(ss[1]); } void printRes() { System.out.println(nCand); } private void calculate() { // count napitki double p; p = -1.5 + Math.sqrt(2.25 + 2.0*(n+k)); nCand = (int)Math.round(n-p); } public static void main(String[] args) throws IOException { // BufferedReader bin = new BufferedReader(new FileReader("cactus.in")); BufferedReader bin = new BufferedReader( new InputStreamReader(System.in)); SportMafia l = new SportMafia(); l.readData(bin); l.calculate(); l.printRes(); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * * @author Fuad */ public class Codeforces { private static boolean greater(long mid, long s) { int sum = 0; long num = mid; while (num != 0) { sum += (num % 10); num /= 10; } return mid - sum >= s; } static class pair { int first; int second; pair(int f, int s) { first = f; second = s; } pair() { } } public static void main(String[] args) throws Exception { // TODO code application logic here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long n, s; String arr[] = br.readLine().split(" "); n = Long.parseLong(arr[0]); s = Long.parseLong(arr[1]); long l = 1; long h = n; while (l < h) { long mid = (l + h) / 2; if (greater(mid, s)) { h = mid; } else { l = mid + 1; } } System.out.println(greater(h, s) ? n - h + 1 : 0); } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class P817C { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n = scan.nextLong(); long s = scan.nextLong(); long ans = 0; if (s > n) { System.out.println(0); return; } if (n > s+200) { ans += n-(s+200); n = s+200; } for (long i = s; i <= n; i++) { char[] num = (""+i).toCharArray(); int sum = 0; for (int j = 0; j < num.length; j++) sum += num[j] - '0'; if (i - sum >= s) ans++; } System.out.println(ans); } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicReferenceArray; public class NastyaWardrobe { static long modulo = 1000000007; static long ans = 0; public static void main(String[] args) throws IOException { BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); String[] s1 = inp.readLine().split(" "); long clothes = Long.parseLong(s1[0]); long months = Long.parseLong(s1[1]); //formula 2^k(2x-1)+1; calc(clothes,months); System.out.print(ans); } static void calc(long clothes,long months){ if(clothes!=0) { long a; long count = 0; ArrayList<Long> list = new ArrayList<>(); if (months >= 2) { a = 2; long c = months; while (c > 1) { if (c % 2 == 1) { count++; list.add(a); } c = c / 2; a = (a * a) % modulo; } while (count > 0) { long b = list.get(0); list.remove(0); a = (a * b) % modulo; count--; } } else { a = (long) Math.pow(2, months); } long b = clothes; //System.out.println(b); b = (2 * b - 1) % modulo; ans = (a * b) % modulo; ans = (ans + 1) % modulo; }else{ ans = 0; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.*; import java.util.*; public class r584p5 { private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter pw = new PrintWriter(System.out); private static int n, m, arr[][]; private static ArrayList<HashSet<Integer>> chls; private static void gench(){ chls.add(new HashSet<>()); chls.get(0).add(0); for(int i=1; i<(1<<n); i++){ int des = i^Integer.highestOneBit(i); HashSet<Integer> st = new HashSet<>(); for(int z : chls.get(des)){ st.add(z); st.add(z|Integer.highestOneBit(i)); } chls.add(st); } } private static void cal(){ int val[][] = new int[(1<<n)][m]; for(int j=0; j<m; j++){ val[0][j] = 0; for(int mask=1; mask<(1<<n); mask++){ int max = 0; for(int begin=0; begin<n; begin++){ int sum = 0; for(int ptr=begin, pos=0; pos<n; ptr=(ptr+1)%n, pos++){ if((mask&(1<<pos)) > 0) sum += arr[ptr][j]; } max = Math.max(max, sum); } val[mask][j] = max; } } int dp[][] = new int[(1<<n)][m]; for(int mask=0; mask<(1<<n); mask++) dp[mask][0] = val[mask][0]; for(int j=1; j<m; j++){ dp[0][j] = 0; for(int mask=1; mask<(1<<n); mask++){ dp[mask][j] = 0; for(int ch1 : chls.get(mask)){ int ch2 = mask^ch1; dp[mask][j] = Math.max(dp[mask][j], val[ch1][j]+dp[ch2][j-1]); } } } pw.println(dp[(1<<n)-1][m-1]); } private static void run()throws IOException{ StringTokenizer tk = new StringTokenizer(r.readLine()); n = Integer.parseInt(tk.nextToken()); m = Integer.parseInt(tk.nextToken()); arr = new int[n][m]; chls = new ArrayList<>(); for(int i=0; i<n; i++){ tk = new StringTokenizer(r.readLine()); for(int j=0; j<m; j++) arr[i][j] = Integer.parseInt(tk.nextToken()); } gench(); cal(); } public static void main(String args[])throws IOException{ int t = Integer.parseInt(r.readLine()); while(t-->0) run(); pw.flush(); pw.close(); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.Scanner; /* * 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. */ /** * * @author Madi */ public class A630 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); System.out.println("25"); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); long[] a = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = Long.parseLong(st.nextToken()); } long[] sum = new long[n]; sum[0] = a[0]; for (int i = 1; i < sum.length; i++) { sum[i] = sum[i - 1] + a[i]; } solve(a, sum); } private static void solve(long[] a, long[] sum) { int n = a.length; Map<Long, List<Pair>> map = new HashMap<>(); for (int j = 0; j < sum.length; j++) { for (int i = 0; i <= j; i++) { long k = getSum(sum, i, j); if (map.containsKey(k)) { map.get(k).add(new Pair(i, j)); } else { List<Pair> arr = new ArrayList<>(); arr.add(new Pair(i, j)); map.put(k, arr); } } } int max = -1; List<Pair> ans = null; for (Map.Entry<Long, List<Pair>> entry : map.entrySet()) { List<Pair> pairs = entry.getValue(); int prev = -1; int count = 0; List<Pair> temp = new ArrayList<Pair>(); for (Pair p : pairs) { if (p.x > prev) { prev = p.y; temp.add(p); count++; } } if (count > max) { ans = temp; max = count; } } if (max != -1) { System.out.println(ans.size()); for (Pair p : ans) { System.out.println((p.x + 1) + " " + (p.y + 1)); } } } private static long getSum(long[] sum, int l, int r) { if (l == 0) { return sum[r]; } return sum[r] - sum[l - 1]; } } class Pair { int x; int y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int hashCode() { int h = 171 << 4; h = h * x; h = h * y; return h; } @Override public boolean equals(Object o) { if (o instanceof Pair) { Pair other = (Pair) o; return this.x == other.x && this.y == other.y; } return false; } @Override public String toString() { return "Pair [x=" + x + ", y=" + y + "]"; } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.IntStream; public class Test { static PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static int readInt() { int ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } static long readLong() { long ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } static String readLine() { StringBuilder b = new StringBuilder(); try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (Character.isLetterOrDigit(c)) { start = true; b.append((char) c); } else if (start) break; } } catch (IOException e) { } return b.toString(); } public static void main(String[] args) { Test te = new Test(); te.start(); writer.flush(); } int[] buf = new int[10]; int best(int[][] a, int c) { int ans = 0; if (c == a[0].length) { for (int i = 0; i < a.length; i++) ans += Arrays.stream(a[i]).max().getAsInt(); return ans; } for (int r = 0; r <= a.length; r++) { for (int i = 0; i < a.length; i++) buf[(i+1) % a.length] = a[i][c]; for (int i = 0; i < a.length; i++) a[i][c] = buf[i]; ans = Math.max(ans, best(a, c+1)); } return ans; } void start() { int t = readInt(); while (t-- > 0) { int n = readInt(), m = readInt(); int[][] a = new int[n][m]; int[][] e = new int[n*m][]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { a[i][j] = readInt(); e[i*m+j] = new int[]{a[i][j], j}; } Arrays.sort(e, (x, y) -> x[0] == y[0] ? Integer.compare(x[1], y[1]) : Integer.compare(y[0], x[0])); Set<Integer> cols = new HashSet<>(); for (int[] x : e) { cols.add(x[1]); if (cols.size() >= n) break; } int[] cs = cols.stream().mapToInt(Integer::intValue).toArray(); int[][] na = new int[n][cs.length]; for (int i = 0; i < n; i++) for (int j = 0; j < cs.length; j++) na[i][j] = a[i][cs[j]]; writer.println(best(na, 0)); } } }
np
1209_E1. Rotate Columns (easy version)
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.util.*; public class CottageVillage { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int size=sc.nextInt(); int side=sc.nextInt(); ArrayList<Pair> lis=new ArrayList<Pair>(); for(int x=0;x<size;x++) { lis.add(new Pair(sc.nextInt(), sc.nextInt())); } Collections.sort(lis); int count=2; for(int x=0;x<lis.size()-1;x++) { Pair a=lis.get(x); Pair b=lis.get(x+1); double na=a.x+a.len/2; double nb=b.x-b.len/2; //System.out.println(na+" "+nb); if(na<nb) { double dif=Math.abs(nb-na); if(dif==side)count++; else if(dif>side)count+=2; } } System.out.println(count); } } class Pair implements Comparable<Pair> { int x; double len; public Pair(int a,int b) { x=a; len=b; } public int compareTo(Pair o) { return x-o.x; } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.security.SecureRandom; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { class Pair implements Comparable<Pair> { int col; int time; int place; public Pair() { } public Pair(int col, int time) { this.col = col; this.time = time; } @Override public int compareTo(Pair arg0) { if (col == arg0.col) { return time - arg0.time; } return arg0.col - col; } } public void solve() throws Exception { int n = sc.nextInt(); int k = sc.nextInt(); ArrayList<Pair> a = new ArrayList<Pair>(); for (int i = 0;i < n; ++ i) { a.add(new Pair(sc.nextInt(), sc.nextInt())); } Collections.sort(a); int place = 1; int placex = 0; int ans2 = 0; int ans1 = 0; for (int i = 0;i < n; ++ i) { if (i > 0 && a.get(i).compareTo(a.get(i - 1)) != 0) { ++ place; ++ placex; } else { ++ placex; } a.get(i).place = place; if (placex == k) { ans1 = place; } } for (int i = 0;i < n; ++ i) { if (a.get(i).place == ans1) { ++ ans2; } } out.println(ans2); } /*--------------------------------------------------------------*/ static String filename = ""; static boolean fromFile = false; BufferedReader in; PrintWriter out; FastScanner sc; public static void main(String[] args) { new Thread(null, new Solution(), "", 1 << 25).start(); } public void run() { try { init(); solve(); } catch (Exception e) { throw new RuntimeException(e); } finally { out.close(); } } void init() throws Exception { if (fromFile) { in = new BufferedReader(new FileReader(filename+".in")); out = new PrintWriter(new FileWriter(filename+".out")); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } sc = new FastScanner(in); } } class FastScanner { BufferedReader reader; StringTokenizer strTok; public FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws IOException { while (strTok == null || !strTok.hasMoreTokens()) { strTok = new StringTokenizer(reader.readLine()); } return strTok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } public BigDecimal nextBigDecimal() throws IOException { return new BigDecimal(nextToken()); } }
nlogn
166_A. Rank List
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Random; import java.util.TreeSet; public final class CF_599_D1_C { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static class Composite implements Comparable<Composite>{ int idx; int v; public int compareTo(Composite X) { if (v!=X.v) return v-X.v; return idx-X.idx; } public Composite(int idx, int v) { this.idx = idx; this.v = v; } } static void test() { log("testing"); log("done"); } static void explore(ArrayList<Integer>[] components,ArrayList<Integer> bob,int[][] move,ArrayList<int[]>[] howto,int[][] list) { for (int x:bob) { if (components[x].size()==1) { int tm[]=howto[x].get(0); int L=howto[x].size(); howto[x].add(tm); for (int i=0;i<L;i++) { int[] cur=howto[x].get(i); int[] nx=howto[x].get(i+1); int a=cur[0]; int a2=nx[0]; int b2=nx[1]; move[a2][0]=list[a2][b2]; move[a2][1]=a; } } else { explore(components,components[x],move,howto,list); } } } static void process() throws Exception { //arrayTest(); out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); int k=reader.readInt(); int[][] list=new int[k][]; long[] sum=new long[k]; int[] L=new int[k]; HashMap<Integer,int[]> target=new HashMap<Integer,int[]>(); long tot=0; for (int i=0;i<k;i++) { L[i]=reader.readInt(); list[i]=new int[L[i]]; for (int j=0;j<L[i];j++) { list[i][j]=reader.readInt(); sum[i]+=list[i][j]; target.put(list[i][j],new int[] {i,j}); } tot+=sum[i]; } int MX=1<<k; int AX=1000000001; ArrayList<int[]>[] howto=new ArrayList[MX]; log("ok with the data"); if (tot%k!=0) { output("No"); } else { tot/=k; for (int i=0;i<k;i++) { if (sum[i]==tot) { //log("nothing to do for i:"+i); // nothing to do int mask=1<<i; ArrayList<int[]> cand=new ArrayList<int[]>(); cand.add(new int[] {i,0}); howto[mask]=cand; } else for (int j=0;j<L[i];j++) { int u=i; int v=j; boolean ok=true; int src_u=u; int src_v=v; int mask=0; boolean goon=true; ArrayList<int[]> cand=new ArrayList<int[]>(); //log("start loop"); while (goon) { cand.add(new int[] {u,v}); //log("u:"+u+" v:"+v); ok=false; goon=false; long need=tot-((long)sum[u]-(long)list[u][v]); if (Math.abs(need)<=AX) { //log("need:"+need); int nd=(int)need; int[] tm=target.get(nd); //log("tm:"+tm); if (tm!=null) { //log("can find successor"); int nxu=tm[0]; int nxv=tm[1]; if ((mask&(1<<nxu))==0) { mask|=1<<nxu; if (nxu==src_u) { // looping back to source if (nxv==src_v) ok=true; } else { u=nxu; v=nxv; ok=true; goon=true; } } } } } if (ok) { if (howto[mask]==null) { howto[mask]=cand; } } } } log("step 1 done"); // now mask ArrayList[] components=new ArrayList[MX]; int[] msk=new int[MX]; int w=0; for (int m=0;m<MX;m++) { if (howto[m]!=null) { //String s=Integer.toBinaryString(m); //while (s.length()<k) // s="0"+s; //log("found mask:"+s); components[m]=new ArrayList<Integer>(); components[m].add(m); msk[w++]=m; } } int base=w; for (int e=0;e<base;e++) { int a=msk[e]; int ww=w; for (int i=0;i<ww;i++) { int b=msk[i]; if ((b&a)==0) { int c=b|a; //log("creating c:"+c+" "); if (components[c]==null ) { components[c]=new ArrayList<Integer>(); components[c].add(a); components[c].add(b); msk[w++]=c; } } } } //log("msk:"+msk); //log(components[MX-1]); if (components[MX-1]!=null) { output("Yes"); int[][] move=new int[k][2]; explore(components,components[MX-1],move,howto,list); for (int i=0;i<k;i++) { output(move[i][0]+" "+(move[i][1]+1)); } } else { output("No"); } } try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
np
1242_C. Sum Balance
CODEFORCES
import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.concurrent.LinkedBlockingQueue; public class D { static long n; static long x; static long y; static long c; static long f(long t){ long s=0; if(t==0) s=1; else{ s=(4+4*t)/2*t+1; } if(x+t>n){ long c=x+t-n; s-=c*c; } if(x-t<=0){ long c=t-x+1; s-=c*c; } if(y+t>n){ long c=y+t-n; s-=c*c; } if(y-t<=0){ long c=t-y+1; s-=c*c; } if(t>x+y-1){ long m=t-x-y+1; s+=m*(m+1)/2; } if (t>x+n-y) { long m=t-x-n+y; s+=m*(m+1)/2; } if (t>n-x+y) { long m=t-n-y+x; s+=m*(m+1)/2; } if (t>n-x+n-y+1) { long m=t-2*n+x+y-1; s+=m*(m+1)/2; } return s; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner in=new Scanner(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); n=in.nextLong(); x=in.nextLong(); y=in.nextLong(); c=in.nextLong(); long l=0; long r=2*n; while(l<r){ long m=(l+r)/2; long ff=f(m); if(ff<c){ l=m+1; } else{ r=m; } } out.println(l); out.close(); } }
logn
256_B. Mr. Bender and Square
CODEFORCES