src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.io.*; import java.util.*; public class CF { class W implements Comparable<W> { int id, sz; W(int id, int sz) { this.id = id; this.sz = sz; } @Override public int compareTo(W o) { return -Integer.compare(sz, o.sz); } } int[] left; int center; boolean[] used; boolean go(int v) { if (used[v]) return false; used[v] = true; for (int i = 0; i < g[v].size(); ++i) { int to = g[v].get(i); if (to == center) continue; if (left[to] == -1 || go(left[to])) { left[to] = v; return true; } } return false; } ArrayList<Integer>[] g; void solve() { int n = in.nextInt(); int m = in.nextInt(); used = new boolean[n]; g = new ArrayList[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { g[in.nextInt() - 1].add(in.nextInt() - 1); } long st = System.currentTimeMillis(); int ans = Integer.MAX_VALUE; W[] a = new W[n]; for (int i = 0; i < n; i++) { a[i] = new W(i, g[i].size()); } left = new int[n]; Arrays.sort(a); for (int centerId = 0; centerId < n; centerId++) { center = a[centerId].id; if (System.currentTimeMillis() - st > 800) break; int cost = n - g[center].size(); Arrays.fill(left, -1); for (int i = 0; i < n; i++) if (i != center) { boolean has = false; for (int j = 0; j < g[i].size(); j++) { if (g[i].get(j) == center) has = true; } Arrays.fill(used, false); if (!go(i)) { if (has) { cost += g[i].size(); } else { cost += g[i].size() + 2; } } else { if (has) { cost += g[i].size() - 2; } else { cost += g[i].size(); } } } ans = Math.min(ans, cost); } out.println(ans); } FastScaner in; PrintWriter out; void run() { in = new FastScaner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } void runWithFiles() { in = new FastScaner(new File("input.txt")); try { out = new PrintWriter(new File("output.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.close(); } public static void main(String[] args) { Locale.setDefault(Locale.US); new CF().run(); } class FastScaner { BufferedReader br; StringTokenizer st; FastScaner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } FastScaner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.util.Scanner; public class TaskC { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), r = sc.nextInt(); int[] xcords = new int[n]; double[] ycords = new double[n]; double y = r, x = 0, px = 0, ty = 0; for(int i = 0; i < n; i++) { xcords[i] = sc.nextInt(); x = xcords[i]; y = r; for(int j = 0; j < i; j++) { px = xcords[j]; if(Math.abs(px - x) > r*2) continue; ty = Math.sqrt(4*r*r - (x-px)*(x-px)) + ycords[j]; y = Math.max(y, ty); } ycords[i] = y; } for(int i = 0; i < n; i++) { System.out.print(ycords[i] + " "); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.InputStream; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Task { private static final boolean readFromFile = false; public static void main(String args[]){ InputStream inputStream = System.in; OutputStream outputStream = System.out; FileOutputStream fileOutputStream; FileInputStream fileInputStream; if (readFromFile){ try{ fileInputStream = new FileInputStream(new File("input.txt")); fileOutputStream = new FileOutputStream(new File("output.txt")); }catch (FileNotFoundException e){ throw new RuntimeException(e); } } PrintWriter out = new PrintWriter((readFromFile)?fileOutputStream:outputStream); InputReader in = new InputReader((readFromFile)?fileInputStream:inputStream); Solver s = new Solver(in,out); s.solve(); out.close(); } } class Solver{ InputReader in; PrintWriter out; public void solve(){ String s = in.nextLine(); for (int len=s.length()-1;len>=1;len--) for (int i=0;i<s.length()-len+1;i++) for (int j=i+1;j<s.length()-len+1;j++) if (s.substring(i,i+len).equals(s.substring(j,j+len))){ out.println(len); return; } out.println(0); } Solver(InputReader in, PrintWriter out){ this.in=in; this.out=out; } } class InputReader{ private BufferedReader buf; private StringTokenizer tok; InputReader(InputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } InputReader(FileInputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } public String next(){ while (tok==null || !tok.hasMoreTokens()){ try{ tok = new StringTokenizer(buf.readLine()); }catch (IOException e){ throw new RuntimeException(e); } } return tok.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public float nextFloat(){ return Float.parseFloat(next()); } public String nextLine(){ try{ return buf.readLine(); }catch (IOException e){ return null; } } }
cubic
23_A. You're Given a String...
CODEFORCES
/* * Created on 17.05.2019 */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Wolfgang Weck */ public class A01Easy { private static interface Matrix { boolean get(int i, int j); int size(); } private static class MData implements Matrix { private final boolean[][] m; MData(boolean[][] m) { this.m = m; } @Override public boolean get(int i, int j) { return m[i][j]; } @Override public int size() { return m.length; } } private static abstract class MDecorator implements Matrix { protected final Matrix inner; MDecorator(Matrix inner) { this.inner = inner; } @Override public int size() { return inner.size(); } } private static class MHFlip extends MDecorator { MHFlip(Matrix inner) { super(inner); } @Override public boolean get(int i, int j) { return inner.get(size() - 1 - i, j); } } private static class MVFlip extends MDecorator { MVFlip(Matrix inner) { super(inner); } @Override public boolean get(int i, int j) { return inner.get(i, size() - 1 - j); } } private static class MRot extends MDecorator { MRot(Matrix inner) { super(inner); } @Override public boolean get(int i, int j) { return inner.get(j, size() - 1 - i); } } public static void main(String[] args) { try (BufferedReader r = new BufferedReader(new InputStreamReader(System.in))) { final int N = Integer.parseInt(r.readLine()); Matrix m1 = readMatrix(r, N), m2 = readMatrix(r, N); boolean matched = matchesFlipped(m1, m2); int i = 0; while (i < 3 && !matched) { m1 = new MRot(m1); matched = matchesFlipped(m1, m2); i++; } System.out.println(matched ? "Yes" : "No"); } catch (IOException e) { e.printStackTrace(); } } private static Matrix readMatrix(BufferedReader r, int n) throws IOException { boolean[][] m = new boolean[n][n]; for (int i = 0; i < n; i++) { String line = r.readLine(); for (int j = 0; j < n; j++) { m[i][j] = line.charAt(j) == 'X'; } } return new MData(m); } private static boolean matches(Matrix m1, Matrix m2) { int i = 0, j = 0, n = m1.size(); while (i < n && m1.get(i, j) == m2.get(i, j)) { j++; if (j == n) { j = 0; i++; } } return i == n; } private static boolean matchesFlipped(Matrix m1, Matrix m2) { return matches(m1, m2) || matches(new MHFlip(m1), m2) || matches(new MVFlip(m1), m2); } }
quadratic
958_A1. Death Stars (easy)
CODEFORCES
import java.io.* ; import java.util.* ; public class Codeshefcode { final static long r = 1000000007 ; static FasterScanner ip = new FasterScanner() ; static PrintWriter op = new PrintWriter(System.out) ; public static void main(String[] args) throws IOException{ int n = ip.i() ; TreeMap<Character,Integer> map = new TreeMap<Character,Integer>() ; TreeSet<Character> set = new TreeSet<Character>() ; char c[] = ip.S().toCharArray() ; for(char t : c) set.add(t) ; int size = set.size() ; for(int i=0 ; i<size ; i++) map.put(set.pollFirst(),i) ; int a[] = new int[n] ; for(int i=0 ; i<n ; i++) a[i]=map.get(c[i]) ; int erl[][] = new int[size][n] ; for(int i=0 ; i<size ; i++) for(int j=n-1 ; j>=0 ; j--) erl[i][j]=(a[j]==i) ? j : (j==n-1 ? -1 : erl[i][j+1]) ; long min = Long.MAX_VALUE ; for(int i=0 ; i<n ; i++){ long maxt = Long.MIN_VALUE ; for(int j=0 ; j<size ; j++) if(erl[j][i]!=-1) maxt = Long.max(maxt,(erl[j][i]-i+1)) ; else{ maxt = Long.MAX_VALUE ; break ; } min = Long.min(min,maxt) ; } op.print(min) ; Finish() ; } static void Finish(){ op.flush(); op.close(); } } @SuppressWarnings("serial") class MyList extends ArrayList<Long>{ } class pair { private int x ; private int y ; pair(int a,int b){ x=a ; y=b ; } public int x(){ return x ; } public int y(){ return y ; } } class FasterScanner { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FasterScanner() { this(System.in); } public FasterScanner(InputStream is) { mIs = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine(){ int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String S(){ int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); }while (!isSpaceChar(c)); return res.toString(); } public long l(){ int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); }while(!isSpaceChar(c)); return res * sgn; } public int i(){ int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); }while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String ns = sc.next(); sc.close(); int n1 = Integer.parseInt(ns); int n2 = Integer.parseInt(ns.substring(0, ns.length() - 1)); int n3 = Integer.parseInt(ns.substring(0, ns.length() - 2) + ns.substring(ns.length() - 1)); int max = n1; max = (n2 > max) ? (n2) : (max); max = (n3 > max) ? (n3) : (max); System.out.println(max); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.NoSuchElementException; public class Main { static PrintWriter out; static InputReader ir; static void solve() { int n = ir.nextInt(); int t = ir.nextInt(); int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = ir.nextIntArray(2); long[] f = fact(15); long res = 0; for (int i = 0; i < 1 << n; i++) { int[] ct = new int[4]; int tot = 0; for (int j = 0; j < n; j++) { if (((1 << j) & i) != 0) { tot += a[j][0]; ct[a[j][1]]++; } } if (tot != t) continue; long[][][][] dp = new long[ct[1] + 1][ct[2] + 1][ct[3] + 1][4]; dp[0][0][0][0] = 1; for (int j = 0; j < ct[1] + ct[2] + ct[3]; j++) { for (int k = 0; k <= ct[1]; k++) { for (int l = 0; l <= ct[2]; l++) { if (k + l > j || j - k - l > ct[3]) continue; for (int m = 0; m <= 3; m++) { for (int o = 0; o <= 3; o++) { if (m == o) continue; if (o == 1 && k == ct[1]) continue; if (o == 2 && l == ct[2]) continue; if (o == 3 && j - k - l == ct[3]) continue; if (o == 1) { dp[k + 1][l][j - k - l][1] = add(dp[k + 1][l][j - k - l][1], dp[k][l][j - k - l][m]); } if (o == 2) { dp[k][l + 1][j - k - l][2] = add(dp[k][l + 1][j - k - l][2], dp[k][l][j - k - l][m]); } if (o == 3) { dp[k][l][j - k - l + 1][3] = add(dp[k][l][j - k - l + 1][3], dp[k][l][j - k - l][m]); } } } } } } for (int m = 0; m <= 3; m++) res = add(res, mul(mul(f[ct[1]], f[ct[2]]), mul(f[ct[3]], dp[ct[1]][ct[2]][ct[3]][m]))); } out.println(res); } static long mod = (long) 1e9 + 7; static long add(long a, long b) { return (a + b) % mod; } static long sub(long a, long b) { long d = a - b; while (d < 0) d += mod; return d; } static long mul(long a, long b) { return a * b % mod; } static long div(long a, long b) { return a * mod_inverse(b) % mod; } private static long[] fact(int n) { long[] ret = new long[n + 1]; ret[0] = 1 % mod; for (int i = 1; i <= n; i++) { ret[i] = mul(ret[i - 1], i); } return ret; } private static long[] factInv(int n) { long[] ret = new long[n + 1]; ret[0] = 1; for (int i = 1; i <= n; i++) { ret[i] = div(ret[i - 1], i); } return ret; } public static long comb(int n, int m, long[] fact, long[] factInv) { long ret = fact[n]; ret = mul(ret, factInv[m]); ret = mul(ret, factInv[n - m]); return ret; } public static long[][] stirling(int n) { long[][] ret = new long[n + 1][n + 1]; ret[0][0] = 1; for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) ret[i][j] = add(ret[i - 1][j - 1], mul(ret[i - 1][j], j)); return ret; } public static long mod_inverse(long a) { long[] ret = extgcd(a, mod); return add(mod, ret[0] % mod); } public static long[] extgcd(long a, long b) { long[] ret = new long[3]; ret[2] = _extgcd(a, b, ret); return ret; } private static long _extgcd(long a, long b, long[] x) { long g = a; x[0] = 1; x[1] = 0; if (b != 0) { g = _extgcd(b, a % b, x); long temp = x[0]; x[0] = x[1]; x[1] = temp; x[1] -= (a / b) * x[0]; } return g; } static long modpow(long a, long n) { long res = 1; while (n > 0) { if ((n & 1) != 0) res = res * a % mod; a = a * a % mod; n >>= 1; } return res; } public static void main(String[] args) { ir = new InputReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } static void tr(Object... o) { out.println(Arrays.deepToString(o)); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class CF1009E { static final int MD = 998244353; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] aa = new int[1 + n]; for (int i = 1, a = 0; i <= n; i++) aa[i] = a = (a + Integer.parseInt(st.nextToken())) % MD; int[] pp = new int[n]; pp[0] = 1; for (int i = 1, p = 1; i < n; i++) { pp[i] = p; p = p * 2 % MD; } int d = 0; long ans = 0; for (int i = n - 1; i >= 0; i--) { // rest at i d = (d * 2 % MD + aa[n - 1 - i]) % MD; // rest again before n ans = (ans + (long) (d + aa[n - i]) * pp[i]) % MD; } System.out.println(ans); } }
linear
1009_E. Intercity Travelling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class OlyaAndMagicalSquare { void solve() { long[] dp = new long[32]; dp[0] = 0; for (int i = 1; i < 32; i++) { dp[i] = 4 * dp[i - 1] + 1; } int T = in.nextInt(); L: while (T-- > 0) { int n = in.nextInt(); long k = in.nextLong(); if (n > 31) { out.println("YES " + (n - 1)); continue; } long tot = 0; for (int a = n - 1; a >= 0; a--) { k -= (1L << (n - a)) - 1; if (k < 0) break; if (k == 0) { out.println("YES " + a); continue L; } long limit = (1L << (n + 1 - a)) - 3; if (k <= tot || dp[a] > 0 && (k - tot + dp[a] - 1) / dp[a] <= limit) { out.println("YES " + a); continue L; } tot += dp[a] * limit; } out.println("NO"); } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new OlyaAndMagicalSquare().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class SequenceTransformation { void solve() { int p = 1, n = in.nextInt(); while (n > 0) { if (n == 1) { out.print(p + " "); break; } if (n == 2) { out.print(p + " "); out.print(2 * p + " "); break; } if (n == 3) { out.print(p + " "); out.print(p + " "); out.print(3 * p + " "); break; } for (int i = 0; i < (n + 1) / 2; i++) { out.print(p + " "); } p *= 2; n /= 2; } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new SequenceTransformation().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
linear
1059_C. Sequence Transformation
CODEFORCES
import java.io.*; import java.util.*; public class Main{ public static void main( String[] args ){ Scanner cin = new Scanner( System.in ); String s = cin.next(); int n = s.length(); char[] ss = new char[ n ]; ss = s.toCharArray(); int ans = 0; for (int i=0; i<n; i++) for (int j=i+1; j<n; j++){ int k = 0; while ( i+k<n && j+k<n && ss[i+k] == ss[j+k] ) k++; ans = Math.max( ans, k ); } System.out.println( ans ); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); long totalBlocks = 0; long a[] = new long[n]; for(int i = 0; i < n; ++i) { a[i] = sc.nextLong(); totalBlocks += a[i]; } Arrays.sort(a); long selected = 0; for(int i = 0; i < n; ++i) { if(a[i] > selected) selected++; } long leftCols = a[n - 1] - selected; long remBlocks = totalBlocks - leftCols - n; System.out.print(remBlocks); } }
nlogn
1061_B. Views Matter
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class CF_1029E_Tree_with_Small_Distances { static ArrayList<Integer> adj[]; static int dist[]; static boolean visitParent[]; static int ans=0; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n =sc.nextInt(); adj=new ArrayList[n+1]; dist = new int[n+1]; visitParent = new boolean[n+1]; for(int i=0;i<=n;i++) adj[i]=new ArrayList<Integer>(); int max=0; //first contribution for(int i=1;i<n;i++){ int u = sc.nextInt(),v=sc.nextInt(); adj[u].add(v); adj[v].add(u); } dist[1]=0; dfs(1,1); System.out.println(ans); } private static void dfs(int i , int j) { // TODO Auto-generated method stub boolean f = false; for(int k=0;k<adj[i].size();k++){ int x = adj[i].get(k); if(x!=j){ dist[x]=dist[i]+1; dfs(x,i); if(visitParent[x]) f=true; } } //System.out.println(Arrays.toString(dist)); if(dist[i]>2&&!visitParent[j]&&!f&&!visitParent[i]){ visitParent[j]=true; ans++; for(int v=0;v<adj[i].size();v++){ } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public 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 boolean ready() throws IOException {return br.ready(); } } }
linear
1029_E. Tree with Small Distances
CODEFORCES
import java.util.*; import java.io.*; public class a { static long mod = 1000000009; static ArrayList<Integer>[] g; public static void main(String[] args) throws IOException { //Scanner input = new Scanner(new File("input.txt")); //PrintWriter out = new PrintWriter(new File("output.txt")); input.init(System.in); PrintWriter out = new PrintWriter((System.out)); int n = input.nextInt(), m = input.nextInt(), k = input.nextInt(); long border = n-n/k; if(m<=border) out.println(m); else { long count = m- border; long first = ((pow(2, count+1) + mod - 2)*k)%mod; first += m - k*count; out.println(first%mod); } out.close(); } static long pow(long x, long p) { if(p==0) return 1; if((p&1) > 0) { return (x*pow(x, p-1))%mod; } long sqrt = pow(x, p/2); return (sqrt*sqrt)%mod; } static long gcd(long a, long b) { if(b==0) return a; return gcd(b, a%b); } static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary 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() ); } static String nextLine() throws IOException { return reader.readLine(); } } }
logn
338_A. Quiz
CODEFORCES
import java.util.Scanner; public class Prob023A { public static void main( String[] Args ) { Scanner scan = new Scanner( System.in ); String s = scan.next(); all: for ( int x = s.length() - 1; x >= 0; x-- ) for ( int y = 0; x + y <= s.length(); y++ ) { String sub = s.substring( y, y + x ); if ( s.indexOf( sub, y + 1 ) >= 0 ) { System.out.println( x ); break all; } } } }
cubic
23_A. You're Given a String...
CODEFORCES
//package codeforces_464_div2; import java.util.*; import java.util.stream.Collectors; public class F { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); int[][] sub = new int[n][n]; for (int i = 0; i < n; i++) { sub[i][i] = arr[i]; for (int j = i + 1; j < n; j++) { sub[i][j] = sub[i][j - 1] + arr[j]; } } HashMap<Integer, List<P>> hm = new HashMap<>(); /*for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { if (hm.containsKey(sub[i][j])) { hm.get(sub[i][j]).add(new P(i, j)); } else { List<P> temp = new ArrayList<>(); temp.add(new P(i, j)); hm.put(sub[i][j], temp); } } }*/ for(int stop=0; stop<n; stop++) { for(int start=0; start<=stop; start++) { if (hm.containsKey(sub[start][stop])) { hm.get(sub[start][stop]).add(new P(start, stop)); } else { List<P> temp = new ArrayList<>(); temp.add(new P(start, stop)); hm.put(sub[start][stop], temp); } } } int ans = Integer.MIN_VALUE; /*for(Map.Entry it : hm.entrySet()) { int or = overlap(it.getValue()); ans = Math.max(ans, or); }*/ List<P> ansList = null; for (List<P> it : hm.values()) { int or = overlap(it); if(or>ans) { ans = or; ansList = it; } } List<P> processedList = extractOverlapping(ansList); System.out.println(ans); for(int i=0; i<processedList.size(); i++) { int A = processedList.get(i).a + 1; int B = processedList.get(i).b + 1; System.out.println(A + " " + B); } } public static int overlap(List<P> listOfPair) { /*List<P> sortedList = listOfPair.stream() .sorted((pair1, pair2) -> pair1.getB().compareTo(pair2.getB())) .collect(Collectors.toList());*/ List<P> sortedList = listOfPair; int cnt = 0; int end = sortedList.get(0).b; for (int i = 1; i < sortedList.size(); i++) { if (sortedList.get(i).a <= end) { cnt++; } else { end = sortedList.get(i).b; } } return sortedList.size() - cnt; } public static List<P> extractOverlapping(List<P> ansList) { List<P> sortedList = ansList.stream() .sorted((pair1, pair2) -> pair1.getB().compareTo(pair2.getB())) .collect(Collectors.toList()); List<P> finalList = new ArrayList<>(); finalList.add(sortedList.get(0)); int end = sortedList.get(0).b; for (int i = 1; i < sortedList.size(); i++) { if (sortedList.get(i).a <= end) { continue; } else { finalList.add(sortedList.get(i)); end = sortedList.get(i).b; } } return finalList; } } class P implements Comparable<P> { Integer a; Integer b; public P(int a, int b) { this.a = a; this.b = b; } public Integer getA() { return a; } public Integer getB() { return b; } @Override public int compareTo(P that) { return this.b.compareTo(that.b); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.*; public class B { BufferedReader in; PrintStream out; StringTokenizer tok; public B() throws NumberFormatException, IOException { in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new FileReader("in.txt")); out = System.out; run(); } void run() throws NumberFormatException, IOException { int n = nextInt(); int k = nextInt(); int[] num = new int[n]; for(int i = 0; i < n; i++) num[i] = nextInt(); int[] cant = new int[100001]; int cnt = 0; int r = 0; for(; r < n; r++) { if(cant[num[r]]==0)cnt++; cant[num[r]]++; if(cnt==k) break; } if(cnt<k) { out.println("-1 -1"); return; } int l = 0; for(; l < r; l++) { cant[num[l]]--; if(cant[num[l]]==0)cnt--; if(cnt<k) break; } out.println((l+1)+" "+(r+1)); } public static void main(String[] args) throws NumberFormatException, IOException { new B(); } String nextToken() throws IOException { if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
linear
224_B. Array
CODEFORCES
/** * Author: Ridam Nagar * Date: 27 February 2019 * Time: 01:17:36 **/ /* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { static String reverse(String s){ String reverse=""; for(int i=s.length()-1;i>=0;i--){ reverse=reverse + s.charAt(i); } return reverse; } public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int x=m%(int)Math.pow(2,n); System.out.println(x); } }
constant
913_A. Modular Exponentiation
CODEFORCES
//package com.example.programming; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class Test { static class Pair { int f,s; public Pair(int x, int y) {f = x; s = y;} } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] s = br.readLine().split(" "); int[] arr = new int[n]; for(int i = 0; i<n; i++) arr[i] = Integer.parseInt(s[i]); HashMap<Integer, ArrayList<Pair>> map = new HashMap<>(); for(int i = 0; i<n; i++) { int sum = 0; for(int j = i; j>=0; j--) { sum += arr[j]; ArrayList<Pair> list = map.get(sum); if(list == null) { list = new ArrayList<>(); map.put(sum, list); } list.add(new Pair(j, i)); } } Iterator it = map.entrySet().iterator(); ArrayList<Pair> ans = new ArrayList<>(); for(;it.hasNext();){ Map.Entry<Integer, ArrayList<Pair>> entry = (Map.Entry<Integer, ArrayList<Pair>>)it.next(); ArrayList<Pair> list = entry.getValue(); ArrayList<Pair> pre = new ArrayList<>(); int r = -1; for(Pair p : list) { if(p.f > r) { pre.add(p); r = p.s; } } if(ans.size()<pre.size()) ans = pre; } StringBuilder sb = new StringBuilder(); sb.append(ans.size()).append('\n'); for(Pair p : ans) { sb.append(p.f+1).append(' ').append(p.s+1).append('\n'); } System.out.print(sb); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; import java.io.*; public class C{ static PrintWriter out; static InputReader in; public static void main(String args[]){ out = new PrintWriter(System.out); in = new InputReader(); new C(); out.flush(); out.close(); } C(){ int w = solve(); out.print(w == 0 ? "sjfnb" : "cslnb"); } int n; long a[]; int solve(){ n = in.nextInt(); a = new long[n]; long sum = 0; for(int i = 0; i < n; i++)sum += a[i] = in.nextLong(); if(sum == 0){ return 1; } Arrays.sort(a); int c = 0, c0 = 0; long p = -1, max = 0; int f = 0; long t = -1; int pp = -1; for(int i = 0; i < n; i++){ if(a[i] == p){ c++; }else{ if(p == 0)c0 = c; if(c >= 2){f++; t = p; pp = i - 2;} max = Math.max(max, c); p = a[i]; c = 1; } } max = Math.max(max, c); sum = 0; if(c >= 2){f++; t = p; pp = n - 2;} if(max > 2 || c0 > 1 || f > 1)return 1; if(f == 1){ long v = Arrays.binarySearch(a, t - 1); if(v >= 0)return 1; a[pp]--; sum = 1; } p = -1; for(int i = 0; i < n; i++){ sum += a[i] - (p + 1); a[i] = p + 1; p = a[i]; } return 1 - (int)(sum % 2); } public static class InputReader{ BufferedReader br; StringTokenizer st; InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){} } return st.nextToken(); } } }
linear
1190_B. Tokitsukaze, CSL and Stone Game
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.StringTokenizer; public class LuxuriousHouses { public static void main(String[] args) throws IOException { System.out.println(25); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public 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 boolean ready() throws IOException { return br.ready(); } } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskG solver = new TaskG(); solver.solve(1, in, out); out.close(); } static class TaskG { static final long MODULO = (long) (1e9 + 7); public void solve(int testNumber, InputReader in, PrintWriter out) { String x = in.next(); int[][] comb = new int[x.length() + 2][x.length() + 2]; comb[0][0] = 1; for (int i = 1; i < comb.length; ++i) { comb[i][0] = 1; for (int j = 1; j < comb.length; ++j) { comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]) % (int) MODULO; } } int[][] pow = new int[11][x.length() + 2]; for (int i = 0; i < pow.length; ++i) { pow[i][0] = 1; for (int j = 1; j < pow[i].length; ++j) { pow[i][j] = (int) (i * (long) pow[i][j - 1] % MODULO); } } int[] oneSum = new int[x.length() + 2]; for (int i = 1; i < oneSum.length; ++i) { oneSum[i] = (int) ((10 * (long) oneSum[i - 1] + 1) % MODULO); } int[][] s1 = new int[10][x.length() + 1]; int[][] s2 = new int[10][x.length() + 1]; for (int what = 1; what <= 9; ++what) { for (int max = 0; max <= x.length(); ++max) { long sum1 = 0; long sum2 = 0; for (int equalExtra = 0; equalExtra <= max; ++equalExtra) { long cways = 1; cways *= comb[max][equalExtra]; cways %= MODULO; cways *= pow[what][max - equalExtra]; cways %= MODULO; sum1 += cways * oneSum[equalExtra]; sum1 %= MODULO; sum2 += cways; sum2 %= MODULO; } s1[what][max] = (int) sum1; s2[what][max] = (int) sum2; } } int[] sofar = new int[10]; long res = 0; for (int firstLess = 0; firstLess < x.length(); ++firstLess) { int min = 0; int max = x.charAt(firstLess) - '0'; if (firstLess < x.length() - 1) --max; for (int dig = min; dig <= max; ++dig) { ++sofar[dig]; int totalSofar = firstLess + 1; int sofarBigger = 0; for (int what = 9; what >= 1; --what) { int sofarThisOrLess = totalSofar - sofarBigger; int sofarThis = sofar[what]; int sofarLess = sofarThisOrLess - sofarThis; for (int bigger = sofarBigger; bigger + sofarThisOrLess <= x.length(); ++bigger) { long ways = comb[x.length() - totalSofar][bigger - sofarBigger]; ways *= pow[9 - what][bigger - sofarBigger]; ways %= MODULO; long sum1 = s1[what][x.length() - bigger - sofarThisOrLess]; long sum2 = s2[what][x.length() - bigger - sofarThisOrLess]; long sum = (sum1 * (long) pow[10][sofarThis] + sum2 * oneSum[sofarThis]) % MODULO; sum *= pow[10][bigger]; sum %= MODULO; res = (res + sum * ways % MODULO * what) % MODULO; } sofarBigger += sofarThis; } --sofar[dig]; } ++sofar[x.charAt(firstLess) - '0']; } out.println(res); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } } }
quadratic
908_G. New Year and Original Order
CODEFORCES
import java.io.*; public class again_25 { public static void main(String ar[])throws IOException { long n; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); n=Long.parseLong(br.readLine()); System.out.println("25"); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.*; import java.util.*; public class Main { private void run() throws IOException { int cx = in.nextInt(); int cy = in.nextInt(); int n = in.nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = in.nextInt() - cx; y[i] = in.nextInt() - cy; } int[] dp = new int[1 << n]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; int[] prev = new int[1 << n]; for (int mask = 0; mask < (1 << n); ++mask) { if (dp[mask] == Integer.MAX_VALUE) { continue; } for (int i = 0; i < n; ++i) { if (((mask >> i) & 1) == 0) { if (dp[mask | (1 << i)] > dp[mask] + dist(x[i], y[i])) { dp[mask | (1 << i)] = dp[mask] + dist(x[i], y[i]); prev[mask | (1 << i)] = mask; } for (int j = i + 1; j < n; ++j) { if (((mask >> j) & 1) == 0) { if (dp[mask | (1 << i) | (1 << j)] > dp[mask] + dist(x[i], y[i], x[j], y[j])) { dp[mask | (1 << i) | (1 << j)] = dp[mask] + dist(x[i], y[i], x[j], y[j]); prev[mask | (1 << i) | (1 << j)] = mask; } } } break; } } } out.println(dp[(1 << n) - 1]); int mask = (1 << n) - 1; out.print(0); while (mask != 0) { int p = prev[mask]; int cur = p ^ mask; List<Integer> who = new ArrayList<Integer>(); for (int i = 0; i < n; ++i) { if (((cur >> i) & 1) != 0) { who.add(i + 1); } } for (int t : who) { out.print(" " + t); } out.print(" " + 0); mask = p; } out.flush(); } private int dist(int x, int y, int x2, int y2) { return x * x + y * y + x2 * x2 + y2 * y2 + (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y); } private int dist(int x, int y) { return 2 * (x * x + y * y); } private class Scanner { private StringTokenizer tokenizer; private BufferedReader reader; public Scanner(Reader in) { reader = new BufferedReader(in); tokenizer = new StringTokenizer(""); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean hasNext() throws IOException { while (!tokenizer.hasMoreTokens()) { String next = reader.readLine(); if (next == null) return false; tokenizer = new StringTokenizer(next); } return true; } public String next() throws IOException { hasNext(); return tokenizer.nextToken(); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } } public static void main(String[] args) throws IOException { new Main().run(); } Scanner in = new Scanner(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Colours { public static void main(String args[] ) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int n = Integer.parseInt(line); line = br.readLine(); String[] values = line.split(" "); int[] arr = new int[n]; TreeSet<Integer> set = new TreeSet<>(); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(values[i]); set.add(arr[i]); } int count=0; TreeSet<Integer> copy = new TreeSet<>(); // for(int i=0;i<n;i++) copy.addAll(set); int prev = copy.size(); for(Integer i: set){ // System.out.println("i "+i); if(copy.size()==0){ break; } Iterator<Integer> iterator = copy.iterator(); while (iterator.hasNext()) { Integer e = iterator.next(); if (e % i == 0) { iterator.remove(); } } if(copy.size()!=prev){ count++; prev = copy.size(); } // System.out.println("size "+copy.size()); } System.out.println(count); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import static java.lang.Math.*; import static java.lang.Integer.*; import static java.lang.Long.*; import static java.lang.Character.*; @SuppressWarnings("unused") public class round176B { 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 n = parseLong(next()); long k = parseLong(next()); if(n == 1){ System.out.println(0); return; } if (n <= k) { System.out.println(1); return; } if ((((k * (k + 1)) / 2) - 1) - (k - 2) < n) { System.out.println(-1); } else { long lo = 1; long hi = k + 1; int best = Integer.MAX_VALUE; while (lo < hi) { long mid = lo + ((hi - lo) / 2); long first = ((mid * (2 + (2 + (mid - 1)))) / 2) - (mid - 1); long last = ((mid * (k - mid + 1 + k)) / 2) - (mid - 1); if (n < first) { hi = mid; } else { if (n >= first && n <= last) { hi = mid; best = min(best, (int) mid); } else lo = mid + 1; } } System.out.println(best); } } }
logn
287_B. Pipeline
CODEFORCES
import java.util.*; import java.io.*; public class Main { static Scanner cin = new Scanner(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter cout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static void main(String[] agrs) throws IOException{ String line = cin.nextLine(); HashMap<String, Integer> map = new HashMap<String, Integer>(); int ans = 0; for (int i = 0; i < line.length(); ++i) { StringBuffer str = new StringBuffer(""); for (int j = i; j < line.length(); ++j) { str.append(line.charAt(j)); if (!map.containsKey(str.toString())) { //cout.println(str.toString()); map.put(str.toString(), 1); } else { ans = str.length() > ans ? str.length() : ans; } } } cout.println(ans); cin.close(); cout.close(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class CF274A { public static void main(String[] args) throws Exception { new CF274A().solve(); } private void solve() throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long k = sc.nextInt(); Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } Arrays.sort(a); HashSet<Integer> used = new HashSet<>(n); int count = 0; for (int i = 0; i < n; i++) { Integer v = a[i]; if (!used.contains(v)) { count++; long next = v * k; if (next <= 1000000000) used.add((int) next); } } System.out.println(count); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author emotionalBlind */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { int[] lo; int[] hi; long[][][][][] dp; long[] posVal; long go(int pos, int isAGreaterLo, int isALessHi, int isBGreaterLo, int isBLessHi) { if (pos == 63) { return 0; } if (dp[pos][isAGreaterLo][isALessHi][isBGreaterLo][isBLessHi] != -1) { return dp[pos][isAGreaterLo][isALessHi][isBGreaterLo][isBLessHi]; } // range a int ua = 0; int va = 1; if (isALessHi == 0 && hi[pos] == 0) { va = 0; } if (isAGreaterLo == 0 && lo[pos] == 1) { ua = 1; } // range b; int ub = 0; int vb = 1; if (isBLessHi == 0 && hi[pos] == 0) { vb = 0; } if (isBGreaterLo == 0 && lo[pos] == 1) { ub = 1; } long res = 0; dp[pos][isAGreaterLo][isALessHi][isBGreaterLo][isBLessHi] = 0; for (int i = ua; i <= va; ++i) { int newIsAGreaterLo = isAGreaterLo; int newIsALessHi = isALessHi; if (i < hi[pos]) newIsALessHi = 1; if (i > lo[pos]) newIsAGreaterLo = 1; for (int j = ub; j <= vb; ++j) { int newIsBGreaterLo = isBGreaterLo; int newIsBLessHi = isBLessHi; if (j < hi[pos]) newIsBLessHi = 1; if (j > lo[pos]) newIsBGreaterLo = 1; long val = 0; if (i != j) val = posVal[pos]; val += go(pos + 1, newIsAGreaterLo, newIsALessHi, newIsBGreaterLo, newIsBLessHi); res = Math.max(res, val); } } dp[pos][isAGreaterLo][isALessHi][isBGreaterLo][isBLessHi] = res; return res; } public void solve(int testNumber, InputReader in, OutputWriter out) { lo = new int[63]; hi = new int[63]; long a = in.readLong(); long b = in.readLong(); Binary.convertBinary(a, lo); Binary.convertBinary(b, hi); posVal = new long[63]; posVal[62] = 1; for (int i = 61; i >= 0; --i) { posVal[i] = posVal[i + 1] * 2; } dp = new long[65][2][2][2][2]; for (long[][][][] a1 : dp) { for (long[][][] a2 : a1) { for (long[][] a3 : a2) { for (long[] a4 : a3) { Arrays.fill(a4, -1); } } } } long res = go(0, 0, 0, 0, 0); out.printLine(res); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { // InputMismatchException -> UnknownError if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(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(); } } class Binary { public static void convertBinary(long val, int[] a) { int last = a.length - 1; Arrays.fill(a, 0); while (val > 0) { a[last] = (int) (val % 2); last--; val /= 2; } } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.util.*; import java.io.*; public class A1 { public static BufferedReader br; public static StringTokenizer st; public static String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return st.nextToken(); } public static Integer nextInt() { return Integer.parseInt(next()); } public static Long nextLong() { return Long.parseLong(next()); } public static Double nextDouble() { return Double.parseDouble(next()); } static long fast_pow(long base,long n,long M) { if(n==0) return 1; if(n==1) return base; long halfn=fast_pow(base,n/2,M); if(n%2==0) return ( halfn * halfn ) % M; else return ( ( ( halfn * halfn ) % M ) * base ) % M; } static long finextDoubleMMI_fermat(long n,int M) { return fast_pow(n,M-2,M); } static long nCrModPFermat(int n, int r, int p) { if (r == 0) return 1; long[] fac = new long[n+1]; fac[0] = 1; for (int i = 1 ;i <= n; i++) fac[i] = fac[i-1] * i % p; return (fac[n]* finextDoubleMMI_fermat(fac[r], p)% p * finextDoubleMMI_fermat(fac[n-r], p) % p) % p; } static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } static void sort(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort(arr, l, m); sort(arr , m+1, r); merge(arr, l, m, r); } } static void sort(int arr[]) { int l=0; int r=arr.length-1; if (l < r) { int m = (l+r)/2; sort(arr, l, m); sort(arr , m+1, r); merge(arr, l, m, r); } } static long gcd(long a, long b){ if(a%b==0) return b; if(b%a==0) return a; if(a>b) return gcd(a%b,b); return gcd(a,b%a); } static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static void main(String args[])throws IOException{ int i,j; br = new BufferedReader(new InputStreamReader(System.in)); int n=nextInt(); int a[]=new int[n]; for(i=0;i<n;i++) a[i]=nextInt(); Arrays.sort(a); int l=0; for(i=0;i<n;i++){ if(a[i]!=-1){ int p=a[i]; for(j=i;j<n;j++){ if(a[j]%p==0) a[j]=-1; } l++; } } pw.println(l); pw.close(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.Scanner; public class Main { static class LeftOver { int a; long b; long c; LeftOver(int a, long b, long c) { this.a = a; this.b = b; this.c = c; } } private static long pow(long base, long coe) { if (coe == 0) return 1; if (coe == 1) return base; long res = pow(base, coe / 2); if (coe % 2 == 0) { return res * res; } else { return res * res * base; } } private static void getLen(long n) { long tmp = 0; int cnt = 0; while(tmp < n) { ++cnt; tmp += cnt * 9 * pow(10, cnt - 1); } if (tmp == n) System.out.println("9"); else { tmp -= cnt * 9 * pow(10, cnt - 1); long ans = (n - tmp - 1) / cnt + pow(10, cnt - 1); System.out.println(String.valueOf(ans).charAt((int) ((n - tmp - 1) % cnt))); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); getLen(n); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.io.*; public class Main { boolean eof; String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "-1"; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } void solve() { long n = nextInt(), ans = n; if (n % 6 == 0) { ans = Math.max((n - 1) * (n - 2) * (n - 3), ans); } else if (n % 2 == 0) { ans = Math.max(ans, n * (n - 1) * (n - 3)); } else { ans = Math.max(n * (n - 1) * (n - 2), ans); } out.print(ans); } BufferedReader br; StringTokenizer st; PrintWriter out; void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); // br = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter(new FileWriter("output.txt")); solve(); br.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new Main().run(); } }
constant
235_A. LCM Challenge
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; public class d { double a, v, l, d, w; private void solve() throws Exception { a = nextInt(); v = nextInt(); l = nextInt(); d = nextInt(); w = nextInt(); double ans; if (w >= v){ ans = fromSign(0, l); } else{ double tToW = w / a; double dToW = tToW * tToW * a / 2.; if (dToW > d){ double curT = Math.sqrt(d * 2. / a); ans = curT; double curV = a * curT; ans += fromSign(curV, l - d); } else{ double tToMax = v / a; double dToMax = tToMax * tToMax * a / 2.; double tFromMax = (v - w) / a; double dFromMax = tFromMax * v - tFromMax * tFromMax * a / 2.; if (dToMax + dFromMax <= d){ ans = tToMax + tFromMax + (d - dToMax - dFromMax) / v; } else{ double lo = w, hi = v; for (int i = 0; i < 1000; ++i){ double mi = (lo + hi) / 2.; double tTo = mi / a; double dTo = tTo * tTo * a / 2.; double tFrom = (mi - w) / a; double dFrom = tFrom * mi - tFrom * tFrom * a / 2.; if (dTo + dFrom <= d) lo = mi; else hi = mi; } ans = lo / a + (lo - w) / a; } ans += fromSign(w, l - d); } } out.printf("%.8f", ans); } private double fromSign(double curV, double d) { double tToMax = (v - curV) / a; double dToMax = tToMax * curV + tToMax * tToMax * a / 2.; if (dToMax <= d){ return tToMax + (d - dToMax) / v; } else{ double lo = 0, hi = tToMax; for (int i = 0; i < 1000; ++i){ double mi = (lo + hi) / 2.; double curD = mi * curV + mi * mi * a / 2.; if (curD <= d) lo = mi; else hi = mi; } return lo; } } public void run() { try { solve(); } catch (Exception e) { NOO(e); } finally { out.close(); } } PrintWriter out; BufferedReader in; StringTokenizer St; void NOO(Exception e) { e.printStackTrace(); System.exit(1); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String nextToken() { while (!St.hasMoreTokens()) { try { String line = in.readLine(); St = new StringTokenizer(line); } catch (Exception e) { NOO(e); } } return St.nextToken(); } private d(String name) { try { in = new BufferedReader(new FileReader(name + ".in")); St = new StringTokenizer(""); out = new PrintWriter(new FileWriter(name + ".out")); } catch (Exception e) { NOO(e); } } private d() { try { in = new BufferedReader(new InputStreamReader(System.in)); St = new StringTokenizer(""); out = new PrintWriter(System.out); } catch (Exception e) { NOO(e); } } public static void main(String[] args) { Locale.setDefault(Locale.US); new d(/*"d"*/).run(); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.lang.*; import java.util.function.Predicate; public class Main{ public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static long MOD = (long) (1e9 + 7); // static long MOD = 998244353; static long MOD2 = MOD * MOD; static FastReader sc = new FastReader(); static int pInf = Integer.MAX_VALUE; static int nInf = Integer.MIN_VALUE; static long ded = (long)(1e17)+9; public static void main(String[] args) throws Exception { int test = 1; // test = sc.nextInt(); for (int i = 1; i <= test; i++){ // out.print("Case #"+i+": "); solve(); } out.flush(); out.close(); } static int n,m; static int[][] hor,ver; static Long[][][] dp; static void solve(){ n = sc.nextInt(); m = sc.nextInt(); int k = sc.nextInt(); dp = new Long[n+1][m+1][k+1]; hor = new int[n][m-1]; ver = new int[n-1][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m-1; j++){ hor[i][j] = sc.nextInt(); } } for(int i = 0; i < n-1; i++){ for(int j = 0; j < m; j++){ ver[i][j] = sc.nextInt(); } } if(k%2==1){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ out.print(-1+" "); } out.println(); } return; } k = k/2; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ long ans = cal(i,j,k); out.print((2*ans)+" "); } out.println(); } } static long cal(int i, int j,int k){ if(k==0)return 0; if(dp[i][j][k]!=null)return dp[i][j][k]; long ans = ded; for(int h = 0; h < 4; h++){ int ni = i+di[h]; int nj = j+dj[h]; if(e(ni,nj)){ int cost = 0; if(ni==i){ if(nj>j){ cost = hor[i][j]; }else{ cost = hor[i][nj]; } }if(nj==j){ if(ni>i){ cost = ver[i][j]; }else{ cost = ver[ni][j]; } } ans = Math.min(ans,(cost)+cal(ni,nj,k-1)); } } return dp[i][j][k] = ans; } static int[] di = new int[]{0,-1,0,1}; static int[] dj = new int[]{-1,0,1,0}; static boolean e(int i, int j){ return i>=0&&j>=0&&i<n&&j<m; } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o){ return this.x-o.x; } @Override public String toString() { return "Pair{" + "x=" + x + ", y=" + y + '}'; } public boolean equals(Pair o){ return this.x==o.x&&this.y==o.y; } } public static long mul(long a, long b) { return ((a % MOD) * (b % MOD)) % MOD; } public static long add(long a, long b) { return ((a % MOD) + (b % MOD)) % MOD; } public static long c2(long n) { if ((n & 1) == 0) { return mul(n / 2, n - 1); } else { return mul(n, (n - 1) / 2); } } //Shuffle Sort static final Random random = new Random(); static void ruffleSort(int[] a) { int n = a.length;//shuffle, then sort for (int i = 0; i < n; i++) { int oi = random.nextInt(n); int temp= a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } //Brian Kernighans Algorithm static long countSetBits(long n) { if (n == 0) return 0; return 1 + countSetBits(n & (n - 1)); } //Euclidean Algorithm static long gcd(long A, long B) { if (B == 0) return A; return gcd(B, A % B); } //Modular Exponentiation static long fastExpo(long x, long n) { if (n == 0) return 1; if ((n & 1) == 0) return fastExpo((x * x) % MOD, n / 2) % MOD; return ((x % MOD) * fastExpo((x * x) % MOD, (n - 1) / 2)) % MOD; } //AKS Algorithm static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i <= Math.sqrt(n); i += 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static long modinv(long x) { return modpow(x, MOD - 2); } public static long modpow(long a, long b) { if (b == 0) { return 1; } long x = modpow(a, b / 2); x = (x * x) % MOD; if (b % 2 == 1) { return (x * a) % MOD; } return x; } 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.*; import java.io.*; public final class CF { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); ArrayList<String> a = new ArrayList<>(); for(int i = 0; i<n; i++) a.add(sc.next()); int count = 0; for(int i = 0; i<n; i++) { String b = sc.next(); int idx = a.indexOf(b); if(idx!=-1) a.remove(idx); else count++; } System.out.println(count); } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.util.*; public class Test { public static void main(String[] args) { Scanner t = new Scanner(System.in); int n=t.nextInt(); int a[]= new int[n]; for(int i=0; i<n; i++) a[i]=t.nextInt(); Arrays.sort(a); int r=a[0]; for(int i=1; i<n; i++) if(a[i]!=r) { System.out.println(a[i]); System.exit(0); } System.out.println("NO"); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class ProblemB { public static void main(String[] args) throws IOException { ProblemB solver = new ProblemB(); solver.init(); solver.solve(); } private void init() { } private void solve() throws IOException { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = in.nextInt(); int x = in.nextInt(); int y = in.nextInt(); int c = in.nextInt(); long lo = 0; long hi = 2 * n; while (lo < hi) { long mid = (lo + hi)/2; long r = count(n, x , y, mid); if (r < c) { lo = mid + 1; } else { hi = mid;; } } out.println(lo); out.flush(); out.close(); } private long count(int n, int x, int y, long steps) { long r = 1 + 2 * steps * (1 + steps); r -= countWall(x - 1 - steps); r -= countWall(y - 1 - steps); r -= countWall(n - (x + steps)); r -= countWall(n - (y + steps)); r += countCorner(steps - (x - 1) - (y - 1) - 1); r += countCorner(steps - (y - 1) - (n - x) - 1); r += countCorner(steps - (n - x) - (n - y) - 1); r += countCorner(steps - (x - 1) - (n - y) - 1); return r; } private long countCorner(long x) { if (x <= 0) return 0; return x * ( x + 1) / 2; } private long countWall(long x) { if (x >= 0) return 0; return x * x; } private static class Reader { BufferedReader reader; StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ Reader(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ public String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt( next() ); } public double nextDouble() throws IOException { return Double.parseDouble( next() ); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class C { static int[] nm; static int ans = 0; static int rows, cols; static boolean[][] cae; static int[][] ca; public static void main(String[] args) throws IOException { nm = readIntArray(); rows = Math.max(nm[0], nm[1]); cols = Math.min(nm[0], nm[1]); long s = System.currentTimeMillis(); cae = new boolean[1000][50]; ca = new int[1000][50]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < cols; i++) { sb.append('1'); } int startingState = Integer.parseInt(sb.toString(), 3); ans = solve(startingState, 0); System.out.println(nm[0]*nm[1] - ans); // System.out.println(System.currentTimeMillis() - s ); } static int solve(int state, int row) { if (row == rows) { return 0; } if (cae[state][row]) { return ca[state][row]; } int ans = Integer.MAX_VALUE; for (int i = 0; i < Math.pow(3, cols); i++) { boolean isCover = covers(i, state); if (isCover && (row < rows - 1 || coversTotally(i, state))) { int p = placed(i); int s = solve(i, row + 1); ans = Math.min(ans, s + p); } } cae[state][row] = true; ca[state][row] = ans; return ans; } private static boolean coversTotally(int i, int state) { String bottom = decode(i); for (int j = 0; j < bottom.length(); j++) { if (bottom.charAt(j) == '0') { return false; } } return true; } private static boolean covers(int i, int state) { String top = decode(state); String bottom = decode(i); for (int j = 0; j < top.length(); j++) { if (top.charAt(j) == '0' && bottom.charAt(j) != '2') { return false; } if (top.charAt(j) == '2' && bottom.charAt(j) == '0') { return false; } } for (int j = 0; j < top.length(); j++) { if (bottom.charAt(j) == '1' && (top.charAt(j) != '2' && !(j > 0 && bottom.charAt(j-1) == '2') && !(j < top.length() - 1 && bottom.charAt(j+1) == '2'))) { return false; } } return true; } private static int placed(int i) { String s = decode(i); int cnt = 0; for (int j = 0; j < s.length(); j++) { if (s.charAt(j) == '2') { cnt++; } } return cnt; } private static String decode(int state) { String tmp = Integer.toString(state, 3); if (tmp.length() < cols) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < cols - tmp.length(); i++) { sb.append('0'); } sb.append(tmp); return sb.toString(); } else { return tmp; } } static int countDispositionDivisors(int[] d) { HashSet<Integer> div = new HashSet<Integer>(); for (int i = 1; i <= d.length; i++) { for (int j = 0; j < d.length; j++) { if ((j + 1) % i == 0 && d[j] % i == 0) { div.add(j + 1); break; } } } return div.size(); } static InputStreamReader isr = new InputStreamReader(System.in); static BufferedReader br = new BufferedReader(isr); static int[] readIntArray() throws IOException { String[] v = br.readLine().split(" "); int[] ans = new int[v.length]; for (int i = 0; i < ans.length; i++) { ans[i] = Integer.valueOf(v[i]); } return ans; } static long[] readLongArray() throws IOException { String[] v = br.readLine().split(" "); long[] ans = new long[v.length]; for (int i = 0; i < ans.length; i++) { ans[i] = Long.valueOf(v[i]); } return ans; } static <T> void print(List<T> v) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < v.size(); i++) { if (sb.length() > 0) { sb.append(' '); } sb.append(v.get(i)); } System.out.println(sb); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); long l = in.nextLong(); long r = in.nextLong(); in.close(); if (r - l < 2) { System.out.println(-1); return; } if ((r - l > 2)||(l%2 ==0 )) { long s = l + l%2; System.out.println(s+" "+(s+1)+" "+(s+2)); } else { if (l%2 == 1) { System.out.println(-1); } else{ long s = l; System.out.println(s+" "+(s+1)+" "+(s+2)); } } } static long gcd(long a, long b) { if(a==0) { return b; } if (b==0) { return a; } if (a > b) { return gcd (a%b, b); } return gcd (b%a, a); } }
constant
483_A. Counterexample
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author BSRK Aditya (bsrkaditya@gmail.com) */ 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 { long n,x,y,c; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.readInt(); x = in.readInt(); y = in.readInt(); c = in.readInt(); int lo = -1; int hi = (int)c; while(lo+1<hi) { int mi = (lo+hi)/2; if(P(mi)) hi = mi; else lo = mi; } out.printLine(hi); } private boolean P(int t) { if(t == -1) return false; int ans = 0; for(long i = Math.max(1,y-t); i <= Math.min(y+t,n); ++i) { long a = Math.abs(y - i); ans += D(Math.max(1,x-t+a), Math.min(n,x+t-a)); if(ans >= c) return true; } return false; } private long D(long a, long b) { return b - a + 1; } } 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 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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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(); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.util.Scanner; public class DigitalSequence { public static void print(String s) { System.out.println(s); } public static void main(String[] args) { long k = new Scanner(System.in).nextLong(); long i = 1,t=0, c = 9,digits = 0,l=0,k2=k; while(t<k){ l = t; t += i*c; i++; c*=10; digits++; } k = k-l; long lastNumber = (long)Math.pow(10,digits-1)-1; long p = k/digits,q=k%digits; long finalNumber =lastNumber+p; if(q!=0){ finalNumber++; } k = k-digits*p; if(k<=0) k+=digits; String ans = ""+finalNumber; int index = (int)(k-1); print(""+ans.charAt(index)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; public class Main { long n; long maxlcm; void run(){ n = cin.nextInt(); if(n == 1 || n ==2) maxlcm = n; else if(n >= 3){ if(n % 2 != 0){ maxlcm = n * (n-1) * (n - 2); } else if(n%3 != 0) maxlcm = n * (n-1) * (n - 3); else maxlcm = (n - 1) * (n - 2) * (n - 3); } System.out.println(maxlcm); } public static void main(String[] args) { new Main().run(); } Scanner cin = new Scanner(new BufferedInputStream(System.in)); }
constant
235_A. LCM Challenge
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.StringTokenizer; public class A { static void solve(InputReader in, PrintWriter out) { long n = in.nextLong(); out.print(25); } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public long nextDouble() { return Long.parseLong(next()); } } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.BufferedOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class Task { public static void solve() throws Exception { int n = nextInt(); int[] S = new int[n]; for(int i=0;i<n;i++) { S[i] = nextInt(); if(i > 0) { S[i] += S[i-1]; } } Map<Integer, List<L>> map = new HashMap<>(); for(int j=0;j<n;j++) { for(int i=j;i>=0;i--) { int sum = S[j]; if(i > 0) { sum -= S[i-1]; } L l = new L(); l.a = i; l.b = j; List<L> list = map.get(sum); if(list == null) { list = new ArrayList<>(); map.put(sum, list); } list.add(l); } } List<L> longest = null; for(Integer sum: map.keySet()) { List<L> list = map.get(sum); Collections.sort(list); List<L> list2 = new ArrayList<>(list.size()); int from = list.get(0).a; for(L l: list) { if(l.a >= from) { list2.add(l); from = l.b + 1; } } if(longest == null || longest.size() < list2.size()) { longest = list2; } } println(longest.size()); for(int i=0;i<longest.size();i++) { L l = longest.get(i); println((l.a+1) + " " + (l.b+1)); } } private static class L implements Comparable<L>{ int a; int b; @Override public int compareTo(L l2) { return Integer.valueOf(b).compareTo(l2.b); } } public static void main(String[] args) throws Exception { try { fastReader = new FastReader(System.in); systemOut = new BufferedOutputStream(System.out); solve(); } finally { systemOut.close(); } } private static FastReader fastReader = null; private static BufferedOutputStream systemOut = null; public static void print(Object obj) { print(obj.toString()); } public static void print(String str) { try { systemOut.write(str.getBytes("utf-8")); } catch (Exception ex) { throw new RuntimeException(ex); } } public static void println(Object obj) { println(obj.toString()); } public static void println(String str) { try { print(str); systemOut.write('\n'); } catch (Exception ex) { throw new RuntimeException(ex); } } public static String next() { return fastReader.readNextToken(false); } public static String nextLine() { return fastReader.readNextToken(true); } public static int nextInt() { return Integer.parseInt(fastReader.readNextToken(false)); } public static long nextLong() { return Long.parseLong(fastReader.readNextToken(false)); } public static double nextDouble() { return Double.parseDouble(fastReader.readNextToken(false)); } static class FastReader { private byte[] buf = new byte[65536]; private int ind = 0; private int maxInd = -1; private InputStream is = null; private boolean eof = false; private boolean lastCharRead = false; public FastReader(InputStream is) { this.is = is; } public String readNextToken(boolean endOfLine) { try { StringBuilder sb = new StringBuilder(); boolean found = false; while (true) { if (lastCharRead) { return null; } else if (ind > maxInd) { if (eof) { lastCharRead = true; } else { fillBuffer(); } } byte b = '\n'; if (!lastCharRead) { b = buf[ind++]; } if (b == '\r') { // ignore } else if ((b == '\n' && endOfLine) || (Character.isWhitespace(b) && !endOfLine)) { if (found) { break; } } else { sb.append((char) b); found = true; } } return sb.toString(); } catch (Exception ex) { throw new RuntimeException(ex); } } private void fillBuffer() { try { int read = is.read(buf, 0, buf.length); if (read < buf.length) { eof = true; } ind = 0; maxInd = read - 1; } catch (Exception ex) { throw new RuntimeException(ex); } } } public static class LST { public long[][] set; public int n; public LST(int n) { this.n = n; int d = 1; for (int m = n; m > 1; m >>>= 6, d++) ; set = new long[d][]; for (int i = 0, m = n >>> 6; i < d; i++, m >>>= 6) { set[i] = new long[m + 1]; } } // [0,r) public LST setRange(int r) { for (int i = 0; i < set.length; i++, r = r + 63 >>> 6) { for (int j = 0; j < r >>> 6; j++) { set[i][j] = -1L; } if ((r & 63) != 0) set[i][r >>> 6] |= (1L << r) - 1; } return this; } // [0,r) public LST unsetRange(int r) { if (r >= 0) { for (int i = 0; i < set.length; i++, r = r + 63 >>> 6) { for (int j = 0; j < r + 63 >>> 6; j++) { set[i][j] = 0; } if ((r & 63) != 0) set[i][r >>> 6] &= ~((1L << r) - 1); } } return this; } public LST set(int pos) { if (pos >= 0 && pos < n) { for (int i = 0; i < set.length; i++, pos >>>= 6) { set[i][pos >>> 6] |= 1L << pos; } } return this; } public LST unset(int pos) { if (pos >= 0 && pos < n) { for (int i = 0; i < set.length && (i == 0 || set[i - 1][pos] == 0L); i++, pos >>>= 6) { set[i][pos >>> 6] &= ~(1L << pos); } } return this; } public boolean get(int pos) { return pos >= 0 && pos < n && set[0][pos >>> 6] << ~pos < 0; } public LST toggle(int pos) { return get(pos) ? unset(pos) : set(pos); } public int prev(int pos) { for (int i = 0; i < set.length && pos >= 0; i++, pos >>>= 6, pos--) { int pre = prev(set[i][pos >>> 6], pos & 63); if (pre != -1) { pos = pos >>> 6 << 6 | pre; while (i > 0) pos = pos << 6 | 63 - Long.numberOfLeadingZeros(set[--i][pos]); return pos; } } return -1; } public int next(int pos) { for (int i = 0; i < set.length && pos >>> 6 < set[i].length; i++, pos >>>= 6, pos++) { int nex = next(set[i][pos >>> 6], pos & 63); if (nex != -1) { pos = pos >>> 6 << 6 | nex; while (i > 0) pos = pos << 6 | Long.numberOfTrailingZeros(set[--i][pos]); return pos; } } return -1; } private static int prev(long set, int n) { long h = set << ~n; if (h == 0L) return -1; return -Long.numberOfLeadingZeros(h) + n; } private static int next(long set, int n) { long h = set >>> n; if (h == 0L) return -1; return Long.numberOfTrailingZeros(h) + n; } @Override public String toString() { List<Integer> list = new ArrayList<Integer>(); for (int pos = next(0); pos != -1; pos = next(pos + 1)) { list.add(pos); } return list.toString(); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author George Marcus */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { long left = in.nextLong(); long right = in.nextLong(); long ans = go(left, right); out.println(ans); } private long go(long A, long B) { int bA = -1; for(int i = 62; i >= 0; i--) if((A & (1L << i)) > 0) { bA = i; break; } int bB = -1; for(int i = 62; i >= 0; i--) if((B & (1L << i)) > 0) { bB = i; break; } if(bB == -1) return 0; if(bA < bB) return allOne(bB); else return go(A ^ (1L << bA), B ^ (1L << bB)); } private long allOne(int bits) { long ret = 0; for(int i = 0; i <= bits; i++) ret |= (1L << i); return ret; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public long nextLong() { return Long.parseLong(nextString()); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.util.*; import java.io.*; public class _1523_C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(in.readLine()); while(t-- > 0) { int n = Integer.parseInt(in.readLine()); int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = Integer.parseInt(in.readLine()); } boolean[][] used = new boolean[n][n + 1]; boolean[] used2 = new boolean[n]; String[][] res = new String[n][2]; res[0][0] = "1"; res[0][1] = ""; for(int i = 1; i < n; i++) { if(a[i] == 1) { for(int j = i - 1; j >= 0; j--) { if(!used[j][a[i]] && !used2[j]) { res[i][0] = res[j][0] + ".1"; res[i][1] = res[j][0]; used[j][a[i]] = true; break; } } }else { for(int j = i - 1; j >= 0; j--) { if(!used[j][a[i]] && !used2[j] && a[j] == a[i] - 1) { if(res[j][1].equals("")) { res[i][0] = "" + a[i]; }else { res[i][0] = res[j][1] + "." + a[i]; } res[i][1] = res[j][1]; used[j][a[i]] = true; break; } used2[j] = true; } } } for(int i = 0; i < n; i++) { out.println(res[i][0]); } } in.close(); out.close(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class CodeForce { private void solve() throws IOException { final int N = nextInt(); int []A = new int[N]; for(int i = 0; i < N; i++) A[i] = nextInt(); Arrays.sort(A); if(A[N-1] == 1) A[N-1] = 2; else A[N-1] = 1; Arrays.sort(A); for(int i = 0; i < N; i++) System.out.print(A[i] + " "); } public static void main(String[] args) { new CodeForce().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(new FileOutputStream(new File("output.txt"))); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
nlogn
135_A. Replacement
CODEFORCES
//package contese_476; import java.util.*; public class q1 { int m=(int)1e9+7; public class Node { int a; int b; public void Node(int a,int b) { this.a=a; this.b=b; } } public int mul(int a ,int b) { a=a%m; b=b%m; return((a*b)%m); } public int pow(int a,int b) { int x=1; while(b>0) { if(b%2!=0) x=mul(x,a); a=mul(a,a); b=b/2; } return x; } public static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); HashMap<Integer,Integer> h=new HashMap(); //HashMap<Integer,Integer> h1=new HashMap(); int[] a=new int[n]; int x=sc.nextInt(); for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(h.get(a[i])==null) { h.put(a[i], 1); //h1.put(a[i],i); } else { System.out.print(0); System.exit(0); } } for(int i=0;i<n;i++) { int num=a[i]&x; if(num==a[i]) continue; if(h.get(num)==null) continue; else { System.out.print(1); System.exit(0); } } for(int i=0;i<n;i++) { int num=a[i]&x; if(num==a[i]) continue; if(h.get(num)==null) h.put(num, 1); else { System.out.print(2); System.exit(0); } } System.out.print(-1); } }
linear
1013_B. And
CODEFORCES
import java.util.Scanner; public class A275 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); long a=sc.nextLong(); long b=sc.nextLong(); if(b-a<2){ System.out.println(-1); }else if(b-a==2 && a%2==1){ System.out.println(-1); }else if(b-a==2 && a%2==0){ System.out.println(a+" "+(a+1)+" "+(a+2)); }else{ if(a%2==0){ System.out.println(a+" "+(a+1)+" "+(a+2)); }else{ System.out.println((a+1)+" "+(a+2)+" "+(a+3)); } } } }
constant
483_A. Counterexample
CODEFORCES
import java.util.Scanner; /** * Created by mmaikovych on 18.02.16. */ public class EER_A { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); scanner.nextLine(); System.out.println(25); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.util.*; import java.io.*; import java.text.*; public class Main { //SOLUTION BEGIN //Into the Hardware Mode void pre() throws Exception{} void solve(int TC) throws Exception { long K = nl(); K--; int sz = 1;long pw = 1; while(K >= pw){ long npw = pw*10; long dig = sz*(npw-pw); if(K >= dig){ K -= dig; sz++;pw *= 10; }else break; } long num = pw+K/sz; int dig = sz-(int)(K%sz)-1; while(dig-->0)num /= 10; pn(num%10); } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} void exit(boolean b){if(!b)System.exit(0);} static void debug(Object... o){System.err.println(Arrays.deepToString(o));} final long IINF = (long)2e18; final int INF = (int)1e9+2; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8; static boolean multipleTC = false, memory = true, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ long ct = System.currentTimeMillis(); if (fileIO) { in = new FastReader(""); out = new PrintWriter(""); } else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = multipleTC? ni():1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); System.err.println(System.currentTimeMillis() - ct); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } int[][] make(int n, int e, int[] from, int[] to, boolean f){ int[][] g = new int[n][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = to[i]; if(f)g[to[i]][--cnt[to[i]]] = from[i]; } return g; } int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){ int[][][] g = new int[n][][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0}; if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1}; } return g; } int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));} int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
//>>>BaZ<<<// import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static int dx[] = {-1,1,0,0}; static int dy[] = {0,0,1,-1}; static long MOD = 1000000007; static int INF = Integer.MAX_VALUE/10; static PrintWriter pw; static Reader scan; //static MyFileReader scan; //static MyFileReader1 ss; static int ni() throws IOException{return scan.nextInt();} static long nl() throws IOException{return scan.nextLong();} static double nd() throws IOException{return scan.nextDouble();} static void pl() throws IOException{pw.println();} static void pl(Object o) throws IOException{pw.println(o);} static void p(Object o) throws IOException {pw.print(o+" ");} static void psb(StringBuilder sb) throws IOException {pw.print(sb);} public static void main(String[] args){ new Thread(null,null,"BaZ",99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { Calendar CAL1 = Calendar.getInstance(); CAL1.setTime(new Date()); scan = new Reader(); //scan = new MyFileReader(); //ss = new MyFileReader1(); pw = new PrintWriter(System.out,true); //pw = new PrintWriter(new File("C://Users/Aman deep/Desktop/output.txt")); StringBuilder sb = new StringBuilder(); int n = ni(); int inv = 0; int arr[] = new int[n]; for(int i=0;i<n;++i) { arr[i] = ni(); for(int j=0;j<i;++j) if(arr[j]>arr[i]) inv = 1-inv; } int q = ni(); while(q-->0) { int l = ni(); int r = ni(); int par = c2(r-l+1); par&=1; if(par!=0) inv = 1-inv; if(inv==0) sb.append("even\n"); else sb.append("odd\n"); } psb(sb); Calendar CAL2 = Calendar.getInstance(); CAL2.setTime(new Date()); double Execution_Time = (double)(CAL2.getTimeInMillis()-CAL1.getTimeInMillis())/1000.000; //System.out.println("Execution time : "+Execution_Time+" seconds"); pw.flush(); pw.close(); } static int c2(int n) { return (n*(n-1))>>1; } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static class MyFileReader //File input template { StringTokenizer st; BufferedReader br; MyFileReader() throws IOException { br = new BufferedReader(new FileReader("C://Users/Aman deep/Desktop/input.txt")); } String nextLine() throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(nextLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } static class MyFileReader1 //File input template { StringTokenizer st; BufferedReader br; MyFileReader1() throws IOException { br = new BufferedReader(new FileReader("C://Users/Aman deep/Desktop/output.txt")); } String nextLine() throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(nextLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; public class hackerearth { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); HashMap<String,Integer> map=new HashMap<>(); HashMap<String,Integer> map2=new HashMap<>(); for(int i=0;i<n;i++) { String s=sc.next(); if(map.containsKey(s)) map.put(s,map.get(s)+1); else map.put(s,1); } for(int i=0;i<n;i++) { String s=sc.next(); if(map2.containsKey(s)) map2.put(s,map2.get(s)+1); else map2.put(s,1); if(map.containsKey(s)) { int feq = map.get(s); feq--; if (feq <= 0) map.remove(s); else map.put(s, feq); } } int ans=0; for(Map.Entry<String,Integer> entry:map.entrySet()) { ans+=entry.getValue(); } System.out.println(ans); } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.*; import java.util.ArrayDeque; import java.util.Queue; import java.util.StringTokenizer; public class CodeForces { public static void main(String[] args) throws FileNotFoundException { FastIO io = new FastIO(); int width = io.nextInt(); int height = io.nextInt(); int initials = io.nextInt(); boolean[][] visited = new boolean[width][height]; Queue<Coordinate> q = new ArrayDeque<>(); for (int i = 0; i < initials; i++) { q.add(new Coordinate(io.nextInt() - 1, io.nextInt() - 1)); } Coordinate oneOfLast = null; while (!q.isEmpty()) { int len = q.size(); for (int times = 0; times < len; times++) { Coordinate c = q.poll(); if (visited[c.x][c.y]) { continue; } oneOfLast = c; visited[c.x][c.y] = true; int[][] deltas = new int[][]{ {-1, 0}, {0, -1}, {1, 0}, {0, 1} }; for (int[] delta : deltas) { int ci = c.y + delta[0]; int cj = c.x + delta[1]; if (ci >= 0 && cj >= 0 && ci < height && cj < width) { q.add(new Coordinate(cj, ci)); } } } } io.println((oneOfLast.x + 1) + " " + (oneOfLast.y + 1)); io.close(); } static class Coordinate { int x; int y; public Coordinate(int x, int y) { this.x = x; this.y = y; } } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() throws FileNotFoundException { super(new BufferedOutputStream(new FileOutputStream("output.txt"))); br = new BufferedReader(new InputStreamReader(new FileInputStream("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 nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } } }
cubic
35_C. Fire Again
CODEFORCES
import java.util.Scanner; public class Solution { public static void main(String[] args) { long b=0;long p=1; Scanner s=new Scanner(System.in); long m=s.nextLong(); long x=1; do{ p=(m+b)/x; b=10*b+10; x++; }while(p/(long)Math.pow(10, x-1)!=0); rest : x--;b=b/10-1; b=x*p-b; b=m-b; b=x-b-1; p/=(long)Math.pow(10, b); p%=10; System.out.println(p); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class Solution { public static void main(String[] args) { Solution solution = new Solution(); solution.solve(); } private void solve() { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t -- > 0) { long n = in.nextLong(); long k = in.nextLong(); System.out.println(solve(n, k)); } } private String solve(long n, long k) { if (n > 31) return "YES " + (n - 1); if (k > f(n)) return "NO"; long square = 1; long splitDone = 0; long size = n; long splitLeft = 0; while (splitDone + square <= k && size > 0) { splitDone += square; --size; splitLeft += (square * 2 - 1) * f(size); square = square * 2 + 1; } // System.out.println(square + " " + splitDone + " " + size + " " + splitLeft); if (k > splitDone + splitLeft) return "NO"; else return "YES " + size; } private long f(long x) { return ((1L << (2 * x)) - 1) / 3; } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.util.*; public class LookingForOrder { public Scanner in = new Scanner(System.in); public PrintStream out = System.out; public int[] go; public int[][] cost; public int [] sol; public Pair[] how; public int n, lim; public Pair bag; public Pair[] obj; public void main() { bag = new Pair(in.nextInt(), in.nextInt()); n = in.nextInt(); obj = new Pair[n]; for(int i=0;i<n;++i) obj[i] = new Pair(in.nextInt(), in.nextInt()); go = new int[n]; cost = new int[n][n]; for(int i=0;i<n;++i) { go[i] = squDist(bag, obj[i]); for(int j=0;j<n;++j) cost[i][j] = squDist(obj[i], obj[j]); } lim = (1<<n); sol = new int[lim]; Arrays.fill(sol, -1); how = new Pair[lim]; out.println(solve(lim-1)); Pair T; int set = lim-1; out.print("0"); while(set > 0) { solve(set); T = how[set]; out.print(" "+(T.x+1)); set = off(T.x, set); if(T.y >= 0) { out.print(" " + (T.y+1)); set = off(T.y, set); } out.print(" 0"); } out.println(); }//end public void main() public int oo = 987654321; public boolean in(int x, int set) { return ((1<<x) & set) != 0; } //Turn on bit x public int on(int x, int set) { return (set | (1<<x)); } //Turn off bit x public int off(int x, int set) { return (set ^ (set & (1<<x)) ); } public int solve(int set) { if(sol[set] >= 0) return sol[set]; int ret; if(set == 0) ret = 0; else { ret = oo; int x, y, sub, c; for(x=0;x<n;++x) if(in(x, set)) break; sub = off(x, set); c = go[x]+go[x]+solve(sub); if(c < ret) { how[set] = new Pair(x, -1); ret = c; } for(y=x+1;y<n;++y) if(in(y, set)) { c = go[x]+cost[x][y]+go[y] + solve(off(y, sub)); if(c < ret) { ret = c; how[set] = new Pair(x, y); } } } return sol[set] = ret; } public int squDist(int ax, int ay, int bx, int by) { int dx, dy; dx = ax - bx; dy = ay - by; return dx*dx + dy*dy; } public int squDist(Pair p, Pair q) { return squDist(p.x, p.y, q.x, q.y); } //int pair private class Pair implements Comparable<Pair> { public int x, y; public Pair(int xx, int yy) { x = xx; y = yy; } public int compareTo(Pair u) { if(x!=u.x) return x-u.x; return y-u.y; } public String toString() { return "(" + x + "," + y + ")"; } } public static void main(String[] args) { (new LookingForOrder()).main(); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.Arrays; import java.util.InputMismatchException; public class TestClass11 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub InputReader in=new InputReader(System.in); OutputWriter out=new OutputWriter(System.out); int n=in.readInt(); String s=in.readString(); int low[]=new int[26]; int upper[]=new int[26]; boolean islow[]=new boolean[26]; boolean isupper[]=new boolean[26]; Arrays.fill(low,Integer.MAX_VALUE); Arrays.fill(upper, Integer.MAX_VALUE); int ans[]=new int[n]; int finalsans=Integer.MAX_VALUE; for(int i=0;i<n;i++){ int c=s.charAt(i); if(c>='a'&&c<='z'){ islow[c-'a']=true; } else{ isupper[c-'A']=true; } } for(int i=n-1;i>=0;i--){ int c=s.charAt(i); if(c>='a'&&c<='z'){ low[c-'a']=i; } else{ upper[c-'A']=i; } for(int j=0;j<26;j++){ if(islow[j]==true){ ans[i]=Math.max(ans[i], low[j]); } } for(int j=0;j<26;j++){ if(isupper[j]==true){ ans[i]=Math.max(ans[i], upper[j]); } } finalsans=Math.min(ans[i]-i+1, finalsans); } System.out.println(finalsans); } } 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 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 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); } } 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(); } public void flush() { writer.flush(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test3 { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int x=Integer.parseInt(br.readLine()); int y=Integer.parseInt(br.readLine()); System.out.print((int)(y%(Math.pow(2, x)))); } }
constant
913_A. Modular Exponentiation
CODEFORCES
//package round455; 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 C { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int mod = 1000000007; long[] dp = new long[5005]; dp[0] = 1; for(int i = 0;i < n;i++){ char c = nc(); if(c == 's'){ if(i < n-1){ for(int j = 5003;j >= 0;j--){ dp[j] += dp[j+1]; if(dp[j] >= mod)dp[j] -= mod; } } }else{ for(int j = 5003;j >= 0;j--){ dp[j+1] = dp[j]; } dp[0] = 0; } } long ans = 0; for(int i = 0;i < 5005;i++)ans += dp[i]; out.println(ans % mod); } 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 C().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)); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: Administrator * Date: 13.05.11 * Time: 23:21 * To change this template use File | Settings | File Templates. */ public class ToyArmies { public static void main(String[] args) { Scanner in = new Scanner(System.in); long n = in.nextLong(); System.out.print(String.format("%d",(long)(n*1.5))); } }
constant
84_A. Toy Army
CODEFORCES
import java.util.Scanner; /** * * @author Ronak */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner in=new Scanner(System.in); int n=in.nextInt(); if(n>=3&&n<=100) { int num[]=new int[n]; for(int i=0;i<n;i++) { num[i]=in.nextInt(); } int even=0,odd=0,ceven=0,codd=0; for(int i=0;i<n;i++) { if(num[i]%2==0) { even++; ceven=i+1; } else { odd++; codd=i+1; } } if(odd==1) { System.out.println(""+codd); } else { System.out.println(""+ceven); } } } }
linear
25_A. IQ test
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.util.concurrent.*; public final class on_the_bench { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static int[] parent,size; static int maxn=(int)500; static long mod=(long)(1e9+7); static int[] fact,inv_fact; static int getParent(int u) { if(u==parent[u]) { return u; } else { int val=getParent(parent[u]);parent[u]=val; return val; } } static void merge(int u,int v) { int x=getParent(u),y=getParent(v); if(x!=y) { parent[y]=x; size[x]+=size[y];size[y]=0; } } static int add(long a,long b) { long ret=a+b; if(ret>=mod) { ret%=mod; } return (int)ret; } static int mul(long a,long b) { long ret=a*b; if(ret>=mod) { ret%=mod; } return (int)ret; } static int pow(long a,long b) { long x=1,y=a; while(b>0) { if(b%2==1) { x=mul(x,y); } y=mul(y,y);b=b/2; } return (int)(x%mod); } static void build() { fact=new int[maxn];inv_fact=new int[maxn];fact[0]=1; for(int i=1;i<maxn;i++) { fact[i]=mul(fact[i-1],i); } inv_fact[maxn-1]=pow(fact[maxn-1],mod-2); for(int i=maxn-2;i>=0;i--) { inv_fact[i]=mul(inv_fact[i+1],(i+1)); } } static int[] mul_poly(int[] a,int[] b,int deg1,int deg2) { int[] ret=new int[deg1+deg2+1]; for(int i=0;i<=deg1;i++) { for(int j=0;j<=deg2;j++) { int curr=mul(a[i],b[j]); ret[i+j]=add(ret[i+j],curr); } } return ret; } static int C(int n,int r) { if(n-r<0 || Math.min(n,r)<0) { return 0; } int val1=fact[n],val2=inv_fact[r],val3=inv_fact[n-r]; int mul=mul(val2,val3); return mul(val1,mul); } public static void main(String args[]) throws Exception { int n=sc.nextInt();build(); int[] a=new int[n];parent=new int[n];size=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); parent[i]=i; size[i]=1; } for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { long curr=a[i]*1L*a[j],now=(long)Math.sqrt(curr); if(now*now==curr) { merge(i,j); } } } List<Integer> list=new ArrayList<>(); for(int i=0;i<n;i++) { if(getParent(i)==i) { list.add(size[i]); } } // out.println(list); int res=0;int[] poly=new int[1];poly[0]=1; for(int i=0;i<list.size();i++) { int size=list.get(i); int[] arr=new int[size];arr[0]=1; for(int j=1;j<size;j++) { int now1=C(size,j),now2=mul(fact[size-1],inv_fact[size-1-j]); int qq=mul(now1,now2); arr[j]=qq; } poly=mul_poly(poly,arr,poly.length-1,size-1); } for(int i=1,x=1;i<poly.length;i++,x*=-1) { int now=add(x,mod); int curr=mul(fact[n-i],poly[i]); curr=mul(curr,now); res=add(res,curr); } // out.println(res); int zz=mul(res,mod-1);res=add(fact[n],zz); out.println(res);out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
cubic
840_C. On the Bench
CODEFORCES
import javafx.collections.transformation.SortedList; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Array; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scan scan = new Scan(); int n = scan.scanInt(); long d = scan.scanLong(); long a[]=new long[n]; for(int i=0;i<n;i++){ a[i]=scan.scanLong(); } Arrays.sort(a); int count=0; for(int i=0;i<n-1;i++){ if((a[i+1]-d)>(a[i]+d)){ count+=2; }else if((a[i+1]-d)==(a[i]+d)){ count++; } } count+=2; System.out.println(count); } static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public char scanchar()throws IOException { int n=scan(); while(isWhiteSpace(n)) n=scan(); return (char)n; // int neg=1; // while(!isWhiteSpace(n)) // { // if(n>='0'&&n<='9') // { // integer*=10; // integer+=n-'0'; // n=scan(); // } // else throw new InputMismatchException(); // } // return neg*integer; } public long scanLong()throws IOException { long lng=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n) && n!='.') { if(n>='0'&&n<='9') { lng*=10; lng+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); long temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; lng+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return neg*lng; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class FireAgain { static int n; static int m; public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader r = new BufferedReader(new FileReader("input.txt")); String s = r.readLine(); String[] sp = s.split(" "); n = new Integer(sp[0]); m = new Integer(sp[1]); boolean[][] v = new boolean[n][m]; r.readLine(); s = r.readLine(); sp = s.split(" "); Queue<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < sp.length; i += 2) { v[new Integer(sp[i]) - 1][new Integer(sp[i + 1]) - 1] = true; q.add(new Integer(sp[i]) - 1); q.add(new Integer(sp[i + 1]) - 1); } int[] dx = { 1, -1, 0, 0 }; int[] dy = { 0, 0, 1, -1 }; int lx = -1; int ly = -1; while (!q.isEmpty()) { int x = q.remove(); int y = q.remove(); lx = x; ly = y; for (int i = 0; i < dy.length; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (valid(nx, ny) && !v[nx][ny]) { v[nx][ny] = true; q.add(nx); q.add(ny); } } } lx++; ly++; BufferedWriter wr=new BufferedWriter(new FileWriter("output.txt")); wr.write(""+lx + " " + ly); wr.newLine(); wr.close(); } private static boolean valid(int nx, int ny) { return nx >= 0 && nx < n && ny >= 0 && ny < m; } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; import java.util.Comparator; public class Main { private static StreamTokenizer in; private static PrintWriter out; static { in = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); out = new PrintWriter(System.out); } private static int nextInt() throws Exception { in.nextToken(); return (int) in.nval; } private static double nextDouble() throws Exception { in.nextToken(); return in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } public static void main(String[] args) throws Exception { int n = nextInt(), k = nextInt(), A = nextInt(), r = n + k - 1; int[][] s = new int[n][]; for (int i = 0; i < n; i++) { s[i] = new int[] { nextInt(), nextInt() }; } double max = 0; int[] prb = new int[n]; for (int u = (1 << r); u >= 0; u--) { // проверим на n-1 единичек int ones = 0; for (int i = 0; i < r; i++) { if ((u & (1 << i)) != 0) { ones++; } } if (ones != n - 1) { continue; } // проверили. расставляем массив ones = 0; int p = 0; for (int i = 0; i < r; i++) { if ((u & (1 << i)) == 0) { ones++; } else { prb[p] = ones * 10; p++; ones = 0; } } prb[p] = ones * 10; p++; ones = 0; double sum = 0; for (int i = 0; i < n; i++) { if (prb[i] > 100 - s[i][1]) prb[i] = 100 - s[i][1]; s[i][1] = prb[i] + s[i][1]; } for (int i = (1 << n) - 1; i >= 0; i--) { double prob = 1; int lvl = 0; int kill = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) { prob *= s[j][1] / 100.0; kill--; } else { lvl += s[j][0]; prob *= (1 - s[j][1] / 100.0); kill++; } } if (kill >= 0) { sum += prob * ((double) A / (A + lvl)); } else { sum += prob; } } for (int i = 0; i < n; i++) { s[i][1] = -prb[i] + s[i][1]; } max = Math.max(max, sum); } out.println(max); out.flush(); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { static int bit[]; static int array[]; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); bit = new int[1505]; array = new int[n + 1]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 1;i <= n;i++) array[i] = Integer.parseInt(st.nextToken()); long ans = 0; for(int i = n;i >= 1;i--){ ans += read(array[i]); update(array[i]); } long val = (ans & 1) + 1000_000; int m = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); for(int i = 1;i <= m;i++){ st = new StringTokenizer(br.readLine()); int l = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); long temp = (r - l + 1); temp = temp*(temp - 1) / 2; if((temp & 1) == 1)--val; if((val & 1) == 1)sb.append("odd"); else sb.append("even"); sb.append('\n'); } System.out.print(sb); } static int update(int idx){ int sum = 0; while(idx < 1501){ bit[idx] += 1; idx += idx & (-idx); } return sum; } static int read(int idx){ int sum = 0; while(idx > 0){ sum += bit[idx]; idx -= idx & (-idx); } return sum; } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.*; import java.util.*; public class A { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; class Team implements Comparable<Team>{ int ac; int penalty; public Team(int ac, int penalty) { this.ac = ac; this.penalty = penalty; } @Override public int compareTo(Team o) { if (ac != o.ac) return ac > o.ac ? -1 : 1; return (penalty == o.penalty) ? 0 : (penalty < o.penalty ? -1 : 1); } } void solve() throws IOException { int n = nextInt(); int k = nextInt() - 1; Team[] a = new Team[n]; for (int i = 0; i < n; i++) a[i] = new Team(nextInt(), nextInt()); Arrays.sort(a); for (int i = 0; i < n;) { int j = i; while (j < n && a[j].compareTo(a[i]) == 0) j++; if (i <= k && k < j) { out.println(j - i); return; } i = j; } } 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 null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } 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
166_A. Rank List
CODEFORCES
//package codeforces; import java.util.*; public class Main { class team implements Comparable<team>{ int pro,time; public int compareTo(team oth) { if(pro>oth.pro) return -1; if(pro==oth.pro&&time<oth.time) return -1; // TODO Auto-generated method stub return 1; } } Scanner scan=new Scanner(System.in); void run(){ int n=scan.nextInt(); int k=scan.nextInt()-1; team tm[]=new team[n]; for(int i=0;i<n;i++){ tm[i]=new team(); tm[i].pro=scan.nextInt(); tm[i].time=scan.nextInt(); } Arrays.sort(tm); int sum=0; for(int i=k;i>=0;i--) if(tm[i].pro==tm[k].pro&&tm[i].time==tm[k].time) sum++; for(int i=k;i<n;i++) if(tm[i].pro==tm[k].pro&&tm[i].time==tm[k].time) sum++; System.out.println(sum-1); } public static void main(String args[]) { new Main().run(); } }
nlogn
166_A. Rank List
CODEFORCES
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import static java.lang.Math.max; import static java.lang.Math.min; public class C implements Runnable{ // SOLUTION!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! private final static Random rnd = new Random(); private final static String fileName = ""; private void solve() { int n = readInt(); int m = readInt(); int k = readInt(); Point[] starts = readPointArray(k); for (Point start : starts) { start.x--; start.y--; } Point furthest = bfs(n, m, starts); out.println((furthest.x + 1) + " " + (furthest.y + 1)); } private Point bfs(int n, int m, Point[] starts) { final int INF = n * m + 1; boolean[][] used = new boolean[n][m]; Queue<Integer> queue = new ArrayDeque<>(); for (Point start : starts) { used[start.x][start.y] = true; queue.add(start.x * m + start.y); } int last = -1; while (queue.size() > 0) { int from = queue.poll(); last = from; int fromX = from / m, fromY = from % m; for (int[] step : steps) { int toX = fromX + step[0]; int toY = fromY + step[1]; if (!checkCell(toX, n, toY, m)) continue; if (used[toX][toY]) continue; used[toX][toY] = true; queue.add(toX * m + toY); } } return new Point(last / m, last % m); } ///////////////////////////////////////////////////////////////////// private final static boolean FIRST_INPUT_STRING = false; private final static boolean MULTIPLE_TESTS = true; private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final static int MAX_STACK_SIZE = 128; private final static boolean OPTIMIZE_READ_NUMBERS = false; ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeInit(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { do { try { timeInit(); solve(); time(); out.println(); } catch (NumberFormatException e) { break; } catch (NullPointerException e) { if (FIRST_INPUT_STRING) break; else throw e; } } while (MULTIPLE_TESTS); } out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// private BufferedReader in; private OutputWriter out; private StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new C(), "", MAX_STACK_SIZE * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// private void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } //////////////////////////////////////////////////////////////// private long timeBegin; private void timeInit() { this.timeBegin = System.currentTimeMillis(); } private void time(){ long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } private void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// private String delim = " "; private String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } private String readString() { try { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine()); } return tok.nextToken(delim); } catch (NullPointerException e) { return null; } } ///////////////////////////////////////////////////////////////// private final char NOT_A_SYMBOL = '\0'; private char readChar() { try { int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } catch (IOException e) { throw new RuntimeIOException(e); } } private char[] readCharArray() { return readLine().toCharArray(); } private char[][] readCharField(int rowsCount) { char[][] field = new char[rowsCount][]; for (int row = 0; row < rowsCount; ++row) { field[row] = readCharArray(); } return field; } ///////////////////////////////////////////////////////////////// private long optimizedReadLong() { int sign = 1; long result = 0; boolean started = false; while (true) { try { int j = in.read(); if (-1 == j) { if (started) return sign * result; throw new NumberFormatException(); } if (j == '-') { if (started) throw new NumberFormatException(); sign = -sign; } if ('0' <= j && j <= '9') { result = result * 10 + j - '0'; started = true; } else if (started) { return sign * result; } } catch (IOException e) { throw new RuntimeIOException(e); } } } private int readInt() { if (!OPTIMIZE_READ_NUMBERS) { return Integer.parseInt(readString()); } else { return (int) optimizedReadLong(); } } private int[] readIntArray(int size) { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } private int[] readSortedIntArray(int size) { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } private int[] readIntArrayWithDecrease(int size) { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// private int[][] readIntMatrix(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// private long readLong() { if (!OPTIMIZE_READ_NUMBERS) { return Long.parseLong(readString()); } else { return optimizedReadLong(); } } private long[] readLongArray(int size) { long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// private double readDouble() { return Double.parseDouble(readString()); } private double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// private BigInteger readBigInteger() { return new BigInteger(readString()); } private BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// private Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } private Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// @Deprecated private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) { @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } private static class GraphBuilder { final int size; final List<Integer>[] edges; static GraphBuilder createInstance(int size) { List<Integer>[] edges = new List[size]; for (int v = 0; v < size; ++v) { edges[v] = new ArrayList<>(); } return new GraphBuilder(edges); } private GraphBuilder(List<Integer>[] edges) { this.size = edges.length; this.edges = edges; } public void addEdge(int from, int to) { addDirectedEdge(from, to); addDirectedEdge(to, from); } public void addDirectedEdge(int from, int to) { edges[from].add(to); } public int[][] build() { int[][] graph = new int[size][]; for (int v = 0; v < size; ++v) { List<Integer> vEdges = edges[v]; graph[v] = castInt(vEdges); } return graph; } } ///////////////////////////////////////////////////////////////////// private static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<C.IntIndexPair>() { @Override public int compare(C.IntIndexPair indexPair1, C.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<C.IntIndexPair>() { @Override public int compare(C.IntIndexPair indexPair1, C.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static IntIndexPair[] from(int[] array) { IntIndexPair[] iip = new IntIndexPair[array.length]; for (int i = 0; i < array.length; ++i) { iip[i] = new IntIndexPair(array[i], i); } return iip; } int value, index; IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } int getRealIndex() { return index + 1; } } private IntIndexPair[] readIntIndexArray(int size) { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// private static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; private int precision; private String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } OutputWriter(OutputStream out) { super(out); } OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } int getPrecision() { return precision; } void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } void printWithSpace(double d){ printf(formatWithSpace, d); } void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// private static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants and functions //////////////// ///////////////////////////////////////////////////////////////////// private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; private static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) { return checkIndex(row, rowsCount) && checkIndex(column, columnsCount); } private static boolean checkIndex(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// private static boolean checkBit(int mask, int bit){ return (mask & (1 << bit)) != 0; } private static boolean checkBit(long mask, int bit){ return (mask & (1L << bit)) != 0; } ///////////////////////////////////////////////////////////////////// private static long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } private static Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// private static int[] getPrimes(int n) { boolean[] used = new boolean[n]; used[0] = used[1] = true; int size = 0; for (int i = 2; i < n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j < n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i < n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } ///////////////////////////////////////////////////////////////////// private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } ///////////////////////////////////////////////////////////////////// private static class MultiSet<ValueType> { public static <ValueType> MultiSet<ValueType> createMultiSet() { Map<ValueType, Integer> multiset = new HashMap<>(); return new MultiSet<>(multiset); } private final Map<ValueType, Integer> multiset; private int size; public MultiSet(Map<ValueType, Integer> multiset) { this.multiset = multiset; this.size = 0; } public int size() { return size; } public void inc(ValueType value) { int count = get(value); multiset.put(value, count + 1); ++size; } public void dec(ValueType value) { int count = get(value); if (count == 0) return; if (count == 1) multiset.remove(value); else multiset.put(value, count - 1); --size; } public int get(ValueType value) { Integer count = multiset.get(value); return (count == null ? 0 : count); } } ///////////////////////////////////////////////////////////////////// private static class IdMap<KeyType> extends HashMap<KeyType, Integer> { /** * */ private static final long serialVersionUID = -3793737771950984481L; public IdMap() { super(); } int getId(KeyType key) { Integer id = super.get(key); if (id == null) { super.put(key, id = size()); } return id; } } ///////////////////////////////////////////////////////////////////// private static int[] castInt(List<Integer> list) { int[] array = new int[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } private static long[] castLong(List<Long> list) { long[] array = new long[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class D5 { static int a, v, l, d; static double w; static double afterMark( int s, double w) { if (2 * s * a > v * v - w * w) { // ���� ��������� v. ����� �� return (v - w) * 1.0 / a + (s - (v * v - w * w) * 1.0 / (2 * a)) / v; } else { // ��������� double megav = Math.sqrt((2 * a * s + w * w) * 1.0); return (megav - w) / a; } } public static void main(String args[]) throws IOException { boolean online = System.getProperty("ONLINE_JUDGE") != null; Scanner in = online ? new Scanner(System.in) : new Scanner(new FileReader("input.txt")); PrintWriter out = online ? new PrintWriter(System.out) : new PrintWriter(new FileWriter("output.txt")); a = in.nextInt(); v = in.nextInt(); l = in.nextInt(); d = in.nextInt(); w = (double) in.nextInt(); double t,t1,t2; if (v > w) { // ����� ��������� ������, ����� ����� ��� // ������� ������ �� ����� if (2 * d * a > 2 * v * v - w * w) { // ���� ��������� v. ����� �� t1 = (2 * v - w) * 1.0 / a + (d - (2 * v * v - w * w) * 1.0 / (2 * a)) / v; } else if (2 * d * a > w * w) { // ���� �� ���������, �� ���� � ���� - ��������� double topv = Math.sqrt(d * a + w * w * 1.0 / 2); t1 = (2 * topv - w) * 1.0 / a; } else { // ���� ����������� �� ������ ����� - �����, ��������� t1 = Math.sqrt(2 * d * 1.0 / a); w = Math.sqrt(2 * a * d * 1.0); } // ������� ������ ����� ����� t2 = afterMark(l - d, w); t = t1 + t2; } else { t = afterMark(l, 0.0); } out.println(t); out.flush(); return; } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; public class Main implements Runnable { class Home implements Comparable<Home> { @Override public int compareTo(Home arg0) { return st - arg0.st; } int st, end; } public void solve() throws IOException { int n = nextInt(), t = nextInt() * 2; Home[] h = new Home[n]; for(int i = 0; i < n; ++i) { int x = nextInt() * 2, a = nextInt() * 2; h[i] = new Home(); h[i].st = x - a / 2; h[i].end = x + a / 2; } Arrays.sort(h); int ans = 2; for(int i = 0; i + 1 < n; ++i) { int delta = h[i + 1].st - h[i].end; if (delta == t) ans++; if (delta > t) ans += 2; } pw.println(ans); } static final String filename = "A"; static final boolean fromConsole = true; public void run() { try { if (!fromConsole) { in = new BufferedReader(new FileReader(filename + ".in")); pw = new PrintWriter(filename + ".out"); } else { in = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); } st = new StringTokenizer(""); long st = System.currentTimeMillis(); solve(); //pw.printf("\nWorking time: %d ms\n", System.currentTimeMillis() - st); pw.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } private StringTokenizer st; private BufferedReader in; private PrintWriter pw; boolean hasNext() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return false; } st = new StringTokenizer(line); } return st.hasMoreTokens(); } String next() throws IOException { return hasNext() ? st.nextToken() : null; } int nextInt() throws IOException { return Integer.parseInt(next()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) { new Thread(new Main()).start(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; import java.lang.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.*; public class Main { public static void main(String[] args) throws Exception{ FastReader sc=new FastReader(); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); Main mm=new Main(); long n=sc.nextLong(); long k=sc.nextLong(); long l=0; long r=1000000000; long ans=-1; while(l<=r) { long mid=(l+r)/2; if(n-mid<=0) { r=mid-1; } else { long temp=(n-mid)*(n-mid+1)-(2*mid); if(temp==2*k) { ans=mid; break; } else if(temp<2*k) { r=mid-1; } else if(temp>2*k) { l=mid+1; } } } System.out.println(ans); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.IOException; import java.util.StringTokenizer; /* * @author Tnascimento */ public class MaeDosDragoes { public static PrintWriter saida = new PrintWriter(System.out, false); public static class Escanear { BufferedReader reader; StringTokenizer tokenizer; public Escanear() { this(new InputStreamReader(System.in)); } public Escanear(Reader in) { reader = new BufferedReader(in); } String proximo() { if (tokenizer == null || !tokenizer.hasMoreElements()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } int proximoNum() { return Integer.parseInt(proximo()); } } public static void main(String[] args) { Escanear escanear = new Escanear(); int proximoInt = escanear.proximoNum(); double proximoDouble = escanear.proximoNum(); long[] aux = new long[proximoInt]; for(Integer i = 0; i < proximoInt; i++) { for(Integer j =0; j < proximoInt; j++) { Integer val = escanear.proximoNum(); if (val.equals(1) || i.equals(j)) { aux[i] |= 1L << j; } } } int esquerda = proximoInt/2; int direita = proximoInt - esquerda; int[] depois = new int[1 << esquerda]; int maiorMascara = 1 << esquerda; for(int mascara = 1; mascara <maiorMascara; mascara++) { int mascaraAtual = mascara; for(int j = 0; j < esquerda; j++) { if (((1 << j) & mascara) > 0) { mascaraAtual &= aux[j + direita] >> direita; depois[mascara] = Math.max(depois[mascara], depois[mascara ^ (1 << j)]); } } if (mascara == mascaraAtual) { depois[mascara] = Math.max(depois[mascara],Integer.bitCount(mascara)); } } int auxiliar = 0; int mascaraMaxima = 1 << direita; for(int mascara = 0; mascara < mascaraMaxima; mascara++) { int mascaraCorrente = mascara; int mascaraValor = maiorMascara -1; for(int j = 0; j < direita; j++) { if (((1 << j) & mascara) > 0) { mascaraCorrente &= (aux[j] & (mascaraMaxima-1)); mascaraValor &= aux[j] >> direita; } } if (mascaraCorrente != mascara) continue; auxiliar = Math.max(auxiliar, Integer.bitCount(mascara) + depois[mascaraValor]); } proximoDouble/=auxiliar; saida.println(proximoDouble * proximoDouble * (auxiliar * (auxiliar-1))/2); saida.flush(); } }
np
839_E. Mother of Dragons
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class Div1_429C { static final long MOD = 1_000_000_007; static long[] fact = new long[305]; static long[] iFact = new long[305]; static final long I304 = 904487323; public static void main(String[] args) throws IOException { fact[0] = 1; for (int i = 1; i < 305; i++) { fact[i] = fact[i - 1] * i % MOD; } iFact[304] = I304; for (int i = 303; i >= 0; i--) { iFact[i] = iFact[i + 1] * (i + 1) % MOD; } BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int len = Integer.parseInt(reader.readLine()); long[] groups = new long[len + 1]; int[] gSizes = new int[len + 1]; int nG = 0; StringTokenizer inputData = new StringTokenizer(reader.readLine()); iLoop: for (int i = 0; i < len; i++) { long nxt = Integer.parseInt(inputData.nextToken()); for (int j = 1; j <= nG; j++) { if (isSquare(nxt * groups[j])) { gSizes[j]++; continue iLoop; } } groups[++nG] = nxt; gSizes[nG] = 1; } long[][] dp = new long[nG + 1][len]; dp[0][0] = 1; int fTotal = 0; for (int fG = 0; fG < nG; fG++) { for (int fB = 0; fB < len; fB++) { if (dp[fG][fB] == 0) { continue; } int nGSize = gSizes[fG + 1]; for (int nS = 1; nS <= Math.min(nGSize, fTotal + 1); nS++) { for (int nBR = 0; nBR <= Math.min(fB, nS); nBR++) { long nW = dp[fG][fB] * fact[nGSize] % MOD * comb(nGSize - 1, nS - 1) % MOD * comb(fB, nBR) % MOD * comb(fTotal + 1 - fB, nS - nBR) % MOD; dp[fG + 1][fB - nBR + nGSize - nS] = (dp[fG + 1][fB - nBR + nGSize - nS] + nW) % MOD; } } } fTotal += gSizes[fG + 1]; } printer.println(dp[nG][0]); printer.close(); } static long comb(int a, int b) { if(b > a) { return 0; } return fact[a] * iFact[a - b] % MOD * iFact[b] % MOD; } static boolean isSquare(long inp) { long sqrt = (long) Math.sqrt(inp); return inp == sqrt * sqrt; } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class B { private static StreamTokenizer in; private static PrintWriter out; private static int nextInt() throws Exception{ in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception{ in.nextToken(); return in.sval; } static{ in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); } public static void main(String[] args)throws Exception{ int n = nextInt(); char[] c = nextString().toCharArray(); int tc = 0, hc = 0; for(int i = 0;i<c.length; i++){ if(c[i] == 'T')tc++; else hc++; } // char g = 'T'; // if(tc > hc){ // tc = hc; // g = 'H'; // } int max = -1; int pos = 0; for(int i = 0; i<c.length; i++){ int a = 0; for(int j = 0; j<tc;j++){ int k = i+j; if(k>=n)k-=n; if(c[k] == 'T'){ a++; } } if(a>max){ max = a; pos = i; } } int min1 = tc - max; max = -1; pos = 0; for(int i = 0; i<c.length; i++){ int a = 0; for(int j = 0; j<hc;j++){ int k = i+j; if(k>=n)k-=n; if(c[k] == 'H'){ a++; } } if(a>max){ max = a; pos = i; } } int min2 = hc - max; out.println(Math.min(min1, min2)); out.flush(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.util.Scanner; public class A { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int f1 = 0; int f2 = 1; int f3 = 1; while (f3 < n) { f1 = f2; f2 = f3; f3 = f1 + f2; } if (n == 0) { System.out.println(0 + " " + 0 + " " + 0); } else if (f3 == n) { System.out.println(f1 + " " + f1 + " " + (f2 - f1)); } else { System.out.println("I'm too stupid to solve this problem"); } } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
//package c; import java.util.*; import java.io.*; public class Main { int n,m; int d[][]; Queue<int[]> q = new LinkedList<int[]>(); int cur[]; public void run() throws Exception{ Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new File("output.txt")); n = in.nextInt(); m = in.nextInt(); int k = in.nextInt(); d = new int[n][m]; for(int i=0;i<n;i++) Arrays.fill(d[i], Integer.MAX_VALUE/2); for(int i=0;i<k;i++){ int x = in.nextInt()-1; int y = in.nextInt()-1; d[x][y] = 0; q.add(new int[]{x,y}); } while(q.size() > 0){ cur = q.poll(); int x = cur[0]; int y = cur[1]; add(x, y+1); add(x+1, y); add(x-1, y); add(x, y-1); } int max = 0; int x = 0; int y = 0; for(int i=0;i<n;i++) for(int j=0;j<m;j++) if (max < d[i][j]){ max = d[i][j]; x = i; y = j; } out.println((x+1) + " " + (y+1)); out.close(); } private void add(int x, int y){ if (x < 0 || y < 0) return; if (x >=n || y >=m) return; if (d[x][y] > d[cur[0]][cur[1]] + 1){ d[x][y] = d[cur[0]][cur[1]] + 1; q.add(new int[]{x,y}); } } public static void main(String[] args) throws Exception{ new Main().run(); } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Practice { public static long mod = (long) Math.pow(10, 9) + 7; public static long[][] dp; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String[] s2 = br.readLine().split(" "); int n = (int) Long.parseLong(s2[0]); long m = Long.parseLong(s2[1]); dp = new long[n + 2][n + 2]; long[] power = new long[n + 1]; mod = m; long[][] choose = new long[n + 2][n + 2]; getPow(power, n + 1); getChoose(choose, n + 2, n + 2); dp[0][0] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { for (int k = 1; k + i <= n; k++) { // System.out.println((j + k) + " " + k + " - " + choose[j + k][k]); dp[i + k + 1][j + k] = (dp[i + k + 1][j + k] + (((dp[i][j] * power[k - 1]) % mod) * choose[j + k][k]) % mod) % mod; } } } long ans = 0; for (int i = 0; i <= n; i++) { ans = (ans + dp[n + 1][i]) % mod; } pw.println(ans); pw.close(); } private static void getChoose(long[][] choose, int up, int dow) { // TODO Auto-generated method stub for (int i = 1; i < up; i++) { for (int j = 1; j <= i; j++) { if (j == 1 && i == 1) { choose[i][j] = 1; } else if (j == 1) { choose[i][j] = i; } else { choose[i][j] = (choose[i - 1][j] + choose[i - 1][j - 1]) % mod; } } } } private static void getPow(long[] power, int l) { // TODO Auto-generated method stub for (int i = 0; i < l; i++) { if (i == 0) { power[i] = 1; } else { power[i] = (power[i-1] * 2) % mod; } } } } //private static long getGCD(long l, long m) { //// TODO Auto-generated method stub // //long t1 = Math.min(l, m); //long t2 = Math.max(l, m); //while (true) { // long temp = t2 % t1; // if (temp == 0) { // return t1; // } // t2 = t1; // t1 = temp; //} //}
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { boolean hasBit(long n, int pos) { return (n & (1L << pos)) != 0; } public void solve() throws Exception { long l = sc.nextLong(), r = sc.nextLong(); int bit = 62; while (bit >= 0 && (hasBit(l, bit) == hasBit(r, bit))) { bit--; } out.println((1L << (bit + 1)) - 1); } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable uncaught) { Solution.uncaught = uncaught; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread thread = new Thread (null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); if (Solution.uncaught != null) { throw Solution.uncaught; } } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.util.Scanner; import java.util.TreeMap; public class B { static Scanner in; static void put(TreeMap<Integer, Integer> m, int key) { if (m.containsKey(key)) { m.put(key, m.get(key) + 1); } else { m.put(key, 1); } } static void remove(TreeMap<Integer, Integer> m, int key) { if (!m.containsKey(key)) return; m.put(key, m.get(key) - 1); if (m.get(key) == 0) { m.remove(key); } } public static void main(String[] args) { in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int i = 0; while (i + 1 < n && a[i + 1] == a[0]) { i++; } int left = i; TreeMap<Integer, Integer> used = new TreeMap<Integer, Integer>(); for (; i < n; i++) { put(used, a[i]); if (used.size() == k) { while (used.get(a[left]) > 1) { remove(used, a[left]); left++; } System.out.println(left + 1 + " " + (i + 1)); return; } } System.out.println("-1 -1"); } }
linear
224_B. Array
CODEFORCES
import java.io.*; import java.util.*; public class A { long mod = (long)(1e+9+9); long pow(long a,long b) { long mul = a; long res = 1; while (b > 0) { if (b %2 == 1) { res = (res*mul)%mod; } mul = (mul*mul)%mod; b/=2; } return res; } void solve() throws IOException { long n = nextLong(); long m = nextLong(); long k = nextLong(); long l = -1; long r = m / k; while (l < r - 1) { long mid = (l+r)/2; long leftOk = m - mid*k; long leftPos = n - mid*k; long cgroups = (leftOk + (k-2)) / (k-1); long positions = leftOk+cgroups-1; if (positions <= leftPos) { r = mid; } else { l = mid; } } long res = pow(2,r+1); res = (res - 2 + mod) %mod; res = (res*k) % mod; res = (res+m-r*k) %mod; out.println(res); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new A().run(); } BufferedReader in; PrintWriter out; StringTokenizer st; String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String temp = in.readLine(); if (temp == null) { return null; } st = new StringTokenizer(temp); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } }
logn
338_A. Quiz
CODEFORCES
import java.util.Scanner; public class LCM { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n = scan.nextLong(); if (n <= 2) System.out.println(n); else if (n % 2 == 1) System.out.println(n * (n - 1) * (n - 2)); else if (n % 3 == 0) System.out.println((n - 1) * (n - 2) * (n - 3)); else System.out.println(n * (n - 1) * (n - 3)); } }
constant
235_A. LCM Challenge
CODEFORCES
import java.util.Map; import java.io.InputStreamReader; import java.io.IOException; import java.util.TreeMap; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Hamed Valizadeh (havaliza@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInputReader in = new FastInputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { int n, a, b; Map<Integer, Integer> position; int[] p; int[] group; public void solve(int testNumber, FastInputReader in, PrintWriter out) { n = in.nextInt(); a = in.nextInt(); b = in.nextInt(); position = new TreeMap<Integer, Integer>(); p = new int[n]; group = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt(); group[i] = -1; position.put(p[i], i); } for (int i = 0; i < n; i++) { if (getMate(i) != -1) continue; out.println("NO"); return; } for (int i = 0; i < n; i++) { boolean aMate = position.containsKey(a - p[i]); boolean bMate = position.containsKey(b - p[i]); if (aMate && bMate) continue; if (group[i] != -1) continue; if (!solve(i)) { out.println("NO"); return; } } for (int i = 0; i < n; i++) { if (group[i] != -1) continue; if (!solve(i)) { out.println("NO"); return; } } out.println("YES"); for (int i = 0; i < n; i++) { out.print(group[i]); out.print(" "); } out.println(); } private boolean solve(int index) { int mate = getMate(index); if (mate == -1) return false; assign(index, mate); if (getMate(index) != -1) return solve(getMate(index)); else return getMate(mate) == -1 || solve(getMate(mate)); } private void assign(int index, int mate) { int sum = p[index] + p[mate]; if (sum == a) { group[index] = group[mate] = 0; return; } if (sum == b) { group[index] = group[mate] = 1; return; } throw new RuntimeException("Wrong assignment :("); } private int getMate(int index) { int[] possibleMates = new int[] {a - p[index], b - p[index]}; for (int mate: possibleMates) { if (position.containsKey(mate)) { int mateIndex = position.get(mate); if (group[mateIndex] == -1) return mateIndex; } } return -1; } } class FastInputReader { public BufferedReader reader; public StringTokenizer tokenizer; public FastInputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
linear
468_B. Two Sets
CODEFORCES
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class CottageVillage { class cl { int x=0; int a=0; cl(int x, int a){ this.x=x; this.a=a; } } class cmp implements Comparator<cl> { public int compare(cl d1, cl d2) { return d1.x<d2.x ? -1 : 1; } } public CottageVillage() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); cl[] w = new cl[n]; for(int i=0; i<n; i++) w[i] = new cl(sc.nextInt(), sc.nextInt()); Arrays.sort(w, new cmp()); int cnt=2, diff=0; for(int i=1; i<n; i++) { diff = Math.abs(2*w[i].x-2*w[i-1].x-w[i].a-w[i-1].a)-2*k; if (diff>0) cnt+=2; else if (diff==0) cnt++; } System.out.println(cnt); } public static void main(String... args) { new CottageVillage(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; public class A135 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } Arrays.sort(arr); int[] ans = new int[n]; if (arr[n-1] == 1) { for (int i = 0 ;i < n; i++) { ans[i] = arr[i]; } ans[n-1] = 2; } else { ans[0] = 1; for (int i = 1; i < n; i++) { ans[i] = arr[i-1]; } } StringBuffer buf = new StringBuffer(); for (int i = 0; i < n; i++) { buf.append(ans[i]); if (i != n-1) buf.append(' '); } System.out.print(buf.toString()); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; public class c { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); int n = in.nextInt(), m = in.nextInt(); long bounty = in.nextInt(), increase = in.nextInt(); int damage = in.nextInt(); int[] mh = new int[n]; int[] sh = new int[n]; int[] reg = new int[n]; long countKilled = 0; ArrayList<Event> es = new ArrayList<>(); Event[] regen = new Event[n]; for(int i=0;i<n;i++) { mh[i] = in.nextInt(); sh[i] = in.nextInt(); reg[i] = in.nextInt(); if(sh[i] <= damage) countKilled++; if(reg[i] > 0) { int time = (damage+1 - sh[i]+reg[i]-1)/reg[i]; if(time > 0 && mh[i] >= damage+1) { Event e2 = new Event(time, i, damage+1); regen[i] = e2; es.add(e2); } } } for(int i=0;i<m;i++) { Event e = new Event(in.nextInt(), in.nextInt()-1, in.nextInt()); es.add(e); if(reg[e.e] > 0) { int time = (damage+1 - e.h+reg[e.e]-1)/reg[e.e]; if(time > 0 && mh[e.e] >= damage+1) { Event e2 = new Event(e.t + time, e.e, damage+1); e.regen = e2; es.add(e2); } } } Collections.sort(es, (a,b) -> a.t-b.t); long ans = countKilled*bounty; int lastTime = 0; for(Event e : es) { if(e.t == -1) continue; if(regen[e.e] != e && regen[e.e] != null) { regen[e.e].t = -1; regen[e.e] = null; } if(lastTime != e.t) { ans = Math.max(ans, countKilled*(bounty+(e.t-1)*increase)); } if(sh[e.e] <= damage) countKilled--; sh[e.e] = e.h; if(sh[e.e] <= damage) countKilled++; if(e.regen != null) { regen[e.e] = e.regen; } lastTime = e.t; } if(countKilled != 0) { if(increase > 0) ans = -1; else ans = Math.max(ans, countKilled*bounty); } System.out.println(ans); } static class Event { int t; int e; int h; Event regen; public Event(int tt, int ee, int hh) { t = tt; e = ee; h = hh; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws IOException { if(st.hasMoreTokens()) return st.nextToken(); else st = new StringTokenizer(br.readLine()); return next(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
nlogn
912_C. Perun, Ult!
CODEFORCES
import java.util.Arrays; import java.util.Scanner; /** * * @author Natasha */ public class Main{ public static void main(String[] args) { Scanner in = new Scanner(System.in); int produzeni = in.nextInt(); int devices = in.nextInt(); int stekovi = in.nextInt(); int [] filter = new int[produzeni]; for(int i = 0; i<produzeni; i++){ filter[i] = in.nextInt(); } Arrays.sort(filter); int filt_no = filter.length-1; if(devices<=stekovi) { System.out.println("0"); return; } int used = 0; while(devices>stekovi){ try{ stekovi+=filter[filt_no--]-1; } catch(Exception e){ System.out.println("-1"); return; } } System.out.println(filter.length - filt_no-1); } }
nlogn
257_A. Sockets
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * Created by huhansan on 2017/12/19. * http://codeforces.com/problemset/problem/11/D * 参考 Petr http://codeforces.com/contest/11/submission/47646 * 求所有不同的环的个数 * 首先按长度分 C = C1+C2+...+Cn * 长度为i的环的数量的求解, 规定一个顺序,以最小值开头,按开头不同分治,再按不同结尾分治 * 遍历所有排列,如果长度为i的排列成环,则对应的Ci值+1 * 遍历方式的选择: * 1.integer实现bitmask,从1加到1<<n * 2.递归 */ public class CF_11D { long[][] ways; //ways[mask][endPointIndex] boolean[][] connect; int n, m, lowestIndex, mask; //n 节点数, m边数 00000...0 <--> n:n-1:n-2.....1 bitmask private static int HEAD_POINT_INDEX = 0; public void solve() throws Exception { int a, b; long total = 0; n = nextInt(); m = nextInt(); connect = new boolean[n][n]; ways = new long[1 << n][n]; for (int i = 0; i < m; i++) { a = nextInt(); b = nextInt(); connect[a - 1][b - 1] = true; connect[b - 1][a - 1] = true; } for (int i = 0; i < n; i++) { ways[1 << i][i] = 1; //初始化,单定点也视为环 } for (mask = 1; mask < 1 << n; mask++) { int tmp = mask, cnt = 0; while (tmp > 0) { tmp = tmp & (tmp - 1); cnt++; } lowestIndex = -1; for (int endPointIndex = 0; endPointIndex < n; endPointIndex++) { if ((mask & 1 << endPointIndex) != 0) { if (lowestIndex < 0) { lowestIndex = endPointIndex; } else if (lowestIndex != endPointIndex) { for (int i = lowestIndex; i < n; i++) if (connect[i][endPointIndex]) { ways[mask][endPointIndex] += ways[mask & ~(1 << endPointIndex)][i]; // P[(1,2,3)4]的数量 == 其它+P[1,2,3]的数量, 也就是1,2,3三个点可以组成的以1开头的排列数 } if (connect[endPointIndex][lowestIndex] && cnt > 2) { //以首尾定点分治,存在对称性,如 1-2-3-4-1 == 1-4-3-2-1 total += ways[mask][endPointIndex]; } } } } } writer.println(total / 2); } public static void main(String[] args) { new CF_11D().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Solution implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); @Override public void run() { try { init(); } catch (FileNotFoundException e) { e.printStackTrace(); } long time = System.currentTimeMillis(); try { solve(); } catch (Exception e) { e.printStackTrace(); } out.close(); //System.err.println(System.currentTimeMillis() - time); } private void init() throws FileNotFoundException { String file = "123"; if (!file.equals("")) { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } public static void main(String[] args) { new Thread(new Solution()).start(); } private String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tok.nextToken(); } private int readInt() { return Integer.parseInt(readString()); } int[] counts = new int[1000]; private long readLong() { return Long.parseLong(readString()); } private void solve() { int n = readInt()+2; int m = readInt()+2; boolean[][] graph = new boolean[n][m]; for (int i = 0; i < n; i++) { graph[i][m-1] = true; graph[i][0] = true; } for (int i = 0; i < m; i++) { graph[n-1][i] = true; graph[0][i] = true; } int k = readInt(); int inFire = 0; Queue<Point> q = new ArrayDeque<>(); for (int i = 0; i < k; i++) { int x = readInt(); int y = readInt(); Point p = new Point(x, y); graph[x][y] = true; q.add(p); } while (!q.isEmpty()) { Point current = q.poll(); inFire++; if(!graph[current.x+1][current.y]) { graph[current.x+1][current.y] = true; q.add(new Point(current.x+1, current.y)); } if(!graph[current.x-1][current.y]) { graph[current.x-1][current.y] = true; q.add(new Point(current.x-1, current.y)); } if(!graph[current.x][current.y+1]) { graph[current.x][current.y+1] = true; q.add(new Point(current.x, current.y+1)); } if(!graph[current.x][current.y-1]) { graph[current.x][current.y-1] = true; q.add(new Point(current.x, current.y-1)); } if(q.isEmpty()) { out.print(current.x+" "+current.y); return; } } } class Point{ int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } }
cubic
35_C. Fire Again
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); Set<Integer> div = new HashSet<>(); boolean[] d = new boolean[n]; for (int i = 0; i < n; i++) { for (int j = 0 ; j < n; j++) { if (d[j]) { continue; } if (a[j]%a[i] == 0) { d[j] = true; div.add(a[i]); } } } System.out.println(div.size()); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Locale; import java.util.Scanner; public class A { static { final Locale us = Locale.US; if (!Locale.getDefault().equals(us)) { Locale.setDefault(us); } } static boolean file = false; static Scanner in; static { try { in = new Scanner(file ? new FileInputStream("f:\\var\\tmp\\in.txt") : System.in); } catch (final FileNotFoundException e) { e.printStackTrace(); } } static PrintWriter out; static { try { out = file ? new PrintWriter( new FileWriter("f:\\var\\tmp\\out.txt")) : new PrintWriter( System.out); } catch (final IOException e) { e.printStackTrace(); } } /** * @param args */ public static void main(final String[] args) { try { solve(); if (file) { System.out.flush(); } if (!file) { out.flush(); } } finally { in.close(); out.close(); } } private static void solve() { final String s = in.next(); int ans = 0; for (int l = 0; l < s.length(); ++l) { for (int r = l; r < s.length(); ++r) { for (int p = l + 1; p - l + r < s.length(); ++p) { boolean ok = true; for (int q = l, qq = p; q <= r; ++q, ++qq) { if (s.charAt(q) != s.charAt(qq)) { ok = false; } } if (ok) { ans = Math.max(ans, r - l + 1); } } } } out.println(ans); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) { Scanner s = new Scanner(System.in); s.nextLine(); while(s.hasNext()) { int first = s.nextInt(); int second = s.nextInt(); System.out.println(calculate(first,second)); } } public static int calculate(int first, int second) { int operations = 0; while(first != 0 && second != 0) { int temp; if(first < second) { temp = second/first; operations += temp; second -= (first*temp); } else { temp = first/second; operations += temp; first -= (second*temp); } } return operations; } }
constant
267_A. Subtractions
CODEFORCES
import java.util.*; import java.math.*; public class Solution{ private long [] sums; private void solve(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int [] arr = new int[n]; this.sums = new long[n]; for(int i = 0; i < n; i++){ arr[i] = sc.nextInt(); sums[i] = arr[i] + (i == 0 ? 0 : sums[i - 1]); } long ans = 0; for(int i = 1; i <= n && i <= m; i++){ ans = Math.max(ans, sum(0, i - 1) - k); } long [] dp = new long[n]; for(int i = 0; i < n; i++){ if(i + 1 >= m){ long cur = sum(i - m + 1, i) - k; if(i - m >= 0){ cur += dp[i - m]; } dp[i] = Math.max(dp[i], cur); } for(int j = 0; j <= m && i + j < n; j++){ ans = Math.max(ans, dp[i] + sum(i + 1, i + j) - k * (j > 0 ? 1 : 0)); } } System.out.println(ans); } private long sum(int l, int r){ if(l <= 0){ return sums[r]; }else{ return sums[r] - sums[l - 1]; } } public static void main(String [] args){ new Solution().solve(); } }
quadratic
1197_D. Yet Another Subarray Problem
CODEFORCES
import java.io.*; import java.util.*; public class Main implements Runnable { private BufferedReader in; private PrintWriter out; private StringTokenizer st; private void eat(String line) { st = new StringTokenizer(line); } private String next() throws IOException { while(!st.hasMoreTokens()) { String line = in.readLine(); if(line == null) return null; eat(line); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); eat(""); go(); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(-1); } } public static void main(String[] args) { new Thread(new Main()).start(); } public void go() throws IOException { int n = nextInt(); int[] v = new int[n], count = new int[2]; for(int i = 0; i < n; ++i) { v[i] = nextInt(); ++count[v[i] % 2]; } int residue = count[0] == 1 ? 0 : 1; for(int i = 0; i < n; ++i) if(v[i] % 2 == residue) out.println(i + 1); } }
linear
25_A. IQ test
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; public class TaskC { public static void main(String[] args) { Scanner sc = new Scanner(System.in); BigInteger x = new BigInteger(sc.next()); BigInteger k = new BigInteger(sc.next()); BigInteger mod = new BigInteger(String.valueOf((int) (Math.pow(10, 9) + 7))); BigInteger two = new BigInteger("2"); BigInteger interm = two.modPow(k, mod); BigInteger res = interm.multiply(x).add(interm.multiply(x)).subtract(interm).add(BigInteger.ONE).mod(mod); if(x.equals(BigInteger.ZERO)) { System.out.println("0"); return; } System.out.println(res); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
/** * Mx NINJA 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.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class taskB { StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws NumberFormatException, IOException { taskB solver = new taskB(); solver.open(); long time = System.currentTimeMillis(); solver.solve(); if (!"true".equals(System.getProperty("ONLINE_JUDGE"))) { System.out.println("Spent time: " + (System.currentTimeMillis() - time)); System.out.println("Memory: " + (Runtime.getRuntime().totalMemory() - Runtime .getRuntime().freeMemory())); } solver.close(); } public void open() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } public String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } long n, x, y, c; long sq(long n) { if (n <= 0) return 0; return n * n; } long lrsp(long len, long max) { long cnt = Math.min(len, max); long arpr = (1 + cnt) * cnt / 2; if (len > max) arpr += (len - max) * max; return arpr; } long onn(long len) { long up, down, left, right; long toup = x - 1, todown = n - x, toleft = y - 1, toright = n - y; left = Math.min(toleft, len); right = Math.min(toright, len); down = up = sq(len); up -= sq(len - toup); down -= sq(len - todown); len--; if (toright < len) { up -= lrsp(len - toright, toup); down -= lrsp(len - toright, todown); } if (toleft < len) { up -= lrsp(len - toleft, toup); down -= lrsp(len - toleft, todown); } return 1 + up + down + left + right; } public void solve() throws NumberFormatException, IOException { n = nextInt(); x = nextInt(); y = nextInt(); c = nextInt(); long down = 0, up = 2 * n + 13; while (up - down > 2) { long tmp = (up + down) / 2; if (onn(tmp) >= c) up = tmp; else down = tmp; } if (onn(down) >= c) out.println(down); else if (onn(down + 1) >= c) out.println(down + 1); else if (onn(down + 2) >= c) out.println(down + 2); else out.println(down + 3); } public void close() { out.flush(); out.close(); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { setup(); xuly(); } private static long dp[][] = new long[20][170]; private static void setup() { dp[0][0] = 1; for (int i = 1; i < 20; i ++) for (int j = 0; j < 170; j ++) for (int k = Math.max(j - 9, 0); k <= j; k ++) dp[i][j] += dp[i - 1][k]; } private static int sumD(long x) { int ret = 0; while(x > 0) { ret += x % 10; x /= 10; } return ret; } private static long numSatisfy(long limit, int sumDigit) { long ret = 0; int curSum = sumD(limit); if (curSum == sumDigit) ret ++; for (int i = 0; i < 20; i ++) { int bound = (int) (limit % 10); curSum -= bound; for (int d = 0; d < bound && curSum + d <= sumDigit; d ++) ret += dp[i][sumDigit - curSum - d]; limit /= 10; } return ret; } private static void xuly() { Scanner scanner = new Scanner(System.in); long n = scanner.nextLong(); long s = scanner.nextLong(); long ans = 0; for (int sum = 1; sum < 170; sum ++) if (n >= s + sum) ans += numSatisfy(n, sum) - numSatisfy(s + sum - 1, sum); System.out.print(ans); } }
logn
817_C. Really Big Numbers
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 ankur */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { long mod = (long) 1e9 + 7; public void solve(int testNumber, InputReader in, PrintWriter out) { long x = in.nextLong(); long k = in.nextLong(); if (x == 0) { out.print(0); return; } long n = pow(2, k); long l = (n * ((x % mod)) % mod); l = l % mod; long ans = 2 * l - n + 1; ans = ans % mod; if (ans < 0) ans += mod; out.print(ans); } long pow(long a, long val) { if (val == 0) { return 1; } if (val % 2 == 0) { long ans = pow(a, val / 2); return (ans * ans) % mod; } return ((a % mod) * (pow(a, val - 1))) % mod; } } 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() { //*-*------clare------ //remeber while comparing 2 non primitive data type not to use == //remember Arrays.sort for primitive data has worst time case complexity of 0(n^2) bcoz it uses quick sort //again silly mistakes ,yr kb tk krta rhega ye mistakes //try to write simple codes ,break it into simple things //knowledge>rating /* public class Main implements Runnable{ public static void main(String[] args) { new Thread(null,new Main(),"Main",1<<26).start(); } public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC();//chenge the name of task solver.solve(1, in, out); out.close(); } */ 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
992_C. Nastya and a Wardrobe
CODEFORCES