src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.util.*; public class Main { static int a[][],n; static boolean isClique[]; static int maxClique[]; static void DFS1(int p,int n,int S) { if(p>n) { isClique[S]=true; return ; } DFS1(p+1,n,S); boolean mark=true; for(int i=1;i<p;++i) if((S>>(i-1)&1)==1&&a[p][i]==0) mark=false; if(mark) DFS1(p+1,n,1<<(p-1)|S); } static void DFS2(int p,int n,int m,int S) { if(p>n) { int cnt=0; for(int i=m;i<=n;++i) if((S>>(i-m)&1)==1) ++cnt; maxClique[S]=cnt; return ; } DFS2(p+1,n,m,S); boolean mark=true; for(int i=m;i<p;++i) if((S>>(i-m)&1)==1&&a[p][i]==0) mark=false; if(mark) DFS2(p+1,n,m,1<<(p-m)|S); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); n=Integer.parseInt(sc.next()); a=new int [n+10][n+10]; int cap=Integer.parseInt(sc.next()); for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) a[i][j]=Integer.parseInt(sc.next()); int m=(n+1)>>1; isClique=new boolean [1<<m]; Arrays.fill(isClique,false); DFS1(1,m,0); maxClique=new int [1<<(n-m)]; Arrays.fill(maxClique,0); DFS2(m+1,n,m+1,0); for(int i=1;i<1<<(n-m);++i) for(int j=m+1;j<=n;++j) if((i>>(j-m-1)&1)==1) maxClique[i]=Math.max(maxClique[i],maxClique[i-(1<<(j-m-1))]); int ans=0,tmp[]=new int [m+10]; for(int i=0;i<1<<m;++i) if(isClique[i]) { int mask=0,cnt=0; for(int j=1;j<=m;++j) if((i>>(j-1)&1)==1) tmp[++cnt]=j; for(int j=m+1;j<=n;++j) { boolean mark=true; for(int k=1;k<=cnt;++k) if(a[j][tmp[k]]==0) mark=false; if(mark) mask|=1<<(j-m-1); } ans=Math.max(ans,cnt+maxClique[mask]); } System.out.printf("%.9f\n",cap*cap*(ans-1)/2.0/ans); } }
np
839_E. Mother of Dragons
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.Locale; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Map.Entry; public class Solution implements Runnable { public static void main(String[] args) { (new Thread(new Solution())).start(); } BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String r = in.readLine(); if (r == null) return null; st = new StringTokenizer(r); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int count(int q, int n) { int ans = 0; for (int i = 0; i < n; i++) { if (q % 3 != 1) ans++; q /= 3; } return ans; } int count2(int q, int n) { int ans = 0; for (int i = 0; i < n; i++) { if (q % 3 == 2) ans++; q /= 3; } return ans; } int sz; int[] decode(int q, int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = q % 3; q /= 3; } return res; } boolean[][] precalc(int n, int m) { boolean[][] res = new boolean[sz][sz]; for (int i = 0; i < sz; i++) { int[] ai = decode(i, n); for (int j = 0; j < sz; j++) { int[] aj = decode(j, n); boolean f = true; for (int k = 0; k < n && f; k++) { if (aj[k] == 0) { f = false; if (k > 0 && aj[k - 1] == 1) f = true; if (k < n - 1 && aj[k + 1] == 1) f = true; if (ai[k] == 1) f = true; } if (f && ai[k] == 2) f = (aj[k] == 1); } res[i][j] = f; } } return res; } void solve() throws Exception { int n = nextInt(); int m = nextInt(); if (n > m) { int t = n; n = m; m = t; } sz = 1; for (int i = 0; i < n; i++) sz *= 3; boolean[][] a = precalc(n, m); int[][] d = new int[m + 1][sz]; Arrays.fill(d[0], -1); d[0][0] = 0; for (int i = 1; i <= m; i++) { Arrays.fill(d[i], -1); for (int j = 0; j < sz; j++) { if (d[i - 1][j] != -1) { for (int k = 0; k < sz; k++) { if (a[j][k]) { d[i][k] = Math.max(d[i][k], d[i - 1][j] + count(k, n)); } } } } } int ans = 0; for (int i = 0; i < sz; i++) if (count2(i, n) == 0) ans = Math.max(ans, d[m][i]); out.println(ans); } public void run() { Locale.setDefault(Locale.UK); try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // in = new BufferedReader(new FileReader("knights.in")); // out = new PrintWriter("knights.out"); solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { out.flush(); } } }
np
111_C. Petya and Spiders
CODEFORCES
import java.io.*; import java.util.*; import java.util.Random; import java.util.StringTokenizer; public class Main { long b = 31; String fileName = ""; ////////////////////// SOLUTION SOLUTION SOLUTION ////////////////////////////// int INF = Integer.MAX_VALUE / 10; long MODULO = 1000*1000*100; void solve() throws IOException { int n = readInt(); int d = readInt(); int[] arr = readIntArray(n); Arrays.sort(arr); int ans = 2; for (int i=0; i < n - 1; ++i){ int cur = arr[i] + d; if (arr[i+1] - d == cur) ans++; if (arr[i+1] - d > cur) ans +=2; } out.println(ans); } class Number implements Comparable<Number>{ int x, cost; Number(int x, int cost){ this.x = x; this.cost = cost; } @Override public int compareTo(Number o) { return Integer.compare(this.cost, o.cost); } } class Point{ int x, y; Point(int x, int y){ this.x = x; this.y = y; } } class Vertex implements Comparable<Vertex>{ int num, depth, e, c; Vertex(int num, int depth, int e, int c){ this.num = num; this.e = e; this.depth = depth; this.c = c; } @Override public int compareTo(Vertex o) { return Integer.compare(this.e, o.e); } } /////////////////////////////////////////////////////////////////////////////////////////// class Edge{ int from, to, num; Edge(int to, int num){ this.to = to; this.num = num; } } class SparseTable{ int[][] rmq; int[] logTable; int n; SparseTable(int[] a){ n = a.length; logTable = new int[n+1]; for(int i = 2; i <= n; ++i){ logTable[i] = logTable[i >> 1] + 1; } rmq = new int[logTable[n] + 1][n]; for(int i=0; i<n; ++i){ rmq[0][i] = a[i]; } for(int k=1; (1 << k) < n; ++k){ for(int i=0; i + (1 << k) <= n; ++i){ int max1 = rmq[k - 1][i]; int max2 = rmq[k-1][i + (1 << (k-1))]; rmq[k][i] = Math.max(max1, max2); } } } int max(int l, int r){ int k = logTable[r - l]; int max1 = rmq[k][l]; int max2 = rmq[k][r - (1 << k) + 1]; return Math.max(max1, max2); } } long checkBit(long mask, int bit){ return (mask >> bit) & 1; } class Dsu{ int[] parent; int countSets; Dsu(int n){ countSets = n; parent = new int[n]; for(int i=0; i<n; ++i){ parent[i] = i; } } int findSet(int a){ if(parent[a] == a) return a; parent[a] = findSet(parent[a]); return parent[a]; } void unionSets(int a, int b){ a = findSet(a); b = findSet(b); if(a!=b){ countSets--; parent[a] = b; } } } static int checkBit(int mask, int bit) { return (mask >> bit) & 1; } boolean isLower(char c){ return c >= 'a' && c <= 'z'; } //////////////////////////////////////////////////////////// class SegmentTree{ int[] t; int n; SegmentTree(int n){ t = new int[4*n]; build(new int[n+1], 1, 1, n); } void build (int a[], int v, int tl, int tr) { if (tl == tr) t[v] = a[tl]; else { int tm = (tl + tr) / 2; build (a, v*2, tl, tm); build (a, v*2+1, tm+1, tr); } } void update (int v, int tl, int tr, int l, int r, int add) { if (l > r) return; if (l == tl && tr == r) t[v] += add; else { int tm = (tl + tr) / 2; update (v*2, tl, tm, l, Math.min(r,tm), add); update (v*2+1, tm+1, tr, Math.max(l,tm+1), r, add); } } int get (int v, int tl, int tr, int pos) { if (tl == tr) return t[v]; int tm = (tl + tr) / 2; if (pos <= tm) return t[v] + get (v*2, tl, tm, pos); else return t[v] + get (v*2+1, tm+1, tr, pos); } } class Fenwik { long[] t; int length; Fenwik(int[] a) { length = a.length + 100; t = new long[length]; for (int i = 0; i < a.length; ++i) { inc(i, a[i]); } } void inc(int ind, int delta) { for (; ind < length; ind = ind | (ind + 1)) { t[ind] = Math.max(delta, t[ind]); } } long getMax(int r) { long sum = 0; for (; r >= 0; r = (r & (r + 1)) - 1) { sum = Math.max(sum, t[r]); } return sum; } } int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); } long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } long binPow(long a, long b, long m) { if (b == 0) { return 1; } if (b % 2 == 1) { return ((a % m) * (binPow(a, b - 1, m) % m)) % m; } else { long c = binPow(a, b / 2, m); return (c * c) % m; } } int minInt(int... values) { int min = Integer.MAX_VALUE; for (int value : values) min = Math.min(min, value); return min; } int maxInt(int... values) { int max = Integer.MIN_VALUE; for (int value : values) max = Math.max(max, value); return max; } public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub new Main().run(); } void run() throws NumberFormatException, IOException { solve(); out.close(); }; BufferedReader in; PrintWriter out; StringTokenizer tok; String delim = " "; Random rnd = new Random(); Main() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } tok = new StringTokenizer(""); } String readLine() throws IOException { return in.readLine(); } String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) { return null; } tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt() throws NumberFormatException, IOException { return Integer.parseInt(readString()); } byte readByte() throws NumberFormatException, IOException { return Byte.parseByte(readString()); } int[] readIntArray (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } Integer[] readIntegerArray (int n) throws NumberFormatException, IOException { Integer[] a = new Integer[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } long readLong() throws NumberFormatException, IOException { return Long.parseLong(readString()); } double readDouble() throws NumberFormatException, IOException { return Double.parseDouble(readString()); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class CodeJ { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } public String next() { while(!st.hasMoreTokens()) { String l = nextLine(); if(l == null) return null; st = new StringTokenizer(l); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } } static int nFilas; static int nColumnas; static byte[][][][][] dp; static byte dp(int mascaraActual, int enviadosActual, int enviadosSiguiente, int filaActual, int columnaActual) { if(dp[mascaraActual][enviadosActual][enviadosSiguiente][filaActual][columnaActual] != Byte.MAX_VALUE) return dp[mascaraActual][enviadosActual][enviadosSiguiente][filaActual][columnaActual]; if(filaActual == nFilas) return dp[mascaraActual][enviadosActual][enviadosSiguiente][filaActual][columnaActual] = 0; if(columnaActual == nColumnas) { int ambos = mascaraActual & enviadosSiguiente; int mascaraSiguiente = (1 << nColumnas) - 1; mascaraSiguiente ^= ambos; int mascaraEnviados = enviadosSiguiente; mascaraEnviados ^= ambos; return dp[mascaraActual][enviadosActual][enviadosSiguiente][filaActual][columnaActual] = (byte) (nColumnas - Integer.bitCount(mascaraActual) + dp(mascaraSiguiente, mascaraEnviados, 0, filaActual + 1, 0)); } if(((mascaraActual & (1 << columnaActual)) == 0)) { // me envian desde abajo byte a = dp(mascaraActual | (1 << columnaActual), enviadosActual, enviadosSiguiente | (1 << columnaActual), filaActual, columnaActual + 1); // normal byte b = dp(mascaraActual, enviadosActual, enviadosSiguiente, filaActual, columnaActual + 1); return dp[mascaraActual][enviadosActual][enviadosSiguiente][filaActual][columnaActual] = (byte) Math.max(a, b); } if((enviadosActual & (1 << columnaActual)) != 0) { byte a = dp(mascaraActual, enviadosActual, enviadosSiguiente | (1 << columnaActual), filaActual, columnaActual + 1); byte b = dp(mascaraActual, enviadosActual, enviadosSiguiente, filaActual, columnaActual + 1); return dp[mascaraActual][enviadosActual][enviadosSiguiente][filaActual][columnaActual] = (byte) Math.max(a, b); } // izquierda byte ans = 0; if(columnaActual != 0) ans = (byte) Math.max(ans, dp((mascaraActual ^ (1 << columnaActual)) | (1 << (columnaActual - 1)), enviadosActual, enviadosSiguiente, filaActual, columnaActual + 1)); // derecha if(columnaActual != nColumnas - 1) ans = (byte) Math.max(ans, dp((mascaraActual ^ (1 << columnaActual)) | (1 << (columnaActual + 1)), enviadosActual | (1 << (columnaActual + 1)), enviadosSiguiente, filaActual, columnaActual + 1)); // abajo if(filaActual != nFilas - 1) ans = (byte) Math.max(ans, dp((mascaraActual ^ (1 << columnaActual)), enviadosActual, enviadosSiguiente | (1 << columnaActual), filaActual, columnaActual + 1)); // quieto ans = (byte) Math.max(ans, dp(mascaraActual, enviadosActual, enviadosSiguiente, filaActual, columnaActual + 1)); return dp[mascaraActual][enviadosActual][enviadosSiguiente][filaActual][columnaActual] = ans; } public static void main(String[] args) { Scanner sc = new Scanner(); int a = sc.nextInt(); int b = sc.nextInt(); nFilas = Math.max(a, b); nColumnas = Math.min(a, b); dp = new byte[1 << nColumnas][1 << nColumnas][1 << nColumnas][nFilas + 1][nColumnas + 1]; for(byte[][][][] i : dp) for(byte[][][] j : i) for(byte[][] k : j) for(byte[] l : k) Arrays.fill(l, Byte.MAX_VALUE); System.out.println(dp((1 << nColumnas) - 1, 0, 0, 0, 0)); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author ilyakor */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE1 solver = new TaskE1(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) { solver.solve(i, in, out); } out.close(); } static class TaskE1 { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); // int n = 12; // int m = 2000; int[][] d = new int[2][1 << n]; int[] buf = new int[1 << n]; int[][] a = new int[m][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { a[j][i] = in.nextInt(); // a[j][i] = (int)((i * 12346L + j * 789L) % 100000); } } ArrayList<Integer> inds = new ArrayList<>(); for (int i = 0; i < m; ++i) { inds.add(i); } int[][] finalA = a; Collections.sort(inds, new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { int val1 = 0, val2 = 0; for (int i = 0; i < n; ++i) { if (finalA[i1][i] > val1) { val1 = finalA[i1][i]; } } for (int i = 0; i < n; ++i) { if (finalA[i2][i] > val2) { val2 = finalA[i2][i]; } } return -Integer.compare(val1, val2); } }); int newM = Math.min(m, n + 1); int[][] na = new int[newM][]; for (int i = 0; i < newM; ++i) { int ind = inds.get(i); na[i] = a[ind]; } m = newM; a = na; for (int i = 0; i < m; ++i) { int[] prev = d[i % 2], nx = d[(i + 1) % 2]; for (int shift = 0; shift < n; ++shift) { int[] b = new int[n]; for (int j = 0; j < n; ++j) { b[j] = a[i][(j + shift) % n]; } System.arraycopy(prev, 0, buf, 0, prev.length); for (int j = 0; j < n; ++j) { int inc = b[j]; for (int mask = 0; mask < (1 << n); ++mask) { if ((mask >> j) % 2 == 0) { int val = buf[mask] + inc; int nm = mask ^ (1 << j); if (val > buf[nm]) { buf[nm] = val; } } } } for (int mask = 0; mask < (1 << n); ++mask) { if (nx[mask] < buf[mask]) { nx[mask] = buf[mask]; } } } } out.printLine(d[m % 2][(1 << n) - 1]); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public String nextToken() { int c = readSkipSpace(); StringBuilder sb = new StringBuilder(); while (!isSpace(c)) { sb.append((char) c); c = read(); } return sb.toString(); } public String next() { return nextToken(); } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
//package A; import java.util.Scanner; public class Solution { Scanner in = new Scanner(System.in); void run() throws Exception { int tests = in.nextInt(); while (tests > 0) { --tests; int a = in.nextInt(); int b = in.nextInt(); int res = 0; while (a > 0 && b > 0) { if (a >= b) { res += a / b; a %= b; } else { res += b / a; b %= a; } } System.out.println(res); } } public static void main(String args[]) throws Exception { new Solution().run(); } }
constant
267_A. Subtractions
CODEFORCES
/*(c) gorlum0 [at] gmail.com*/ import java.io.*; import java.util.*; import java.math.*; public class E { int bitcount(int x) { int c = 0; for ( ; x != 0; c++) x &= x-1; return c; } boolean bit(int x, int i) { if (i < 0) return false; return (x>>i & 1) == 1 ? true : false; } int solve(int n, int m) { if (m > n) { int x = m; m = n; n = x; } int maxmask = 1<<m; int[][][] dp = new int[n+1][maxmask][maxmask]; for (int i = 0; i <= n; i++) for (int j = 0; j < maxmask; j++) for (int k = 0; k < maxmask; k++) dp[i][j][k] = inf; for (int i = 0; i < maxmask; i++) dp[0][0][i] = bitcount(i); for (int i = 1; i <= n; i++) for (int b = 0; b < maxmask; b++) for (int c = 0; c < maxmask; c++) for (int a = 0; a < maxmask; a++) { boolean nospider = false; for (int j = 0; j < m; j++) if (not(bit(a,j) || bit(c,j) || bit(b,j-1) || bit(b,j) || bit(b,j+1))) { nospider = true; break; } if (nospider) continue; dp[i][b][c] = Math.min(dp[i][b][c], dp[i-1][a][b] + bitcount(c)); } int res = inf; for (int b = 0; b < maxmask; b++) res = Math.min(res, dp[n][b][0]); return n*m - res; } void main() throws IOException { int n; while ((n = nextInt()) != EOF) { int m = nextInt(); out.println(solve(n, m)); } } public static void main(String[] args) { new E().run(); } // ====================================================================== int inf = (int) 1e9; final int EOF = -1; boolean not(boolean p) { return !p; } int sqr(int x) { return x*x; } long sqr(long x) { return x*x; } double sqr(double x) { return x*x; } BufferedReader fin; StringTokenizer st; PrintWriter out; public void run() { try { fin = new BufferedReader(new InputStreamReader(System.in)); st = null; out = new PrintWriter(System.out); main(); fin.close(); out.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 (st == null || !st.hasMoreTokens()) { String line = fin.readLine(); if (line == null) return "-1"; else st = new StringTokenizer(line); } return st.nextToken(); } }
np
112_E. Petya and Spiders
CODEFORCES
import java.util.*; import java.io.*; public class Main { BufferedReader in; StringTokenizer str = null; private String next() throws Exception{ if (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception{ return Integer.parseInt(next()); } private long nextLong() throws Exception{ return Long.parseLong(next()); } private double nextDouble() throws Exception{ return Double.parseDouble(next()); } public void run() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); long l = nextLong(); long r = nextLong(); int bit = 63; while(bit >= 0 && (hasBit(l, bit) == hasBit(r, bit))) { bit--; } System.out.println((1L<<bit+1)-1); } private boolean hasBit(long x, int i){ return (x & (1L<<i)) > 0; } public static void main(String[] args) throws Exception{ new Main().run(); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); BPhoenixAndPuzzle solver = new BPhoenixAndPuzzle(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BPhoenixAndPuzzle { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); if (n % 2 == 1) { out.println("NO"); return; } n /= 2; if (n == 1 || (int) Math.sqrt(n) * (int) (Math.sqrt(n)) == n) { out.println("YES"); } else { if (n % 2 == 0) { n /= 2; if ((int) Math.sqrt(n) * (int) (Math.sqrt(n)) == n) { out.println("YES"); return; } } out.println("NO"); } } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.*; import java.util.*; public class A implements Runnable { public static void main(String[] args) { new A().run(); } class FastScanner { BufferedReader br; StringTokenizer st; boolean eof; String buf; public FastScanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); nextToken(); } public FastScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); nextToken(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; break; } } String ret = buf; buf = eof ? "-1" : st.nextToken(); return ret; } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } void close() { try { br.close(); } catch (Exception e) { } } boolean isEOF() { return eof; } } FastScanner sc; PrintWriter out; public void run() { Locale.setDefault(Locale.US); try { sc = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); sc.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } int nextInt() { return sc.nextInt(); } String nextToken() { return sc.nextToken(); } long nextLong() { return sc.nextLong(); } double nextDouble() { return sc.nextDouble(); } void solve() { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } Arrays.sort(a); int i = 1; while (i < n && a[i] == a[i - 1]) { ++i; } if (i >= n) { out.println("NO"); } else { out.println(a[i]); } } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.util.*; import java.lang.*; public class Main { static long m = 1000000007; static long powmod(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if((y & 1)==1) res = (res * x) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x * x) % p; } return res; } static long mulmod(long a, long b, long mod){ long res=0; a = a % mod; while (b > 0) { // If b is odd, add 'a' to result if (b % 2 == 1) res = (res + a) % mod; // Multiply 'a' with 2 a = (a * 2) % mod; // Divide b by 2 b /= 2; } // Return result return res % mod; } public static void main(String args[] ) throws Exception { Scanner sc = new Scanner(System.in); long x = sc.nextLong(); long k = sc.nextLong(); if(x>0) { long d= powmod(2,k,m); long ans= mulmod(d,2,m)%m; ans= mulmod(ans,x,m)%m; ans++; ans%=m; ans= (ans-d+m)%m; System.out.println(ans); } else System.out.println(0); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
/** * Created by IntelliJ IDEA. * User: aircube * Date: 11.01.11 * Time: 4:14 * To change this template use File | Settings | File Templates. */ import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.Exchanger; public class Template { BufferedReader br; PrintWriter out; StringTokenizer st; public static void main(String[] args) throws IOException { new Template().run(); } void run() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); st = null; out = new PrintWriter(System.out); solve(); br.close(); out.close(); } double dm[]; double a[][]; boolean fil[]; int p[]; int n; // x & (x - 1) // 10 // void solve() throws IOException { n = nextInt(); a = new double[n][n]; for(int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { a[i][j] = nextDouble(); } dm = new double[1 << n]; fil = new boolean[1 << n]; for(int i = 0; i < n; ++i) { out.print(brute((1 << i)) + " "); } } private double brute(int mask) { if (Integer.bitCount(mask) == n) return 1; if (fil[mask]) return dm[mask]; int c = Integer.bitCount(mask); double res = 0; double p = 2.0 / (double) (c + 1) / (double)(c ) ; for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if ((mask & (1 << i)) == 0 && (mask & (1 << j)) > 0) { res += a[j][i] * brute(mask ^ (1 << i)); } } } res *= p; dm[mask] = res; fil[mask] = true; return dm[mask]; } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }
np
16_E. Fish
CODEFORCES
import java.io.*; import java.util.*; public class A { long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } long solve(long a,long b) { if (a == 0 || b ==0) { return 0; } long t = gcd(a,b); a /= t; b /= t; if (a>b) { return solve(a%b,b)+a/b; } else { return solve(a,b%a)+b/a; } } void solve() throws IOException { long a = nextLong(); long b = nextLong(); out.println(solve(a, b)); } void run() 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().run(); } BufferedReader br; PrintWriter out; StringTokenizer str; String next() throws IOException { while (str == null || !str.hasMoreTokens()) { str = new StringTokenizer(br.readLine()); } return str.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()); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class A { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); br.readLine(); String[] ss = br.readLine().split(" "); int n = ss.length; int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = Integer.parseInt(ss[i]); for (int i = 0; i < n; ++i) { boolean ok = true; for (int j = 0; j < n; ++j) if (j != i && a[j] % 2 == a[i] % 2) ok = false; if (ok) System.out.println(i + 1); } } }
linear
25_A. IQ test
CODEFORCES
import java.io.*; public class CF8C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int si = s.indexOf(' ', 0); int x = Integer.parseInt(s.substring(0, si)); int y = Integer.parseInt(s.substring(si + 1)); int n = Integer.parseInt(br.readLine()); int[] xx = new int[n + 1]; int[] yy = new int[n + 1]; for (int i = 0; i < n; i++) { s = br.readLine(); si = s.indexOf(' ', 0); xx[i] = Integer.parseInt(s.substring(0, si)); yy[i] = Integer.parseInt(s.substring(si + 1)); } xx[n] = x; yy[n] = y; int[][] dd = new int[n + 1][n + 1]; for (int i = 0; i <= n; i++) for (int j = i + 1; j <= n; j++) { int dx = xx[i] - xx[j]; int dy = yy[i] - yy[j]; dd[i][j] = dx * dx + dy * dy; } int[] aa = new int[1 << n]; int[] bb = new int[1 << n]; for (int k = 1; k < 1 << n; k++) { int a = -1; for (int b = 0; b < n; b++) if ((k & 1 << b) > 0) { a = b; break; } int l = k ^ 1 << a; int d = dd[a][n] + dd[a][n]; aa[k] = aa[l] + d; bb[k] = l; for (int b = a + 1; b < n; b++) if ((k & 1 << b) > 0) { l = k ^ 1 << a ^ 1 << b; d = dd[a][n] + dd[b][n] + dd[a][b]; if (aa[l] + d < aa[k]) { aa[k] = aa[l] + d; bb[k] = l; } } } int k = (1 << n) - 1; System.out.println(aa[k]); StringBuilder sb = new StringBuilder(); sb.append(0); while (k != 0) { int l = bb[k]; int m = k ^ l; for (int b = 0; b < n; b++) if ((m & 1 << b) > 0) sb.append(' ').append(b + 1); sb.append(' ').append(0); k = l; } System.out.println(sb); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException{ Scanner cin = new Scanner(System.in); int t, n, m; t = cin.nextInt(); while(t > 0) { t--; int sum = 0; n = cin.nextInt(); m = cin.nextInt(); while(n > 0 && m > 0) { if(n < m) { int k = n; n = m; m = k; } sum += n / m; n %= m; } System.out.println(sum); } } }
constant
267_A. Subtractions
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.next()); int[] a = new int[N]; int[] flag = new int[N]; int ans = 0; for (int i=0;i<N;i++) { a[i] = Integer.parseInt(sc.next()); } Arrays.sort(a); for (int i=0;i<N;i++) { int used = 0; for (int j=0;j<N;j++) { if (flag[j]==1) { continue; } else { if (a[j]%a[i]==0) { used=1; flag[j]=1; } } } if (used==1) { ans++; } } System.out.println(ans); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.InputMismatchException; public class E46A { public static void main(String[] args) { FastScanner in = new FastScanner(System.in); String[] sizes = {"XXXS", "XXS", "XS", "S", "M", "L", "XL", "XXL", "XXXL"}; int n = in.nextInt(); HashMap<String, Integer> a = new HashMap<>(); HashMap<String, Integer> b = new HashMap<>(); for (String s : sizes) { a.put(s, 0); b.put(s, 0); } for (int i = 0; i < n; i++) { String s = in.next(); a.put(s, a.get(s) + 1); } for (int i = 0; i < n; i++) { String s = in.next(); b.put(s, b.get(s) + 1); } for (String s : sizes) { int cut = Math.min(a.get(s), b.get(s)); a.put(s, a.get(s) - cut); b.put(s, b.get(s) - cut); } int changes = 0; for (String s : sizes) changes += a.get(s); System.out.println(changes); } /** * Source: Matt Fontaine */ public static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); new Main().run(in, out); out.close(); } public static long mod = 17352642619633L; void run(FastScanner in, PrintWriter out) { // kth digit long K = in.nextLong(); // which number encompasses the Kth digit long lo = 1; long hi = (long)1e12+1; while (lo < hi) { long m = (lo+hi)>>1; long d = numDigitsLte(m); if (d <= K) { lo = m+1; } else { hi = m; } } // 123[1]1391 = m digits long numDigits = numDigitsLte(lo); if (numDigitsLte(lo-1) == K) { out.println((((lo-1)%10)+10)%10); } else { int offset = (int)(numDigits-K); // out.print(lo + " "); List<Long> digits = new ArrayList<>(); while (lo > 0) { digits.add(lo%10); lo /= 10; } // backwards // before : 1[2]3456 // in list: 6543[2]1 // offset = 4 out.println(digits.get(offset)); } } static long[] dig = new long[15]; static { for (int i = 1; i < dig.length; i++) { dig[i] = 9 * (long)Math.pow(10, i-1) * i; } for (int i = 1; i < dig.length; i++) { dig[i] += dig[i-1]; } } long numDigitsLte(long m) { if (m <= 9) return m; int numDigits = 0; long M = m; while (M > 0) { numDigits++; M /= 10; } long ret = dig[numDigits-1]; ret += (m-(long)Math.pow(10, numDigits-1)+1)*numDigits; return ret; // digits below // 9 + 90 + 900 // [1-9], [10-99], [100-999] // 9, 90*2, 900*3, ... // 9999.. // 9138 // [1-1000), [1000,9138] } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } 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()); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader c=new BufferedReader(new InputStreamReader(System.in)); String S[]=c.readLine().split(" "); int N=Integer.parseInt(S[0]); int K=Integer.parseInt(S[1]); int A[]=parseArray(c.readLine(),N); shuffle(A); Arrays.sort(A); TreeMap<Long,Long> T=new TreeMap<Long, Long>(); int ans=0; for(int i=0;i<N;i++) T.put((long)A[i],1L); //System.out.println(Arrays.toString(A)); if(K==1) { System.out.println(N); return; } else { for(int i=0;i<N;i++) { if(A[i]%K==0&&T.containsKey((long)A[i]/K)) //A[i] is not start of a chain continue; //System.out.println("considering "+A[i]); int chainSize=0; long init=A[i]; while(T.containsKey(init)) { chainSize++; init=init*K; } //System.out.println("\t"+chainSize); ans+=(chainSize+1)/2; } } System.out.println(ans); } /** * Knuth's shuffle. Generate a random permutation of an array */ public static int[] shuffle(int A[]) { int N=A.length; for(int i=1;i<N;i++) { int j=(int) (Math.random()*100000)%(i+1); // 0<=j<=i; int temp=A[i]; A[i]=A[j]; A[j]=temp; } return A; } // Parse an integer array of size N from a string s public static int[] parseArray(String s,int N) { int A[]=new int[N]; StringTokenizer st=new StringTokenizer(s); for(int i=0;i<N;i++) A[i]=Integer.parseInt(st.nextToken()); return A; } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.*; import java.util.*; /* * And now I wonder if I should delete these comments cause they might throw me off. * Lol who cares though? */ public class R364C { public static void main(String[] args) throws NumberFormatException, IOException { Scanner s = new Scanner(System.in); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(f.readLine()); char[] a = f.readLine().toCharArray(); int difTypes = 0; TreeSet<Character> types = new TreeSet<Character>(); for(int i = 0; i < n; i++) { if(!types.contains(a[i])) { types.add(a[i]); } } int i = 0, j = 0; difTypes = types.size(); int curTypes = 0; int min = Integer.MAX_VALUE; TreeSet<Character> has = new TreeSet<Character>(); HashMap<Character, Integer> freq = new HashMap<Character, Integer>(); while(i < n && j < n) { // System.out.println(i + " " + j); has.add(a[j]); if(!freq.containsKey(a[j])) { freq.put(a[j], 1); } else { freq.put(a[j], freq.get(a[j])+1); } j++; curTypes = has.size(); if(curTypes == difTypes) min = Math.min(min, j-i); // System.out.println(freq.toString()); // System.out.println(curTypes); // System.out.println(); while(i < n && has.size() == difTypes) { int Freq = freq.get(a[i]); // System.out.println(Freq); if(Freq - 1 == 0) { has.remove(a[i]); freq.put(a[i], freq.get(a[i])-1); i++; break; } freq.put(a[i], freq.get(a[i])-1); i++; if(curTypes == difTypes) min = Math.min(min, j-i); } curTypes = has.size(); } // if(curTypes == difTypes) min = Math.min(min, j-i); System.out.println(min); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; public class Main { HashMap<Integer,Pair> map; int n,a[]; private void solve()throws IOException { n=nextInt(); a=new int[n+1]; for(int i=1;i<=n;i++) a[i]=nextInt(); map=new HashMap<>(); for(int i=1;i<=n;i++) { int sum=0; for(int j=i;j>=1;j--) { sum+=a[j]; if(!map.containsKey(sum)) map.put(sum,new Pair(i,1)); else { Pair p=map.get(sum); if(p.pos<j) map.put(sum,new Pair(i,p.cnt+1)); } } } int sum=0,ans=0; for(int i:map.keySet()) if(map.get(i).cnt>ans) { ans=map.get(i).cnt; sum=i; } out.println(ans); ArrayList<String> list=new ArrayList<>(); for(int i=1,prev=0;i<=n;i++) { int s=0; for(int j=i;j>=1;j--) { s+=a[j]; if(s==sum && j>prev) { list.add(j+" "+i); prev=i; } } } for(String s:list) out.println(s); } class Pair{ int pos,cnt; Pair(int a,int b){ pos=a; cnt=b; } } /////////////////////////////////////////////////////////// public void run()throws IOException { br=new BufferedReader(new InputStreamReader(System.in)); st=null; out=new PrintWriter(System.out); solve(); br.close(); out.close(); } public static void main(String args[])throws IOException{ new Main().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; String nextToken()throws IOException{ while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine()throws IOException{ return br.readLine(); } int nextInt()throws IOException{ return Integer.parseInt(nextToken()); } long nextLong()throws IOException{ return Long.parseLong(nextToken()); } double nextDouble()throws IOException{ return Double.parseDouble(nextToken()); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class P111C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int h, w; void run(){ h=sc.nextInt(); w=sc.nextInt(); solve(); } void shuffle(int[] is){ Random rand=new Random(); for(int i=is.length-1; i>=1; i--){ int j=rand.nextInt(i+1); int t=is[i]; is[i]=is[j]; is[j]=t; } } void solve(){ n=w*h; g=new long[n]; int[] dx={0, 0, -1, 1}; int[] dy={-1, 1, 0, 0}; int[] _=new int[n]; for(int i=0; i<n; i++){ _[i]=i; } shuffle(_); HashMap<Integer, Integer> map=new HashMap<Integer, Integer>(); for(int i=0; i<n; i++){ map.put(_[i], i); } for(int y=0; y<h; y++){ for(int x=0; x<w; x++){ for(int k=0; k<4; k++){ int x2=x+dx[k]; int y2=y+dy[k]; if(x2>=0&&x2<w&&y2>=0&&y2<h){ // g[y*w+x]|=1L<<(y2*w+x2); g[map.get(y*w+x)]|=1L<<(map.get(y2*w+x2)); } } } } mds=(1L<<n)-1; mds(0, 0, 0); println((n-Long.bitCount(mds))+""); } int n; long[] g; long mds; long[] candidate; void mds(long choosed, long removed, long covered){ if(Long.bitCount(choosed)>=Long.bitCount(mds)) return; if(covered==((1L<<n)-1)){ if(Long.bitCount(choosed)<Long.bitCount(mds)) mds=choosed; return; } int k=-1; // ArrayList<Integer> list=new ArrayList<Integer>(); for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); if((covered>>>i&1)==1){ if(Long.bitCount(g[i]&~covered)==0){ mds(choosed, removed|(1L<<i), covered); return; }else if(Long.bitCount(g[i]&~covered)==1 &&(g[i]&~covered&~removed)!=0){ mds(choosed, removed|(1L<<i), covered); return; } }else{ if(Long.bitCount(g[i]&~removed)==0){ mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]); return; }else if(Long.bitCount(g[i]&~removed)==1 &&((g[i]&~removed)|(g[i]&~covered))==(g[i]&~removed)){ int j=Long.numberOfTrailingZeros(g[i]&~removed); mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered |(1L<<j)|g[j]); return; } } if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)) k=i; if(false){ /* if(k==-1 ||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k] &~covered)){ list.clear(); list.add(i); k=i; }else if(Long.bitCount(g[i]&~covered)==Long.bitCount(g[k] &~covered)) list.add(i); */ } } if(k==-1) return; // k=list.get((int)(list.size()*random())); mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]); mds(choosed, removed|(1L<<k), covered); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } public static void main(String[] args){ Locale.setDefault(Locale.US); new P111C().run(); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { static final long MODULO = (long) (1e9 + 7); public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); long[][] dp = new long[n + 100][n + 100]; dp[0][0] = 1; for (int i = 0; i < n; ++i) { char current = in.nextCharacter(); if (current == 'f') { for (int j = 0; j < n; ++j) { dp[i + 1][j + 1] += dp[i][j]; dp[i + 1][j + 1] %= MODULO; } } else { long runningSum = 0; for (int j = n; j >= 0; --j) { runningSum += dp[i][j]; runningSum %= MODULO; dp[i + 1][j] += runningSum; dp[i + 1][j] %= MODULO; } } } out.println(dp[n][0]); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char nextCharacter() { int c = pread(); while (isSpaceChar(c)) c = pread(); return (char) c; } } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Round113_A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt() - 1; Obe[] a = new Obe[n]; for (int i = 0; i < n; i++) a[i] = new Obe(in.nextInt(), in.nextInt()); Arrays.sort(a); int c = 0; int p = 0, d = 0; if (k > -1 && k < n) { c = 1; p = a[k].p; d = a[k].d; } else { System.out.println(c); return; } for (int i = k + 1; i < n; i++) { if (a[i].p == p && a[i].d == d) c++; } for (int i = k - 1; i > -1; i--) { if (a[i].p == p && a[i].d == d) c++; } System.out.println(c); } } class Obe implements Comparable<Obe> { int p, d; public Obe(int pe, int de) { p = pe; d = de; } @Override public int compareTo(Obe o) { int x = new Integer(o.p).compareTo(this.p); if (x != 0) return x; return new Integer(this.d).compareTo(o.d); } }
nlogn
166_A. Rank List
CODEFORCES
import java.util.Scanner; public class Main { private static boolean check(int n , int m , int k) { for (int i = 0;i < n;i ++) { for (int j = 0;j < n;j ++) { for (int l = 0;l < (1 << n);l ++) { dp[i][j][l] = - 1; } } } for (int i = 0;i < n;i ++) { if (dfs(i , i , n , m , k , 0)) { return true; } } return false; } private static boolean dfs(int first , int current , int n , int m , int k , int bitmap) { bitmap |= (1 << current); if (bitmap == (1 << n) - 1) { // check first and current if (n == 1) { if (m > 1) { if (rowMinDist[current] >= k) { return true; } else { return false; } } else { return true; } } else { if (m > 1) { if (minDistBetweenHeadAndTail[first][current] >= k) { return true; } else { return false; } } else { return true; } } } else { if (dp[first][current][bitmap] >= 0) { if (dp[first][current][bitmap] > 0) { return true; } else { return false; } } short ans = 0; for (int i = 0;i < n;i ++) { if ((bitmap & (1 << i)) == 0 && minDistBetweenRow[current][i] >= k) { if (dfs(first , i , n , m , k , bitmap)) { ans = 1; break; } } } dp[first][current][bitmap] = ans; if (ans > 0) { return true; } else { return false; } } } private static short[][][] dp = new short[20][20][(1 << 17)]; private static int[][] input = new int[20][10010]; private static int[][] minDistBetweenRow = new int[20][20]; private static int[][] minDistBetweenHeadAndTail = new int[20][20]; private static int[] rowMinDist = new int[20]; public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i , j , k , n , m; n = scan.nextInt(); m = scan.nextInt(); for (i = 0;i < n;i ++) { for (j = 0;j < m;j ++) { input[i][j] = scan.nextInt(); } } for (i = 0;i < n;i ++) { for (j = i + 1;j < n;j ++) { int minDist = - 1; for (k = 0;k < m;k ++) { int dist = Math.abs(input[i][k] - input[j][k]); if (dist < minDist || minDist < 0) { minDist = dist; } } minDistBetweenRow[i][j] = minDistBetweenRow[j][i] = minDist; } } for (i = 0;i < n;i ++) { for (j = 0;j < n;j ++) { if (i != j) { // i head , j tail int minDist = - 1; for (k = 0;k < m - 1;k ++) { int dist = Math.abs(input[j][k] - input[i][k + 1]); if (dist < minDist || minDist < 0) { minDist = dist; } } minDistBetweenHeadAndTail[i][j] = minDist; } } } for (i = 0;i < n;i ++) { int minDist = - 1; for (j = 0;j < m - 1;j ++) { int dist = Math.abs(input[i][j] - input[i][j + 1]); if (dist < minDist || minDist < 0) { minDist = dist; } } rowMinDist[i] = minDist; } int low = 0 , high = 1000000010; while (low < high) { int mid = (low + high) / 2; if (check(n , m , mid)) { low = mid + 1; } else { high = mid; } } System.out.println(high - 1); } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.util.*; import java.io.*; public class Sol{ static class Pair implements Comparable<Pair>{ int x;int y;int value; public Pair(int x,int y,int value) { this.x=x; this.y=y; this.value=value; } @Override public int compareTo(Pair p){return Long.compare(y,p.y); } } public static void main(String []args){ int t=1; while(t-->0){ int n=ni();mod=nl(); precomp(); long dp[][]=new long[405][405];dp[0][0]=1l; for(int i=0;i<n;i++){ for(int j=0;j<=i;j++){ for(int k=1;k+i<=n;k++){ dp[i+k+1][j+k]+=((dp[i][j]*p2[k-1])%mod)*Comb[k+j][k]; dp[i+k+1][j+k]%=mod; } } } long sum=0l; for(int i=0;i<=n;i++)sum=(sum+dp[n+1][i])%mod; out.println(sum); }out.close();} //-----------------Utility-------------------------------------------- static long Comb[][]=new long[405][405]; static long p2[]=new long[405]; static long inv[]=new long[405]; static long factorial[]=new long[405]; static void precomp(){ inv[0]=1;factorial[0]=1l; for(long i=1;i<405;i++){factorial[(int)i]=i*factorial[(int)i-1];factorial[(int)i]%=mod;} for(int i=1;i<405;i++){ inv[i]=power(factorial[i],mod-2);} for(int i=0;i<405;i++){ for(int j=0;j<=i;j++){ Comb[i][j]=(((factorial[i]*inv[j])%mod)*inv[i-j])%mod; } } for(int i=0;i<405;i++)p2[i]=power(2,i); } static int Max=Integer.MAX_VALUE; static long mod=1000000007; static int v(char c){return (int)(c-'a')+1;} public static long power(long x, long y ) { //0^0 = 1 long res = 1L; x = x%mod; while(y > 0) { if((y&1)==1) res = (res*x)%mod; y >>= 1; x = (x*x)%mod; } return res; } //-------------------------------------------------------------------- static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static FastReader in=new FastReader(inputStream); static PrintWriter out=new PrintWriter(outputStream); static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int ni(){return in.nextInt();} static long nl(){return in.nextLong();} static String ns(){return in.nextLine();} static int[] na(int n){int a[]=new int[n];for(int i=0;i<n;i++){a[i]=ni();} return a;} }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int m = s.nextInt(); int k = s.nextInt(); int a[] = new int [n]; for (int i = 0; i < a.length; i++) { a[i] = s.nextInt(); } int ans = 0; while(k < m){ k--; int max = -1; int ix = -1; for (int i = 0; i < a.length; i++) { if(a[i] > max){ max = a[i]; ix = i; } } if(ix == -1){ System.out.println("-1"); return ; } k += a[ix]; a[ix] = -1; ans++; } System.out.println(ans); } }
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; public class Bag implements Runnable { private void solve() throws IOException { int xs = nextInt(); int ys = nextInt(); int n = nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = nextInt(); y[i] = nextInt(); } final int[][] pair = new int[n][n]; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]); final int[] single = new int[n]; for (int i = 0; i < n; ++i) { single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys)); } final int[] best = new int[1 << n]; final int[] prev = new int[1 << n]; for (int set = 1; set < (1 << n); ++set) { int i; for (i = 0; i < n; ++i) if ((set & (1 << i)) != 0) break; int bestC = best[set ^ (1 << i)] + single[i]; int prevC = 1 << i; int nextSet = set ^ (1 << i); int unoI = 1 << i; for (int j = i + 1, unoJ = 1 << (i + 1); j < n; ++j, unoJ <<= 1) if ((set & unoJ) != 0) { int cur = best[nextSet ^ unoJ] + pair[i][j]; if (cur < bestC) { bestC = cur; prevC = unoI | unoJ; } } best[set] = bestC; prev[set] = prevC; } writer.println(best[(1 << n) - 1]); int now = (1 << n) - 1; writer.print("0"); while (now > 0) { int differents = prev[now]; for(int i = 0; i < n; i++) if((differents & (1 << i)) != 0) { writer.print(" "); writer.print(i + 1); now ^= 1 << i; } writer.print(" "); writer.print("0"); } writer.println(); } public static void main(String[] args) { new Bag().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
8_C. Looking for Order
CODEFORCES
import javax.print.attribute.standard.PrinterMessageFromOperator; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().run();} // int[] h,ne,to,wt; // int ct = 0; // int n; // void graph(int n,int m){ // h = new int[n]; // Arrays.fill(h,-1); //// sccno = new int[n]; //// dfn = new int[n]; //// low = new int[n]; //// iscut = new boolean[n]; // ne = new int[2*m]; // to = new int[2*m]; // wt = new int[2*m]; // ct = 0; // } // void add(int u,int v,int w){ // to[ct] = v; // ne[ct] = h[u]; // wt[ct] = w; // h[u] = ct++; // } // // int color[],dfn[],low[],stack[] = new int[1000000],cnt[]; // int sccno[]; // boolean iscut[]; // int time = 0,top = 0; // int scc_cnt = 0; // // // 有向图的强连通分量 // void tarjan(int u) { // low[u] = dfn[u]= ++time; // stack[top++] = u; // for(int i=h[u];i!=-1;i=ne[i]) { // int v = to[i]; // if(dfn[v]==0) { // tarjan(v); // low[u]=Math.min(low[u],low[v]); // } else if(sccno[v]==0) { // // dfn>0 but sccno==0, means it's in current stack // low[u]=Math.min(low[u],low[v]); // } // } // // if(dfn[u]==low[u]) { // sccno[u] = ++scc_cnt; // while(stack[top-1]!=u) { // sccno[stack[top-1]] = scc_cnt; // --top; // } // --top; // } // } // // //缩点, topology sort // int[] h1,to1,ne1; // int ct1 = 0; // void point(){ // for(int i=0;i<n;i++) { // if(dfn[i]==0) tarjan(i);//有可能图不连通,所以要循环判断。 // } // // 入度 // int du[] = new int[scc_cnt+1]; // h1 = new int[scc_cnt+1]; // Arrays.fill(h1, -1); // to1 = new int[scc_cnt*scc_cnt]; // ne1 = new int[scc_cnt*scc_cnt]; // // scc_cnt 个点 // // for(int i=1;i<=n;i++) { // for(int j=h[i]; j!=-1; j=ne[j]) { // int y = to[j]; // if(sccno[i] != sccno[y]) { // // add(sccno[i],sccno[y]); // 建新图 // to1[ct1] = sccno[y]; // ne1[ct1] = h[sccno[i]]; // h[sccno[i]] = ct1++; // du[sccno[y]]++; //存入度 // } // } // } // // int q[] = new int[100000]; // int end = 0; // int st = 0; // for(int i=1;i<=scc_cnt;++i){ // if(du[i]==0){ // q[end++] = i; // } // } // // int dp[] = new int[scc_cnt+1]; // while(st<end){ // int cur = q[st++]; // for(int i=h1[cur];i!=-1;i=ne1[i]){ // int y = to[i]; // // dp[y] += dp[cur]; // if(--du[y]==0){ // q[end++] = y; // } // } // } // } // // // // // int fa[]; // int faw[]; // // int dep = -1; // int pt = 0; // void go(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt = cur; // } // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (fp == v) continue; // // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // int pt1 = -1; // void go1(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt1 = cur; // } // // fa[cur] = fp; // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (v == fp) continue; // faw[v] = wt[i]; // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // // int r = 0; // int stk[] = new int[301]; // int fk[] = new int[301]; // int lk[] = new int[301]; // void ddfs(int rt,int t1,int t2,int t3,int l){ // // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = t3;p++; // while(p>0){ // int cur = stk[p-1]; // int fp = fk[p-1]; // int ll = lk[p-1]; // p--; // r = Math.max(r,ll); // for(int i=h[cur];i!=-1;i=ne[i]){ // int v = to[i]; // if(v==t1||v==t2||v==fp) continue; // stk[p] = v; // lk[p] = ll+wt[i]; // fk[p] = cur;p++; // } // } // // // // } static long mul(long a, long b, long p) { long res=0,base=a; while(b>0) { if((b&1L)>0) res=(res+base)%p; base=(base+base)%p; b>>=1; } return res; } static long mod_pow(long k,long n,long p){ long res = 1L; long temp = k; while(n!=0L){ if((n&1L)==1L){ res = (res*temp)%p; } temp = (temp*temp)%p; n = n>>1L; } return res%p; } int ct = 0; int f[] =new int[200001]; int b[] =new int[200001]; int str[] =new int[200001]; void go(int rt,List<Integer> g[]){ str[ct] = rt; f[rt] = ct; for(int cd:g[rt]){ ct++; go(cd,g); } b[rt] = ct; } int add =0; void go(int rt,int sd,int k,List<Integer> g[],int n){ if(add>n) { return; } Queue<Integer> q =new LinkedList<>(); q.offer(rt); for(int i=1;i<=sd;++i){ int sz =q.size(); if(sz==0) break; int f = (i==1?2:1); while(sz-->0){ int cur = q.poll(); for(int j=0;j<k-f;++j){ q.offer(add); g[cur].add(add);add++; if(add==n+1){ return; } } } } } void solve() { int n = ni(); int s[] = new int[n+1]; for(int i=0;i<n;++i){ s[i+1] = s[i] + ni(); } Map<Integer,List<int[]>> mp = new HashMap<>(); for(int i=0;i<n;++i) { for (int j = i; j>=0; --j) { int v = s[i+1]-s[j]; if(!mp.containsKey(v)){ mp.put(v, new ArrayList<>()); } mp.get(v).add(new int[]{j+1,i+1}); } } int all = 0;int vv = -1; for(int v:mp.keySet()){ List<int[]> r = mp.get(v); ;int c = 0; int ri = -2000000000; for(int [] fk : r){ if(fk[0]>ri){ ri = fk[1];c++; } } if(c>all){ all = c; vv = v; } } println(all); List<int[]> r = mp.get(vv); int ri = -2000000000; for(int fk[]:r){ if(fk[0]>ri){ ri = fk[1];println((fk[0])+" "+(fk[1])); } } //N , M , K , a , b , c , d . 其中N , M是矩阵的行列数;K 是上锁的房间数目,(a, b)是起始位置,(c, d)是出口位置 // int n = ni(); // int m = ni(); // int k = ni(); // int a = ni(); // int b = ni(); // int c = ni(); // int d = ni(); // // // char cc[][] = nm(n,m); // char keys[][] = new char[n][m]; // // char ky = 'a'; // for(int i=0;i<k;++i){ // int x = ni(); // int y = ni(); // keys[x][y] = ky; // ky++; // } // int f1[] = {a,b,0}; // // int dd[][] = {{0,1},{0,-1},{1,0},{-1,0}}; // // Queue<int[]> q = new LinkedList<>(); // q.offer(f1); // int ts = 1; // // boolean vis[][][] = new boolean[n][m][33]; // // while(q.size()>0){ // int sz = q.size(); // while(sz-->0) { // int cur[] = q.poll(); // vis[cur[0]][cur[1]][cur[2]] = true; // // int x = cur[0]; // int y = cur[1]; // // for (int u[] : dd) { // int lx = x + u[0]; // int ly = y + u[1]; // if (lx >= 0 && ly >= 0 && lx < n && ly < m && (cc[lx][ly] != '#')&&!vis[lx][ly][cur[2]]){ // char ck =cc[lx][ly]; // if(ck=='.'){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // // }else if(ck>='A'&&ck<='Z'){ // int g = 1<<(ck-'A'); // if((g&cur[2])>0){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true;; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // } // } // } // } // // } // ts++; // } // println(-1); // int n = ni(); // // HashSet<String> st = new HashSet<>(); // HashMap<String,Integer> mp = new HashMap<>(); // // // for(int i=0;i<n;++i){ // String s = ns(); // int id= 1; // if(mp.containsKey(s)){ // int u = mp.get(s); // id = u; // // } // // if(st.contains(s)) { // // while (true) { // String ts = s + id; // if (!st.contains(ts)) { // s = ts; // break; // } // id++; // } // mp.put(s,id+1); // }else{ // mp.put(s,1); // } // println(s); // st.add(s); // // } // int t = ni(); // // for(int i=0;i<t;++i){ // int n = ni(); // long w[] = nal(n); // // Map<Long,Long> mp = new HashMap<>(); // PriorityQueue<long[]> q =new PriorityQueue<>((xx,xy)->{return Long.compare(xx[0],xy[0]);}); // // for(int j=0;j<n;++j){ // q.offer(new long[]{w[j],0}); // mp.put(w[j],mp.getOrDefault(w[j],0L)+1L); // } // // while(q.size()>=2){ // long f[] = q.poll(); // long y1 = f[1]; // if(y1==0){ // y1 = mp.get(f[0]); // if(y1==1){ // mp.remove(f[0]); // }else{ // mp.put(f[0],y1-1); // } // } // long g[] = q.poll(); // long y2 = g[1]; // if(y2==0){ // y2 = mp.get(g[0]); // if(y2==1){ // mp.remove(g[0]); // }else{ // mp.put(g[0],y2-1); // } // } // q.offer(new long[]{f[0]+g[0],2L*y1*y2}); // // } // long r[] = q.poll(); // println(r[1]); // // // // // } // int o= 9*8*7*6; // println(o); // int t = ni(); // for(int i=0;i<t;++i){ // long a = nl(); // int k = ni(); // if(k==1){ // println(a); // continue; // } // // int f = (int)(a%10L); // int s = 1; // int j = 0; // for(;j<30;j+=2){ // int u = f-j; // if(u<0){ // u = 10+u; // } // s = u*s; // s = s%10; // if(s==k){ // break; // } // } // // if(s==k) { // println(a - j - 2); // }else{ // println(-1); // } // // // // // } // int m = ni(); // h = new int[n]; // to = new int[2*(n-1)]; // ne = new int[2*(n-1)]; // wt = new int[2*(n-1)]; // // for(int i=0;i<n-1;++i){ // int u = ni()-1; // int v = ni()-1; // // } // long a[] = nal(n); // int n = ni(); // int k = ni(); // t1 = new long[200002]; // // int p[][] = new int[n][3]; // // for(int i=0;i<n;++i){ // p[i][0] = ni(); // p[i][1] = ni(); // p[i][2] = i+1; // } // Arrays.sort(p, new Comparator<int[]>() { // @Override // public int compare(int[] x, int[] y) { // if(x[1]!=y[1]){ // return Integer.compare(x[1],y[1]); // } // return Integer.compare(y[0], x[0]); // } // }); // // for(int i=0;i<n;++i){ // int ck = p[i][0]; // // } } // int []h,to,ne,wt; long t1[]; // long t2[]; void update(long[] t,int i,long v){ for(;i<t.length;i+=(i&-i)){ t[i] += v; } } long get(long[] t,int i){ long s = 0; for(;i>0;i-=(i&-i)){ s += t[i]; } return s; } int equal_bigger(long t[],long v){ int s=0,p=0; for(int i=Integer.numberOfTrailingZeros(Integer.highestOneBit(t.length));i>=0;--i) { if(p+(1<<i)< t.length && s + t[p+(1<<i)] < v){ v -= t[p+(1<<i)]; p |= 1<<i; } } return p+1; } static class S{ int l = 0; int r = 0 ; long le = 0; long ri = 0; long tot = 0; long all = 0; public S(int l,int r) { this.l = l; this.r = r; } } static S a[]; static int[] o; static void init(int[] f){ o = f; int len = o.length; a = new S[len*4]; build(1,0,len-1); } static void build(int num,int l,int r){ S cur = new S(l,r); if(l==r){ a[num] = cur; return; }else{ int m = (l+r)>>1; int le = num<<1; int ri = le|1; build(le, l,m); build(ri, m+1,r); a[num] = cur; pushup(num, le, ri); } } // static int query(int num,int l,int r){ // // if(a[num].l>=l&&a[num].r<=r){ // return a[num].tot; // }else{ // int m = (a[num].l+a[num].r)>>1; // int le = num<<1; // int ri = le|1; // pushdown(num, le, ri); // int ma = 1; // int mi = 100000001; // if(l<=m) { // int r1 = query(le, l, r); // ma = ma*r1; // // } // if(r>m){ // int r2 = query(ri, l, r); // ma = ma*r2; // } // return ma; // } // } static long dd = 10007; static void update(int num,int l,long v){ if(a[num].l==a[num].r){ a[num].le = v%dd; a[num].ri = v%dd; a[num].all = v%dd; a[num].tot = v%dd; }else{ int m = (a[num].l+a[num].r)>>1; int le = num<<1; int ri = le|1; pushdown(num, le, ri); if(l<=m){ update(le,l,v); } if(l>m){ update(ri,l,v); } pushup(num,le,ri); } } static void pushup(int num,int le,int ri){ a[num].all = (a[le].all*a[ri].all)%dd; a[num].le = (a[le].le + a[le].all*a[ri].le)%dd; a[num].ri = (a[ri].ri + a[ri].all*a[le].ri)%dd; a[num].tot = (a[le].tot + a[ri].tot + a[le].ri*a[ri].le)%dd; //a[num].res[1] = Math.min(a[le].res[1],a[ri].res[1]); } static void pushdown(int num,int le,int ri){ } int gcd(int a,int b){ return b==0?a: gcd(b,a%b);} InputStream is;PrintWriter out; void run() throws Exception {is = System.in;out = new PrintWriter(System.out);solve();out.flush();} private byte[] inbuf = new byte[2]; 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 char ncc() {int b;while((b = readByte()) != -1 && !(b >= 32 && b <= 126));return (char)b;} 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 String nline() {int b = skip();StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b);b = readByte(); } return sb.toString();} private char[][] nm(int n, int m) {char[][] a = new char[n][];for (int i = 0; i < n; i++) a[i] = ns(m);return a;} private int[] na(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = ni();return a;} private long[] nal(int n) { long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nl();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 << 3) + (num << 1) + (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();}} void print(Object obj){out.print(obj);} void println(Object obj){out.println(obj);} void println(){out.println();} }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; /** * @author Son-Huy TRAN * */ public class P122A_LuckyDivision { private static boolean isLuckyNumber(int number) { while (number > 0) { int digit = number % 10; if (digit != 4 && digit != 7) { return false; } number /= 10; } return true; } private static boolean isAlmostLuckyNumber(int number) { int max = (int) Math.sqrt(number); int i = 1; while (i <= max) { if (number % i == 0 && (isLuckyNumber(i) || isLuckyNumber(number / i))) { return true; } i++; } return false; } /** * @param args */ public static void main(String[] args) { try { // begin reading inputs InputStreamReader isr = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(isr); // reading inputs int input = Integer.parseInt(reader.readLine()); reader.close(); isr.close(); // end reading inputs boolean result = isAlmostLuckyNumber(input); System.out.println(result ? "YES" : "NO"); } catch (Exception e) { e.printStackTrace(); } } }
constant
122_A. Lucky Division
CODEFORCES
import java.util.Arrays; import java.util.InputMismatchException; import java.io.*; /** * Generated by Contest helper plug-in * Actual solution is at the bottom */ public class Main { public static void main(String[] args) { InputReader in = new StreamInputReader(System.in); PrintWriter out = new PrintWriter(System.out); run(in, out); } public static void run(InputReader in, PrintWriter out) { Solver solver = new TaskB(); solver.solve(1, in, out); Exit.exit(in, out); } } abstract class InputReader { private boolean finished = false; public abstract int read(); 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(); 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; } public void setFinished(boolean finished) { this.finished = finished; } public abstract void close(); } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(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 void close() { try { stream.close(); } catch (IOException ignored) { } } } class Exit { private Exit() { } public static void exit(InputReader in, PrintWriter out) { in.setFinished(true); in.close(); out.close(); } } interface Solver { public void solve(int testNumber, InputReader in, PrintWriter out); } class TaskB implements Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); int m = in.readInt(); int k = in.readInt(); int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = in.readInt(); Arrays.sort(a); if(k>=m) { out.println(0); } else { for(int i=n-1;i>=0;i--) { k += (a[i]-1); if(k>=m) { out.println(n-i); return; } } if(k<m) out.println(-1); } } }
nlogn
257_A. Sockets
CODEFORCES
//package round429; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class C2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); for(int i = 0;i < n;i++){ int v = a[i]; for(int j = 2;j*j <= v;j++){ while(v % (j*j) == 0){ v /= j*j; } } a[i] = v; } Arrays.sort(a); int[] f = new int[n]; int p = 0; for(int i= 0;i < n;i++){ if(i > 0 && a[i] != a[i-1]){ p++; } f[p]++; } f = Arrays.copyOf(f, p+1); int mod = 1000000007; int[][] fif = enumFIF(1000, mod); long[] res = countSameNeighborsSequence(f, fif, mod); long ans = res[0]; for(int v : f){ ans = ans * fif[0][v] % mod; } out.println(ans); } public static int[][] enumFIF(int n, int mod) { int[] f = new int[n + 1]; int[] invf = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; i++) { f[i] = (int) ((long) f[i - 1] * i % mod); } long a = f[n]; long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } invf[n] = (int) (p < 0 ? p + mod : p); for (int i = n - 1; i >= 0; i--) { invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod); } return new int[][] { f, invf }; } public static long[] countSameNeighborsSequence(int[] a, int[][] fif, int mod) { int n = a.length; int bef = a[0]; int aft = a[0]; long[] dp = new long[bef]; dp[bef-1] = 1; for(int u = 1;u < n;u++){ int v = a[u]; aft += v; long[][] ldp = new long[bef][aft]; for(int i = 0;i < dp.length;i++){ ldp[i][0] = dp[i]; } for(int i = 0;i < v;i++){ long[][] ndp = new long[bef][aft]; for(int j = 0;j < bef;j++){ for(int k = 0;j+k < aft;k++){ if(ldp[j][k] == 0)continue; // XX -> XCX if(j > 0){ ndp[j-1][k] += ldp[j][k] * j; ndp[j-1][k] %= mod; } // CC -> CCC // XC -> XCC // #XC = 2*(i-k) ndp[j][k+1] += ldp[j][k] * (2*i-k); ndp[j][k+1] %= mod; // XY -> XCY // #XY = bef+i+1-#XC-#CC-#XX ndp[j][k] += ldp[j][k] * (bef+i+1-j-k-2*(i-k)); ndp[j][k] %= mod; } } ldp = ndp; } dp = new long[aft]; for(int j = 0;j < bef;j++){ for(int k = 0;j+k < aft;k++){ dp[j+k] += ldp[j][k]; } } for(int j = 0;j < aft;j++)dp[j] = dp[j] % mod * fif[1][v] % mod; bef = aft; } return dp; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C2().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
cubic
840_C. On the Bench
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main { private static int REM = 1000000007; private static int dig; private static int[][][] dp = new int[701][701][2]; public static void main(String[] args) { Scanner in = new Scanner(System.in); String X = in.next(); int N = X.length(); int[] P = new int[701]; P[0] = 1; for (int i=1; i<P.length; ++i) { P[i] = (int)((long)P[i-1] * 10 % REM); } int ans = 0; for (int d=1; d<=9; ++d) { //at least d dig = d; for (int[][] array2 : dp) { for (int[] array1 : array2) { Arrays.fill(array1, -1); } } for (int c=1; c<=N; ++c) { //exact count of at least d for (int k=0; k<c; ++k) { ans = (int)((ans + (long)f(0, c, false, X) * P[k]) % REM); } } } System.out.println(ans); } private static int f(int ps, int needed, boolean less, final String X) { if (needed < 0) {return 0;} if (dp[ps][needed][less?0:1] != -1) {return dp[ps][needed][less?0:1];} if (ps == X.length()) { if (needed == 0) {return 1;} return 0; } int dg = X.charAt(ps)-'0'; int ans = 0; for (int d=0; d<=9; ++d) { if (!less && d>dg) {continue;} boolean nless = less || d < dg; ans = (int)((ans + (long)f(ps+1, needed-(d>=dig?1:0), nless, X)) % REM); } dp[ps][needed][less?0:1] = ans; return ans; } }
quadratic
908_G. New Year and Original Order
CODEFORCES
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { int n,a,b; Scanner obj=new Scanner(System.in); n=obj.nextInt(); if(n%4==0){a=n/2;b=n/2;System.out.println(a+" "+b);} else if(n%2==0 && n%4!=0) {a=n/2-1;b=n/2+1;System.out.println(a+" "+b);} else if(n%2!=0) { a=4;b=0; while(b!=1) { b=n-a; if(b%3==0){ System.out.println(a+" "+b);break; } else{a=a+2;} } } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;} public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;} public double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } // |----| /\ | | ----- | // | / / \ | | | | // |--/ /----\ |----| | | // | \ / \ | | | | // | \ / \ | | ----- ------- public static long check(long mid,long x,long y,long n) { long ans=2*mid*mid+2*mid+1; long uleft=Math.max(0,mid-x+1); long dleft=Math.max(0,mid-(n-x)); long lleft=Math.max(0,mid-y+1); long rleft=Math.max(0,mid-(n-y)); ans-=uleft*uleft+dleft*dleft+lleft*lleft+rleft*rleft; ans+=(Math.max(0,mid-(x+y-1))*(Math.max(0,mid-(x+y-1))+1))/2; ans+=(Math.max(0,mid-(x+n-y))*(Math.max(0,mid-(x+n-y))+1))/2; ans+=(Math.max(0,mid-(y+n-x))*(Math.max(0,mid-(y+n-x))+1))/2; ans+=(Math.max(0,mid-(n-x+n-y+1))*(Math.max(0,mid-(n-x+n-y+1))+1))/2; return ans; } public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); long n=sc.l(); long x=sc.l(); long y=sc.l(); long c=sc.l(); long low=0; long high=(long)Math.pow(10,9); while(low<high) { long mid=(low+high)/2; if(check(mid,x,y,n)>=c) high=mid; else low=mid+1; } out.println(low); out.flush(); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.*; import java.util.*; public class Test{ public static void main(String[] args) { Scanner in= new Scanner(System.in); int n=in.nextInt(); if(n%7==0 || n%4==0 || n%47==0 || n%74==0 || n%447==0 || n%474==0 || n%477==0 || n%747==0 || n%774==0){ System.out.println("YES"); }else System.out.println("NO"); } }
constant
122_A. Lucky Division
CODEFORCES
/** * Created with IntelliJ IDEA. * User: brzezinsky * Date: 12/16/12 * Time: 7:44 PM * To change this template use File | Settings | File Templates. */ import java.io.*; import java.util.*; import java.util.StringTokenizer; public class E extends Thread { public E(String inputFileName, String outputFileName) { try { if (inputFileName != null) { this.input = new BufferedReader(new FileReader(inputFileName)); } else { this.input = new BufferedReader(new InputStreamReader(System.in)); } if (outputFileName != null) { this.output = new PrintWriter(outputFileName); } else { this.output = new PrintWriter(System.out); } this.setPriority(Thread.MAX_PRIORITY); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } } private void solve() throws Throwable { long l = nextLong(), r = nextLong(); int []bitL = new int[63]; int []bitR = new int[63]; int szL = doit(l, bitL); int szR = doit(r, bitR); int ret = szR; while (ret >= 0 && bitL[ret] == bitR[ret]) --ret; if (ret < 0) { output.println(0); } else { output.println((1L << (ret + 1)) - 1); } } static final int doit(long q, int []a) { int sz = 0; while (q != 0L) { a[sz++] = (int)(q &1L); q >>= 1; } return sz; } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.close(); } } public static void main(String... args) { new E(null, null).start(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private double nextDouble() throws IOException { return Double.parseDouble(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private String next() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private StringTokenizer tokens; private BufferedReader input; private PrintWriter output; }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class E implements Runnable { public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();} int n, m; char[] str; int[][] occs, cost; int[] dp; public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println(""); //where's my 420???? :( long tot = 0; for(int i = 0; i < 19000; i++) tot += i; System.err.println(tot); n = fs.nextInt(); m = fs.nextInt(); byte[] str = fs.next().getBytes(); int[] occs = new int[1<<m]; for(int i = 0; i < n-1; i++) { int l1 = str[i] - 'a'; int l2 = str[i+1] - 'a'; occs[(1<<l1) | (1<<l2)]++; occs[(1<<l2) | (1<<l1)]++; } //cost[mask][v] = numPairs with v for some all bits on in mask int all = (1<<m)-1; cost = new int[m][1<<m]; for(int i = 0; i < m; i++) { for(int mask = 1; mask < all; mask++) { if(((1<<i)&mask) > 0) continue; int lb = mask & (-mask); int trail = Integer.numberOfTrailingZeros(lb); int nmask = mask ^ lb; cost[i][mask] = cost[i][nmask]+occs[1<<i | 1<<trail]; } } dp = new int[1<<m]; for(int mask = dp.length-2; mask >= 0; mask--) { int addOn = 0; for(int nxt = 0; nxt < m; nxt++) { if(((1<<nxt)&mask) > 0) continue; addOn += cost[nxt][mask]; } int res = oo; for(int nxt = 0; nxt < m; nxt++) { if(((1<<nxt)&mask) > 0) continue; int ret = addOn+dp[mask | (1<<nxt)]; res = min(res, ret); } dp[mask] = res; } System.out.println(dp[0]>>1); out.close(); } int oo = (int)1e9; int min(int a, int b) { if(a < b) return a; return b; } class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.util.*; import java.io.*; public class SameSumBlock { static BufferedReader br; static StringTokenizer tokenizer; public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(); int[] arr = new int[n]; int[] pSum = new int[n]; for(int i = 0; i< n; i++) { arr[i] = nextInt(); if(i != 0) pSum[i] += pSum[i - 1]; pSum[i] += arr[i]; } ArrayList<Interval> sorted = new ArrayList<Interval>(); for(int i = 0; i < n; i++) sorted.add(new Interval(pSum[i],0, i)); for(int i = 1; i < n; i++) { for(int j = i; j < n; j++) { sorted.add(new Interval(pSum[j] - pSum[i - 1], i, j)); } } sorted.sort(null); int i = 0; int max = 0, idx = 0, end = 0; while(i < sorted.size()) { int last = i; int curr = 1; int start = i; sorted.get(i).marked = true; while(i < sorted.size() - 1 && sorted.get(i).val == sorted.get(i + 1).val) { i++; if(sorted.get(i).l > sorted.get(last).r) { sorted.get(i).marked = true; curr++; last = i; } } if(curr > max) { max = curr; idx = start; end = i; } i++; } System.out.println(max); for(int j = idx; j <= end; j++) { if(sorted.get(j).marked) System.out.println(sorted.get(j).l + 1 + " " + (sorted.get(j).r + 1)); } } public static String next() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) throw new IOException(); tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } } class Interval implements Comparable<Interval> { int val, l, r; boolean marked; public Interval(int val, int l, int r) { super(); this.val = val; this.l = l; this.r = r; } @Override public int compareTo(Interval o) { if(val != o.val) return val - o.val; return r - o.r; } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static Reader scan; static PrintWriter pw; static int n,k,left[],right[],arr[]; static long MOD = 1000000007,count[],dp[]; public static void main(String[] args) { new Thread(null,null,"BaZ",1<<25) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { scan = new Reader(); pw = new PrintWriter(System.out,true); StringBuilder sb = new StringBuilder(); n = ni(); k = ni(); int stack[] = new int[1000001]; int top = -1; arr = new int[n]; left = new int[n]; right = new int[n]; for(int i=0;i<n;++i) { arr[i] = ni(); while(top>=0 && arr[stack[top]]<=arr[i]) top--; if(top==-1) left[i] = 0; else left[i] = stack[top]+1; stack[++top] = i; } top = -1; for(int i=n-1;i>=0;--i) { while(top>=0 && arr[stack[top]]<arr[i]) top--; if(top==-1) right[i] = n-1; else right[i] = stack[top]-1; stack[++top] = i; } //pa("left", left); //pa("right", right); dp = new long[n+1]; for(int i=0;i<=n;++i) { if(i<k) continue; dp[i] = dp[i-k+1] + (i-k+1); } count = new long[n]; long ans = 0; for(int i=0;i<n;++i) { int len = right[i]-left[i]+1; int lef = i-left[i]; int rig = right[i]-i; long count = dp[len] - dp[lef] - dp[rig]; if(count>=MOD) count%=MOD; ans += count*arr[i]; if(ans>=MOD) ans%=MOD; } pl(ans); pw.flush(); pw.close(); } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
linear
1037_F. Maximum Reduction
CODEFORCES
import sun.reflect.generics.tree.Tree; import java.io.*; import java.math.BigInteger; import java.net.Inet4Address; import java.util.*; public class l { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static long mod = (int) (1e9 + 7); static int n; static StringBuilder sol; static class pair implements Comparable<pair> { int L,R; public pair( int x,int y) { L=x;R=y; } public int compareTo(pair o) { if (L!=o.L)return L-o.L; return o.R-R; } public String toString(){ return L+" "+R; } } static boolean is; static int [][][]memo; static int[]val,gen; static int dp(int last,int rem,int msk){ if (rem==0)return 1; if (memo[last][rem][msk]!=-1)return memo[last][rem][msk]; int ans =0; for (int i =0;i<n;i++){ if ((msk&1<<i)==0){ if (gen[i]!=last&&val[i]<=rem){ ans+=dp(gen[i],rem-val[i],msk|1<<i); ans%=mod; } } } return memo[last][rem][msk]=ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); //FileWriter f = new FileWriter("C:\\Users\\Ibrahim\\out.txt"); PrintWriter pw = new PrintWriter(System.out); n = sc.nextInt(); int t = sc.nextInt(); gen= new int[n]; val= new int[n]; for (int i =0;i<n;i++){ val[i]=sc.nextInt(); gen[i]=sc.nextInt(); } memo= new int[4][t+1][1<<n]; for (int[][]x:memo)for (int[]a:x)Arrays.fill(a,-1); pw.println(dp(0,t,0)); pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } 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 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 boolean ready() throws IOException { return br.ready(); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
/* ⠀⠀⠀⠀⣠⣶⡾⠏⠉⠙⠳⢦⡀⠀⠀⠀⢠⠞⠉⠙⠲⡀⠀ ⠀⠀⠀⣴⠿⠏⠀⠀⠀⠀⠀⠀⢳⡀⠀⡏⠀⠀Y⠀⠀⢷ ⠀⠀⢠⣟⣋⡀⢀⣀⣀⡀⠀⣀⡀⣧⠀⢸⠀⠀A⠀⠀ ⡇ ⠀⠀⢸⣯⡭⠁⠸⣛⣟⠆⡴⣻⡲⣿⠀⣸⠀⠀S⠀ ⡇ ⠀⠀⣟⣿⡭⠀⠀⠀⠀⠀⢱⠀⠀⣿⠀⢹⠀⠀H⠀⠀ ⡇ ⠀⠀⠙⢿⣯⠄⠀⠀⠀⢀⡀⠀⠀⡿⠀⠀⡇⠀⠀⠀⠀⡼ ⠀⠀⠀⠀⠹⣶⠆⠀⠀⠀⠀⠀⡴⠃⠀⠀⠘⠤⣄⣠⠞⠀ ⠀⠀⠀⠀⠀⢸⣷⡦⢤⡤⢤⣞⣁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⢀⣤⣴⣿⣏⠁⠀⠀⠸⣏⢯⣷⣖⣦⡀⠀⠀⠀⠀⠀⠀ ⢀⣾⣽⣿⣿⣿⣿⠛⢲⣶⣾⢉⡷⣿⣿⠵⣿⠀⠀⠀⠀⠀⠀ ⣼⣿⠍⠉⣿⡭⠉⠙⢺⣇⣼⡏⠀⠀⠀⣄⢸⠀⠀⠀⠀⠀⠀ ⣿⣿⣧⣀⣿………⣀⣰⣏⣘⣆⣀⠀⠀ */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; // System.out is a PrintStream // import java.util.Arrays; import java.util.ArrayDeque; // import java.util.ArrayList; // import java.util.Collections; // for sorting ArrayList mainly // import java.util.HashMap; // import java.util.HashSet; // import java.util.Random; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { FastScanner scn = new FastScanner(); PrintWriter out = new PrintWriter(System.out); for (int tc = scn.nextInt(); tc > 0; tc--) { int N = scn.nextInt(); int[] arr = new int[N]; for (int i = 0; i < N; i++) { arr[i] = scn.nextInt(); } StringBuilder[] ans = new StringBuilder[N]; ans[0] = new StringBuilder("1"); ArrayDeque<Integer> st = new ArrayDeque<>(); st.addLast(0); for (int i = 1; i < N; i++) { // System.out.println(st); ans[i] = new StringBuilder(); if (arr[i] == 1) { st.addLast(i); ans[i].append(ans[i - 1].toString() + ".1"); } else { while (arr[st.getLast()] != arr[i] - 1) { st.removeLast(); } int pos = st.removeLast(); String[] prev = ans[pos].toString().split("[.]"); for (int j = 0, sz = prev.length - 1; j < sz; j++) { ans[i].append(prev[j] + "."); } ans[i].append(arr[i] + ""); st.addLast(i); } } for (StringBuilder str : ans) { out.println(str); } } out.close(); } private static int gcd(int num1, int num2) { int temp = 0; while (num2 != 0) { temp = num1; num1 = num2; num2 = temp % num2; } return num1; } private static int lcm(int num1, int num2) { return (int)((1L * num1 * num2) / gcd(num1, num2)); } private static void ruffleSort(int[] arr) { // int N = arr.length; // Random rand = new Random(); // for (int i = 0; i < N; i++) { // int oi = rand.nextInt(N), temp = arr[i]; // arr[i] = arr[oi]; // arr[oi] = temp; // } // Arrays.sort(arr); } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { this.br = new BufferedReader(new InputStreamReader(System.in)); this.st = new StringTokenizer(""); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException err) { err.printStackTrace(); } } return st.nextToken(); } String nextLine() { if (st.hasMoreTokens()) { return st.nextToken("").trim(); } try { return br.readLine().trim(); } catch (IOException err) { err.printStackTrace(); } return ""; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.awt.Point; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class ProblemA { static ArrayList<Point2> houses = new ArrayList<Point2>(); public static void main(String[] args) { ProblemA a = new ProblemA(); Scanner in = new Scanner(System.in); while(in.hasNextInt()){ int n = in.nextInt(); double t = in.nextDouble(); for (int k=0;k<n;k++){ houses.add(a.new Point2(in.nextDouble(),in.nextDouble())); } Collections.sort(houses); int ans = 2; for (int k=0;k<n-1;k++){ Point2 cur = houses.get(k); Point2 next = houses.get(k+1); double dist = (next.x - next.y/2) - (cur.x + cur.y/2); if (dist == t) ans ++; if (dist > t ) ans+=2; } System.out.println(ans); } } public class Point2 implements Comparable<Point2>{ public double x; public double y; public Point2(double one, double two){ x = one; y = two; } public int compareTo(Point2 other){ if (x - other.x > 0) return 1; if (x - other.x < 0) return -1; return 0; } public String toString(){ return "x:" + x + " y:" + y; } } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class A { public void realMain() throws Exception { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in), 1000000); String in = fin.readLine(); String[] ar = in.split(" "); int n = Integer.parseInt(ar[0]); int[] a = new int[n]; for(int i = 0; i < n; i++) { int ret = 0; boolean dig = false; for (int ch = 0; (ch = fin.read()) != -1; ) { if (ch >= '0' && ch <= '9') { dig = true; ret = ret * 10 + ch - '0'; } else if (dig) break; } a[i] = ret; } int ret = 0; Arrays.sort(a); boolean[] colored = new boolean[n]; for(int i = 0; i < n; i++) { if(!colored[i]) { ret++; for(int j = i; j < n; j++) { if(a[j] % a[i] == 0) { colored[j] = true; } } } } System.out.println(ret); } public static void main(String[] args) throws Exception { A a = new A(); a.realMain(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author kessido */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskG solver = new TaskG(); solver.solve(1, in, out); out.close(); } static class TaskG { static int[][] g; static int n; static int[] a; static int[][] edges; static long[] dp; static long[] dpPathToRootWithDetours; static int time = 0; static int[] appearance; static int[] firstAppearance; static int[] depth; public static void dfs(int i, int parE) { firstAppearance[i] = time; appearance[time++] = i; dp[i] = a[i]; for (int eIndex : g[i]) { if (eIndex == parE) continue; int child = i ^ edges[eIndex][0] ^ edges[eIndex][1]; dfs(child, eIndex); appearance[time++] = i; dp[i] += Math.max(dp[child] - edges[eIndex][2] * 2, 0); } } public static void dfs2(int i, int parE) { if (i == 0) { dpPathToRootWithDetours[i] = dp[i]; } else { int par = i ^ edges[parE][0] ^ edges[parE][1]; depth[i] = depth[par] + 1; dpPathToRootWithDetours[i] = dpPathToRootWithDetours[par] - Math.max(0, dp[i] - edges[parE][2] * 2); dpPathToRootWithDetours[i] -= edges[parE][2]; dpPathToRootWithDetours[i] += dp[i]; long myPathWeight = Math.max(dp[i] - edges[parE][2] * 2, 0); long change = dp[par] - myPathWeight - edges[parE][2] * 2; change = Math.max(change, 0); dp[i] += change; } for (int eIndex : g[i]) { if (eIndex == parE) continue; dfs2(i ^ edges[eIndex][0] ^ edges[eIndex][1], eIndex); } } public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.NextInt(); int q = in.NextInt(); a = in.NextIntArray(n); edges = new int[n - 1][3]; { long[] count = new long[n]; for (int i = 0; i < n - 1; i++) { int u = in.NextInt() - 1; int v = in.NextInt() - 1; int w = in.NextInt(); edges[i][0] = u; edges[i][1] = v; edges[i][2] = w; count[u]++; count[v]++; } g = new int[n][]; for (int i = 0; i < n; i++) { g[i] = new int[(int) count[i]]; } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < 2; j++) { g[edges[i][j]][(int) --count[edges[i][j]]] = i; } } } dp = new long[n]; dpPathToRootWithDetours = new long[n]; depth = new int[n]; firstAppearance = new int[n]; appearance = new int[(n - 1) * 2 + 1]; dfs(0, -1); dfs2(0, -1); GraphLowestCommonAncestor.LCA lca = GraphLowestCommonAncestor.createLCA(appearance, firstAppearance, depth); firstAppearance = null; depth = null; appearance = null; edges = null; g = null; for (int i = 0; i < q; i++) { int u = in.NextInt() - 1; int v = in.NextInt() - 1; int lcaI = lca.getLCA(u, v); long res = dpPathToRootWithDetours[u] + dpPathToRootWithDetours[v] - 2 * dpPathToRootWithDetours[lcaI] + dp[lcaI]; out.println(res); } } } static class MinRangeSparseTable implements ISearchInRange { private final int[][] sparseTables; private final long[] array; private final boolean reverseOrdered; public MinRangeSparseTable(long[] array, boolean reverseOrdered) { this.reverseOrdered = reverseOrdered; this.array = array; int LCALength = IntegerExtension.getNumberOfBits(array.length); sparseTables = new int[LCALength][]; sparseTables[0] = new int[array.length]; for (int i = 0; i < array.length; i++) { sparseTables[0][i] = i; } for (int i = 1; i < LCALength; i++) { int size = 1 << i; int jumpSize = 1 << (i - 1); sparseTables[i] = new int[sparseTables[0].length - size + 1]; for (int j = 0; j < sparseTables[i].length; j++) { sparseTables[i][j] = min(sparseTables[i - 1][j], sparseTables[i - 1][j + jumpSize]); } } } private int min(int a, int b) { return ((array[a] < array[b]) ^ reverseOrdered) ? a : b; } public Pair<Long, Long> queryIndexValueInRange(long l, long r) { int size = (int) (r - l + 1); int LCAIndex = IntegerExtension.getNumberOfBits(size) - 1; int sizeNeeded = 1 << LCAIndex; int res = min(sparseTables[LCAIndex][(int) l], sparseTables[LCAIndex][(int) (r - sizeNeeded + 1)]); return new Pair<>((long) res, array[res]); } public MinRangeSparseTable(long[] array) { this(array, false); } } static class GraphLowestCommonAncestor { public static GraphLowestCommonAncestor.LCA createLCA(int[] appearances, final int[] firstAppearance, final int[] depth) { return new GraphLowestCommonAncestor.LCA_MinRangeSparseTable(appearances, firstAppearance, depth); } public interface LCA { int getLCA(int a, int b); } private static class LCA_MinRangeSparseTable implements GraphLowestCommonAncestor.LCA { private final MinRangeSparseTable minRangeSparseTable; private final int[] firstAppearance; private final int[] indexToNode; public LCA_MinRangeSparseTable(int[] appearances, final int[] firstAppearance, final int[] depth) { this.firstAppearance = firstAppearance; this.indexToNode = appearances; long[] depthOrder = new long[appearances.length]; for (int i = 0; i < depthOrder.length; i++) { depthOrder[i] = depth[appearances[i]]; } minRangeSparseTable = new MinRangeSparseTable(depthOrder); } public int getLCA(int a, int b) { a = firstAppearance[a]; b = firstAppearance[b]; int l = Math.min(a, b), r = Math.max(a, b); return indexToNode[(int) (long) minRangeSparseTable.queryIndexValueInRange(l, r).first]; } } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,"); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int NextInt() { return Integer.parseInt(next()); } public int[] NextIntArray(int n) { return NextIntArray(n, 0); } public int[] NextIntArray(int n, int offset) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = NextInt() + offset; } return a; } } static interface ISearchInRange { } static class Pair<T1, T2> { public T1 first; public T2 second; public Pair(T1 f, T2 s) { first = f; second = s; } } static class IntegerExtension { public static int getNumberOfBits(long i) { return 64 - Long.numberOfLeadingZeros(i); } } }
nlogn
1000_G. Two-Paths
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class A { static final Scanner sc = new Scanner(System.in); void run() { int n = sc.nextInt(); int[] xs = new int[n]; for(int i = 0; i < n; i++) { xs[i] = sc.nextInt(); } Arrays.sort(xs); xs[n-1] = xs[n-1] == 1 ? 2 : 1; Arrays.sort(xs); for(int i = 0; i < n; i++) System.out.print(xs[i] + " "); } public static void main(String[] args) { new A().run(); } }
nlogn
135_A. Replacement
CODEFORCES
import static java.lang.Math.*; public class C { public C () { int N = sc.nextInt(); int R = sc.nextInt(); int [] X = sc.nextInts(); double [] res = new double [N]; for (int i : rep(N)) { res[i] = R; for (int j : rep(i)) { int D = abs(X[i] - X[j]); if (D <= 2*R) { double H = sqrt(4.0*R*R - 1.0*D*D); res [i] = max(res[i], res[j] + H); } } } exit(res); } private static int [] rep(int N) { return rep(0, N); } private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } //////////////////////////////////////////////////////////////////////////////////// private final static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); } private static class IOUtils { public static class MyScanner { public String next() { newLine(); return line[index++]; } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { return split(nextLine()); } public int [] nextInts() { String [] L = nextStrings(); int [] res = new int [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim(String delim, Object o, Object ... A) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : A) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static void start() { if (t == 0) t = millis(); } private static void append(StringBuilder b, Object o, String delim) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) append(b, java.lang.reflect.Array.get(o, i), delim); } else if (o instanceof Iterable<?>) for (Object p : (Iterable<?>) o) append(b, p, delim); else { if (o instanceof Double) o = new java.text.DecimalFormat("#.############").format(o); b.append(delim).append(o); } } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print(Object o, Object ... A) { pw.println(build(o, A)); } private static void err(Object o, Object ... A) { System.err.println(build(o, A)); } private static void exit() { IOUtils.pw.close(); System.out.flush(); err("------------------"); err(IOUtils.time()); System.exit(0); } private static long t; private static long millis() { return System.currentTimeMillis(); } private static String time() { return "Time: " + (millis() - t) / 1000.0; } } public static void main (String[] args) { new C(); IOUtils.exit(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import static java.lang.Math.*; import java.io.*; import java.math.*; import java.util.*; public class Solution implements Runnable { public static void main(String... strings) throws InterruptedException { new Thread(new Solution()).start(); } BufferedReader in; PrintWriter out; StringTokenizer st; String next() throws Exception { if (st == null || !st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } @Override public void run() { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); solve(); } catch (Exception e) { throw new RuntimeException(e); } finally { out.close(); } } int n, m, k, xor = 0; boolean[][] used; HashSet<Long> [] set; void solve() throws Exception { n = nextInt(); m = nextInt(); k = nextInt(); used = new boolean[n][m]; set = new HashSet[2]; for(int i = 0; i < 2; set[i++] = new HashSet<Long>()); for(int i = 0; i < k; i++){ int x = nextInt()-1, y = nextInt()-1; used[x][y] = true; set[0].add(10000L*x + y); } for (;;xor ^= 1){ set[xor^1].clear(); int ansx = -1, ansy = -1; for (long i : set[xor]){ int x = (int)(i/10000), y = (int)(i%10000); if (ansx < 0){ ansx = x+1; ansy = y+1; } add(x+1, y); add(x-1, y); add(x, y+1); add(x, y-1); } if (set[xor^1].size() == 0){ out.println(ansx + " " + ansy); break; } } } public void add(int x, int y){ if (!( x >= 0 && y >= 0 && x < n && y < m && !used[x][y])) return; set[xor^1].add(10000L*x + y); used[x][y] = true; } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class Main20 { static ArrayList<Integer> primes = new ArrayList<Integer>(); static boolean[] prime = new boolean[1001]; public static void gen(){ Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int i = 2; i < 1001; i++) { if (prime[i]){ primes.add(i); for (int j = i*2; j < 1001; j+=i) prime[j] = false; } } } public static boolean isVowel(char c){ Character r = Character.toLowerCase(c); return (r == 'e' || r == 'a' || r == 'i' || r == 'o' || r == 'u'|| r == 'y'); } public static void main(String[] args) throws IOException { Scanner s = new Scanner(new InputStreamReader(System.in)); String str = s.next(); int x; int max= 0; for (int i = 0; i < str.length()-1; i++) { for (int j = i+1; j < str.length(); j++) { x = str.indexOf(str.substring(i,j),i+1) ; if (x != -1){ if (j-i > max) max = j-i; } } } System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
//created by Whiplash99 import java.io.*; import java.util.*; public class D { private static ArrayDeque<Integer>[][] edge; private static long[][] dp[],w1,w2; private static int N,M,K; private static void answer() { StringBuilder sb=new StringBuilder(); for(int i=0;i<N;i++) { for (int j = 0; j < M; j++) sb.append(dp[i][j][K]).append(" "); sb.append("\n"); } System.out.println(sb); } private static long solve(int i, int j, int pos) { if(pos==0) return 0; if(dp[i][j][pos]!=-1) return dp[i][j][pos]; long a=Long.MAX_VALUE/100; if(i-1>=0) a=Math.min(a,solve(i-1,j,pos-1)+w2[i-1][j]); if(i<N-1) a=Math.min(a,solve(i+1,j,pos-1)+w2[i][j]); if(j-1>=0) a=Math.min(a,solve(i,j-1,pos-1)+w1[i][j-1]); if(j<M-1) a=Math.min(a,solve(i,j+1,pos-1)+w1[i][j]); return dp[i][j][pos]=a; } public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i; String[] s=br.readLine().trim().split(" "); N=Integer.parseInt(s[0]); M=Integer.parseInt(s[1]); K=Integer.parseInt(s[2]); edge=new ArrayDeque[N][M]; for(i=0;i<N;i++) { for(int j=0;j<M;j++) edge[i][j]=new ArrayDeque<>(); } w1=new long[N][M-1]; w2=new long[N-1][M]; dp=new long[N][M][K/2+1]; for(i=0;i<N;i++) { s=br.readLine().trim().split(" "); for(int j=0;j<M-1;j++) w1[i][j]=Integer.parseInt(s[j])*2L; } for(i=0;i<N-1;i++) { s=br.readLine().trim().split(" "); for(int j=0;j<M;j++) w2[i][j]=Integer.parseInt(s[j])*2L; } for(i=0;i<N;i++) { for(int j=0;j<M;j++) Arrays.fill(dp[i][j],-1); } if(K%2==1) { K/=2; answer(); System.exit(0); } K/=2; for(i=0;i<N;i++) { for(int j=0;j<M;j++) solve(i,j,K); } answer(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; public class CF8C { FastScanner in; PrintWriter out; int[] x, y; int[] av; int[][] d = new int[25][25]; int dist(int v, int u) { if (u == v) return 0; return (d[v][u] == 0 ? d[v][u] = d[u][v] = (x[v] - x[u]) * (x[v] - x[u]) + (y[v] - y[u]) * (y[v] - y[u]) : d[v][u]); } void add(int x) { av[++av[0]] = x; } int size() { return av[0]; } int get(int i) { return av[i + 1]; } int N = 24; int[] dp = new int[(1 << N)]; int[] dpFrom = new int[1 << N]; void solve() { int x1 = in.nextInt(); int y1 = in.nextInt(); int n = in.nextInt(); x = new int[n + 1]; y = new int[n + 1]; for (int i = 1; i <= n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } x[0] = x1; y[0] = y1; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; av = new int[n + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) dist(i, j); for (int st = 0; st < (1 << n); st++) { if (dp[st] == Integer.MAX_VALUE) continue; av[0] = 0; for (int i = 0; i < n; i++) if ((st & (1 << i)) == 0) add(i); if (av[0] == 0) continue; for (int i = 0; i < 1; i++) for (int j = i + 1; j < av[0]; j++) { int val = dp[st] + d[get(i) + 1][0] + d[get(j) + 1][0] + d[get(i) + 1][get(j) + 1]; if (dp[st | (1 << get(i)) | (1 << get(j))] > val) { dp[st | (1 << get(i)) | (1 << get(j))] = val; dpFrom[st | (1 << get(i)) | (1 << get(j))] = st; } } for (int i = 0; i < 1; i++) { int val = dp[st] + d[get(i) + 1][0] * 2; if (dp[st | (1 << get(i))] > val) { dp[st | (1 << get(i))] = val; dpFrom[st | (1 << get(i))] = st; } } } out.println(dp[(1 << n) - 1]); int nowSt = (1 << n) - 1; ArrayList<Integer> ans = new ArrayList<Integer>(); ans.add(0); while (nowSt != 0) { int newSt = dpFrom[nowSt]; for (int i = 0; i < n; i++) if (((1 << i) & nowSt) == (1 << i)) if (((1 << i) & newSt) == 0) ans.add(i + 1); ans.add(0); nowSt = newSt; } for (int i = ans.size() - 1; i >= 0; i--) out.print(ans.get(i) + " "); } void run() { try { in = new FastScanner(new File("object.in")); out = new PrintWriter(new File("object.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { new CF8C().runIO(); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author madis */ public class Spreadsheet { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); in.nextLine(); for (int i = 0; i < N; i++) { String str = in.nextLine(); if (str.indexOf("R") == 0 && str.indexOf("R") + 1 < str.indexOf("C") && isNum(str.charAt(1))) { int row = Integer.parseInt(str.substring(str.indexOf("R") + 1, str.indexOf("C"))); int col = Integer.parseInt(str.substring(str.indexOf("C") + 1)); System.out.println(convertRC(row, col)); } else { String row = ""; int j = 0; while (str.charAt(j) >= 'A' && str.charAt(j) <= 'Z') { row += str.charAt(j); j++; } int num = Integer.parseInt(str.substring(j)); System.out.println(convertAB(row, num)); } } } static String convertAB(String str, int num) { String result = ""; int col = 0; for (int i = 0; i < str.length(); i++) { col += (int)Math.pow(26, (str.length()) - (i + 1)) * (str.charAt(i) - 'A' + 1); } result += "R" + num; result += "C" + col; return result; } static String convertRC(int row, int column) { String result = ""; while (column > 0) { int index = column % 26; char c; if (index == 0) { c = 'Z'; column = column - 26; } else { c = (char) ('A' + index - 1); column = column - index; } result += c; column = column / 26; } String res = ""; for (int i = 0; i < result.length(); i++) { res += result.charAt(result.length() - (i + 1)); } res += row; return res; } static boolean isNum(char x){ return x>'0'&&x<='9'; } }
linear
1_B. Spreadsheets
CODEFORCES
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.*; /** * * @author N-AssassiN */ public class Main { private static BufferedReader reader; private static BufferedWriter out; private static StringTokenizer tokenizer; //private final static String filename = "filename"; private static void init(InputStream input, OutputStream output) { reader = new BufferedReader(new InputStreamReader(input)); out = new BufferedWriter(new OutputStreamWriter(output)); //reader = new BufferedReader(new FileReader(filename + ".in")); //out = new BufferedWriter(new FileWriter(filename + ".out")); tokenizer = new StringTokenizer(""); } private static String nextLine() throws IOException { return reader.readLine(); } private static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(nextLine()); } return tokenizer.nextToken(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { init(System.in, System.out); int n = nextInt(); //long startTime = System.currentTimeMillis(); if (n > 0) { out.write(n + "\n"); } else { String s = n + ""; String s2 = s.substring(0, s.length() - 1); String s3 = s.substring(0, s.length() - 2) + s.charAt(s.length() - 1); int a = Integer.parseInt(s2); int b = Integer.parseInt(s3); int ans = Math.max(a, b); out.write(ans + "\n"); } //long runTime = System.currentTimeMillis() - startTime; //out.write(runTime + "\n"); out.flush(); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); if (n % 2 == 0) { System.out.println((n - 4) + " " + (n - (n - 4))); } else { System.out.println((n - 9) + " " + (n - (n - 9))); } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; public class D { int[][] fast(int n, int m){ int[][] ans = new int[2][n * m]; int c = 0; for (int left = 1, right = m; left < right; left++, right--) { for (int l = 1, r = n; l <= n && r >= 1; l++, r--) { ans[0][c] = l; ans[1][c++] = left; ans[0][c] = r; ans[1][c++] = right; } } if (m % 2 == 1) { int x = m/2 + 1; for(int l = 1, r = n;l < r;l++, r--){ ans[0][c] = l; ans[1][c++] = x; ans[0][c] = r; ans[1][c++] = x; if(n % 2 == 1 && l + 2 == r){ ans[0][c] = l+1; ans[1][c++] = x; } } } if(n == 1 && m % 2 == 1){ ans[0][c] = 1; ans[1][c] = m/2 + 1; } return ans; } void stress(){ for(int i = 3;i<=5;i++){ for(int j = 2;j<=5;j++){ int[][] ans = new int[2][]; try{ ans = fast(i, j); }catch(Exception e){ out.println("ошибка"); out.print(i + " " + j); return; } boolean[][] check = new boolean[i][j]; for(int c = 0;c<ans[0].length;c++){ int x = ans[0][c] - 1; int y = ans[1][c] - 1; check[x][y] = true; } for(int c = 0;c<i;c++){ for(int q = 0;q<j;q++){ if(!check[c][q]){ out.println(i + " " + j); out.println("точки"); for(int w = 0;w<ans[0].length;w++){ out.println(ans[0][w] + " " + ans[1][w]); } return; } } } HashSet<String> set = new HashSet<>(); for(int c = 1;c<ans[0].length;c++){ int x = ans[0][c] - ans[0][c- 1]; int y = ans[1][c] - ans[1][c - 1]; set.add(x + " " + y); } if(set.size() < i * j - 1){ out.println(i + " " + j); out.println("вектора"); for(int w = 0;w<ans[0].length;w++){ out.println(ans[0][w] + " " + ans[1][w]); } return; } } } } void normal(){ int n =readInt(); int m = readInt(); int[][] ans = fast(n, m); for(int i = 0;i<ans[0].length;i++){ out.println(ans[0][i] + " " + ans[1][i]); } } boolean stress = false; void solve(){ if(stress) stress(); else normal(); } public static void main(String[] args) { new D().run(); } void run(){ init(); solve(); out.close(); } BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init(){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } String readLine(){ try{ return in.readLine(); }catch(Exception ex){ throw new RuntimeException(ex); } } String readString(){ while(!tok.hasMoreTokens()){ String nextLine = readLine(); if(nextLine == null) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt(){ return Integer.parseInt(readString()); } long readLong(){ return Long.parseLong(readString()); } double readDouble(){ return Double.parseDouble(readString()); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class b { public static void main(String[] rgs) { Scanner s=new Scanner(System.in); int n=s.nextInt(); long[] arr=new long[n]; for(int i=0;i<n;i++) { arr[i]=s.nextLong(); } HashMap<Long,ArrayList<pair>> map=new HashMap<>(); ArrayList<pair> list=new ArrayList<>(); for(int i=0;i<n;i++) { long sum=0; for(int j=i;j<n;j++) { sum=sum+arr[j]; pair ob=new pair(i,j); if(map.containsKey(sum)) { ArrayList p=map.get(sum); p.add(ob); map.put(sum, p); }else { ArrayList<pair> listt=new ArrayList<>(); listt.add(ob); map.put(sum,listt); } } } long in=-1; int max=0; for(Map.Entry<Long, ArrayList<pair>> entry:map.entrySet()) { int l=1; ArrayList<pair> p=entry.getValue(); Collections.sort(p,new comp()); int now=p.get(0).end; for(int j=0;j<p.size();j++) { if(p.get(j).st>now) { l++; now=p.get(j).end; } } if(l>max) { max=l; in=entry.getKey(); } } System.out.println(max); ArrayList<pair> d=map.get(in); int now=-1; for(int j=0;j<d.size();j++) { if(d.get(j).st>now) { System.out.println((d.get(j).st+1)+" "+(d.get(j).end+1)); now=d.get(j).end; } } } } class pair{ //long val; int st; int end; public pair(int st,int end) { //this.val=val; this.st=st; this.end=end; } } class comp implements Comparator<pair>{ public int compare(pair h,pair j) { if(h.end<j.end) { return -1; }else if(h.end==j.end) { if(h.st<j.st) { return 1; }else if(h.st==j.st) { return 0; }else { return -1; } }else { return 1; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; import java.util.Map.Entry; import java.io.*; public class A{ public static void main(String args[]){ FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); boolean change = false; if(a > b){ int t = a; a = b; b = t; change = true; } boolean[] inb = new boolean[n]; int[] numbers = new int[n]; TreeMap<Integer, Integer> num = new TreeMap<Integer, Integer>(); for(int i = 0; i < n; i++){ num.put(in.nextInt(), i); } boolean hasAns = true; while(!num.isEmpty()){ Entry<Integer, Integer> last = num.lastEntry(); int key = last.getKey(); if(num.containsKey(a - key)){ num.remove(key); num.remove(a - key); } else if(num.containsKey(b - key)){ inb[num.get(key)] = true; inb[num.get(b - key)] = true; num.remove(key); num.remove(b - key); } else{ hasAns = false; break; } } if(hasAns){ out.println("YES"); for(int i = 0; i < n && !change; i++){ if(inb[i]){ out.print("1"); } else{ out.print("0"); } if(i != n - 1){ out.print(" "); } } for(int i = 0; i < n && change; i++){ if(inb[i]){ out.print("0"); } else{ out.print("1"); } if(i != n - 1){ out.print(" "); } } } else{ out.println("NO"); } out.close(); } static class FastScanner{ private BufferedReader reader; private StringTokenizer tokenizer; public FastScanner(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine(){ try{ return reader.readLine(); } catch(IOException e){ e.printStackTrace(); return null; } } public String next(){ while(tokenizer == null || !tokenizer.hasMoreTokens()){ try{ tokenizer = new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
linear
468_B. Two Sets
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main { public static String taskName = ""; public class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int r = in.nextInt(); int[] x = new int[n]; for(int i = 0; i < n; i++) x[i] = in.nextInt(); double[] y = new double[n]; for(int i = 0; i < n; i++) { y[i] = r; for(int j = 0; j < i; j++) { int dx = Math.abs(x[i] - x[j]); if(dx <= 2 * r) y[i] = Math.max(y[i], y[j] + Math.abs(Math.sqrt(4 * r * r - dx * dx))); } System.out.print(y[i] + " "); } System.out.println(); } } public static void main(String[] args) throws FileNotFoundException { if(!taskName.isEmpty()) { System.setIn(new BufferedInputStream(new FileInputStream(taskName + ".in"))); System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(taskName + ".out")))); } InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Main main = new Main(); main.run(in, out); out.close(); } public void run(InputReader in, PrintWriter out) { Task solver = new Task(); solver.solve(1, in, out); } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public double nextShort() { return Short.parseShort(next()); } public double nextByte() { return Byte.parseByte(next()); } public double nextFloat() { return Float.parseFloat(next()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // Scanner scan = new Scanner(System.in); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] a = new int[n]; for(int i = 0 ; i <n;i++) a[i] = Integer.parseInt(st.nextToken()); int l = 0, r = 0; int[] t = new int[100001]; int kk = 0; int min = 1 << 25 , ll =-1 , rr = -1; while(r < n) { int x = a[r++]; t[x]++; if(t[x] == 1) kk++; while(r < n && kk < k) { x = a[r++]; t[x]++; if(t[x] == 1) kk++; } while(kk == k && l < r) { x = a[l]; if(t[x] == 1) break; t[x]--; l++; } if(kk == k) { int m = r-l+1; if(m < min) { ll = l+1; rr = r; min = m; } } } System.out.println(ll +" "+rr); } }
linear
224_B. Array
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class StringRepeat { static Scanner in = new Scanner( new BufferedReader( new InputStreamReader( System.in ) ) ); public static void main( String[] args ) { String s = in.next(); int n = s.length(), ans = 0; for( int i = 0; i < n; i++ ) for( int j = i+1; j < n; j++ ) { int l = 0; while( j+l<n && s.charAt(i+l)==s.charAt(j+l) ) l++; ans = Math.max( ans, l ); } System.out.println( ans ); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; import java.math.BigInteger; import java.util.Map.Entry; import static java.lang.Math.*; public class C extends PrintWriter { final long mod = 1_000_000_007; long pow(long n, long p) { long r = 1; while (p > 0) { if (p % 2 == 1) { r = (r * n) % mod; } n = (n * n) % mod; p /= 2; } return r; } long solve(long n, long k) { if (k == 0) { return (2 * n) % mod; } if (n == 0) { return 0; } long m = pow(2, k); long a = 2; a = (a * n) % mod; a = (a * m) % mod; long b = (m + mod - 1) % mod; return ((a - b + mod) % mod); } void run() { long n = nextLong(); long k = nextLong(); println(solve(n, k)); } boolean skip() { while (hasNext()) { next(); } return true; } int[][] nextMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) matrix[i][j] = nextInt(); return matrix; } String next() { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } int[] nextArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return reader.readLine(); } catch (IOException err) { return null; } } public C(OutputStream outputStream) { super(outputStream); } static BufferedReader reader; static StringTokenizer tokenizer = new StringTokenizer(""); static Random rnd = new Random(); static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; C solution = new C(System.out); if (OJ) { reader = new BufferedReader(new InputStreamReader(System.in)); solution.run(); } else { reader = new BufferedReader(new FileReader(new File(C.class.getName() + ".txt"))); long timeout = System.currentTimeMillis(); while (solution.hasNext()) { solution.run(); solution.println(); solution.println("----------------------------------"); } solution.println("time: " + (System.currentTimeMillis() - timeout)); } solution.close(); reader.close(); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.Scanner; /** * Write a description of class lukno here. * * @author (your name) * @version (a version number or a date) */ public class lukno { public static void main (String args[]) { Scanner i= new Scanner(System.in); int n,p; n=i.nextInt(); int t=n; while(n!=0) { p=n%10; if(p!=4||p!=7) { if(t%7==0||t%4==0||t%47==0||t%74==0||t%447==0||t%477==0||t%474==0) System.out.print("YES"); else System.out.print("NO"); break;} else System.out.print("NO"); n=(n/10); } } }
constant
122_A. Lucky Division
CODEFORCES
import java.util.*; import java.io.*; public class submitting { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); StringTokenizer st = new StringTokenizer(sc.nextLine()); long n = Integer.parseInt(st.nextToken()); long k = Integer.parseInt(st.nextToken()); long put = n / 2; long lower = 0; long upper = n; while (put * (put + 1) / 2 - (n - put) != k) { if (put * (put + 1) / 2 - (n - put) > k) { upper = put - 1; put = (lower + upper) / 2; } else { lower = put + 1; put = (lower + upper) / 2; } } System.out.println(n - put); sc.close(); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class C { public static void main(String[] args) { MyScanner in = new MyScanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int r = in.nextInt(); double[] y = new double[n]; int[] x = new int[n]; for(int i=0;i<n;++i){ x[i] = in.nextInt(); double bestY = r; for(int j=0;j<i;++j){ if(Math.abs(x[i]-x[j]) <= 2*r){ double ny = y[j] + Math.sqrt(4*r*r - (x[i]-x[j])*(x[i]-x[j])); if(ny > bestY){ bestY = ny; } } } y[i] = bestY; } for(int i=0;i<n;++i){ out.println(y[i]); } out.close(); } // -----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // -------------------------------------------------------- }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); boolean[][] graph = new boolean[n][n]; for(int i = 0; i < m; i++) { int from = in.nextInt() - 1; int to = in.nextInt() - 1; graph[from][to] = true; graph[to][from] = true; } int max = 1 << n; long[][] dp = new long[max][n]; for(int mask = 1; mask < max; mask++) { for(int i = 0; i < n; i++) { int countMask = Integer.bitCount(mask); boolean existSubSeti = (mask & (1 << i)) > 0; if(countMask == 1 && existSubSeti) { dp[mask][i] = 1; } else if(countMask > 1 && existSubSeti) { int mask1 = mask ^ (1 << i); for(int j = 0; j < n; j++) { if(graph[j][i] && i != firstMask(mask, n)) { dp[mask][i] += dp[mask1][j]; } } } } } long counter = 0; for(int mask = 1; mask < max; mask++) { for(int i = 0; i < n; i++) { if(Integer.bitCount(mask) >= 3 && graph[firstMask(mask, n)][i]) { counter += dp[mask][i]; } } } System.out.println(counter / 2); in.close(); } public static int firstMask(int mask, int n) { for(int i = 0; i < n; i++) { if((mask & (1 << i)) > 0) return i; } return -1; } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import javax.script.*; public class Noldbach { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); boolean[] sieve=new boolean[1001]; sieve[2]=false; ArrayList<Integer> primes=new ArrayList<Integer>(); for(int x=2;x<1001;x++) if(!sieve[x]) { primes.add(x); for(int y=x;y<1001;y+=x) sieve[y]=true; } int sum=0; for(int x=2;x<=n;x++) { if(primes.contains(x)) { int need=x-1; for(int y=0;y<primes.size()-1;y++) { if(primes.get(y)+primes.get(y+1)==need) { sum++; break; } } } if(sum==k)break; } if(sum==k)System.out.println("YES"); else System.out.println("NO"); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int a[]=new int[n]; for(int i=0; i<n; i++) a[i]=in.nextInt(); long no=0; for(int i=0; i<n-1; i++) { for(int j=i+1; j<n; j++) { if(a[i]>a[j]) no++; } } // System.out.println(no); no%=2; int m=in.nextInt(); int te; String te2="odd",te1="even"; for(int i=0; i<m; i++) { te=in.nextInt()-in.nextInt(); te=-te+1; // System.out.println(te); if((te*(te-1)/2)%2==0) { // System.out.println("HOLA"+no); if(no==0) System.out.println("even"); else System.out.println("odd"); } else { no=(no+1)%2; if(no==0) System.out.println("even"); else System.out.println("odd"); } } } }
quadratic
911_D. Inversion Counting
CODEFORCES
//package ; import java.io.*; import java.util.*; public class D { static int dp(int i,int start,int msk) { if(Integer.bitCount(msk)==n) return s_e[i][start]; if(dp[i][start][msk]!=-1) return dp[i][start][msk]; int max=0; for(int k=0;k<n;k++) { int min=Integer.MAX_VALUE; if((msk & (1<<k)) == 0 ) { min=diff[i][k]; min=Math.min(min, dp(k,start,msk | (1<<k))); max=Math.max(max, min); } } return dp[i][start][msk]=max; } static int n,m,a[][],dp[][][],diff[][],s_e[][]; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter pw = new PrintWriter(System.out); n=sc.nextInt(); m=sc.nextInt(); a=new int[n][m]; diff=new int[n][n]; s_e=new int[n][n]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=sc.nextInt(); dp=new int[n][n][70000]; int ans=0; for(int i=0;i<n;i++) for(int j=0;j<n;j++) { Arrays.fill(dp[i][j], -1); diff[i][j]=Integer.MAX_VALUE; s_e[i][j]=Integer.MAX_VALUE; for(int k=0;k<m-1;k++) { diff[i][j]=Math.min(Math.abs(a[i][k]-a[j][k]), diff[i][j]); s_e[i][j]=Math.min(Math.abs(a[i][k]-a[j][k+1]), s_e[i][j]); } diff[i][j]=Math.min(Math.abs(a[i][m-1]-a[j][m-1]), diff[i][j]); } for(int i=0;i<n;i++) ans=Math.max(ans, dp(i,i,1<<i)); pw.print(ans); pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } 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()); } String nextLine() throws IOException { return br.readLine(); } boolean hasnext() throws IOException { return br.ready(); } } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.util.*; import java.io.*; public class D { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static void solve() { in = new InputReader(System.in); out = new PrintWriter(System.out); int t = 1; while(t-- > 0) { int n = in.nextInt(); int m = in.nextInt(); int K = in.nextInt(); long[][] x = new long[n][]; for(int i = 0; i < n; i++) { x[i] = in.nextLongArray(m - 1); } long[][] y = new long[n - 1][]; for(int i = 0; i < n - 1; i++) { y[i] = in.nextLongArray(m); } if(K % 2 != 0) { for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { out.print("-1 "); } out.println(); } continue; } K /= 2; long[][][] dp = new long[K + 1][n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { for(int k = 1; k <= K; k++) { dp[k][i][j] = Integer.MAX_VALUE; } } } for(int k = 1; k <= K; k++) { for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(i + 1 < n) { dp[k][i][j] = Math.min(dp[k][i][j], dp[k - 1][i + 1][j] + 2 * y[i][j]); } if(i - 1 >= 0) { dp[k][i][j] = Math.min(dp[k][i][j], dp[k - 1][i - 1][j] + 2 * y[i - 1][j]); } if(j + 1 < m) { dp[k][i][j] = Math.min(dp[k][i][j], dp[k - 1][i][j + 1] + 2 * x[i][j]); } if(j - 1 >= 0) { dp[k][i][j] = Math.min(dp[k][i][j], dp[k - 1][i][j - 1] + 2 * x[i][j - 1]); } } } } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { out.print(dp[K][i][j] + " "); } out.println(); } } out.close(); } public static void main(String[] args) { new Thread(null ,new Runnable(){ public void run() { try{ solve(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } static int[][] graph(int from[], int to[], int n) { int g[][] = new int[n][]; int cnt[] = new int[n]; for (int i = 0; i < from.length; i++) { cnt[from[i]]++; cnt[to[i]]++; } for (int i = 0; i < n; i++) { g[i] = new int[cnt[i]]; } Arrays.fill(cnt, 0); for (int i = 0; i < from.length; i++) { g[from[i]][cnt[from[i]]++] = to[i]; g[to[i]][cnt[to[i]]++] = from[i]; } return g; } static class Pair implements Comparable<Pair>{ int x,y,z; Pair (int x,int y,int z){ this.x=x; this.y=y; this.z=z; } public int compareTo(Pair o) { if (this.x == o.x) return Integer.compare(this.y,o.y); return Integer.compare(this.x,o.x); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Integer(x).hashCode() * 31 + new Integer(y).hashCode(); } @Override public String toString() { return x + " " + y; } } static String rev(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return sb.toString(); } static long gcd(long x, long y) { if (y == 0) { return x; } else { return gcd(y, x % y); } } static int gcd(int x, int y) { if (y == 0) { return x; } else { return gcd(y, x % y); } } static int abs(int a, int b) { return (int) Math.abs(a - b); } static long abs(long a, long b) { return (long) Math.abs(a - b); } static int max(int a, int b) { if (a > b) { return a; } else { return b; } } static int min(int a, int b) { if (a > b) { return b; } else { return a; } } static long max(long a, long b) { if (a > b) { return a; } else { return b; } } static long min(long a, long b) { if (a > b) { return b; } else { return a; } } static long pow(long n, long p, long m) { long result = 1; if (p == 0) { return 1; } while (p != 0) { if (p % 2 == 1) { result *= n; } if (result >= m) { result %= m; } p >>= 1; n *= n; if (n >= m) { n %= m; } } return result; } static long pow(long n, long p) { long result = 1; if (p == 0) { return 1; } if (p == 1) { return n; } while (p != 0) { if (p % 2 == 1) { result *= n; } p >>= 1; n *= n; } return result; } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.StringTokenizer; import java.util.function.Function; public class D { public static void main(String[] args) throws IOException { try (Input input = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { long[] s = new long[40]; for (int i = 1; i < s.length; i++) { s[i] = 1 + 4 * s[i - 1]; if (i >= 32) { s[i] = Long.MAX_VALUE; } } Function<Integer, Long> getS = (i) -> (i < s.length) ? s[i] : Long.MAX_VALUE; int t = input.nextInt(); testCase: for (int tt = 0; tt < t; tt++) { int n = input.nextInt(); long k = input.nextLong(); long kk = 1; BigInteger maxDivisions = BigInteger.ZERO; for (int division = 1; division <= n; division++) { long needToDivide = (1L << division) - 1; if (needToDivide > k) { writer.println("NO"); continue testCase; } k -= needToDivide; maxDivisions = maxDivisions.add(BigInteger.valueOf(kk).multiply(BigInteger.valueOf(getS.apply(n - division)))); if (maxDivisions.compareTo(BigInteger.valueOf(k)) >= 0) { writer.println("YES " + (n - division)); continue testCase; } kk += (1L << division + 1); } writer.println("NO"); } } } interface Input extends Closeable { String next() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.util.*; import java.io.*; public class _G14 { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = 1; while (t-- > 0) { int n = sc.nextInt(); mod = sc.nextLong(); long res = 0; initFac(n + 7); long [] tpow = new long[n + 7]; long [][] combo = new long[n + 6][n + 6]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= i; j++) { if (j == 0 || j == i) combo[i][j] = 1; else combo[i][j] = (combo[i - 1][j - 1] + combo[i - 1][j]) % mod; } } tpow[0] = 1; for (int i = 1; i <= n + 6; i++) tpow[i] = (tpow[i - 1] * 2) % mod; // dp[i][auto] long [][] dp = new long[n + 1][n + 1]; for (int i = 1; i <= n; i++) dp[i][0] = tpow[i - 1]; for (int i = 3; i <= n; i++) { for (int auto = 1; auto <= n / 2; auto++) { if (!check(i, auto)) continue; long total = 0; for (int j = i - 2; j >= 1; j--) { if (!check(j, auto - 1)) break; int len = i - j - 1; long ways = tpow[len - 1]; int picked = j - (auto - 1); long interleave = combo[len + picked][picked]; ways = (ways * interleave) % mod; ways = (ways * dp[j][auto - 1]) % mod; total = (total + ways) % mod; } dp[i][auto] = total; if (i == n) res = (res + dp[i][auto]) % mod; } } res = (res + dp[n][0]) % mod; out.println(res); } out.close(); } static boolean check(int n, int auto) { int rem = n - auto; int seg = auto + 1; return rem >= seg; } static long[] fac; static long mod; static void initFac(long n) { fac = new long[(int)n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) { fac[i] = (fac[i - 1] * i) % mod; } } static long nck(int n, int k) { if (n < k) return 0; long den = inv((int) (fac[k] * fac[n - k] % mod)); return fac[n] * den % mod; } static long pow(long b, long e) { long ans = 1; while (e > 0) { if (e % 2 == 1) ans = ans * b % mod; e >>= 1; b = b * b % mod; } return ans; } static long inv(long x) { return pow(x, mod - 2); } static void sort(int[] a) { ArrayList<Integer> q = new ArrayList<>(); for (int i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } static void sort(long[] a) { ArrayList<Long> q = new ArrayList<>(); for (long i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class A { private void solve() throws IOException { int n = nextInt(); int r = n; n *= 2; n -= (0.5*r); System.out.println(n); } public static void main(String[] args) { new A().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[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = nextInt(); } return res; } long[] readLongArray(int size) throws IOException { long[] res = new long[size]; for (int i = 0; i < size; i++) { res[i] = nextLong(); } return res; } double[] readDoubleArray(int size) throws IOException { double[] res = new double[size]; for (int i = 0; i < size; i++) { res[i] = nextDouble(); } return res; } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
constant
84_A. Toy Army
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class DD { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); long k=Long.parseLong(br.readLine()); long ans=9*(int)Math.pow(10,0); int c=0; long start=0; while(k>ans) { c++; start=ans; ans+=9*(long)Math.pow(10,c)*(c+1); } long ms=(k-start-1)%(c+1); long a=(long)Math.pow(10,c)+(k-start-1)/(c+1); System.out.println((a+"").charAt((int)ms)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class TaxiDriversAndLyft2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long n = scanner.nextLong(); long m = scanner.nextLong(); long[] people = new long[(int) (n+m)]; int[] taxiDrivers = new int[(int) (n+m)]; for(int i = 0;i< (n+m); i++) { people[i] = scanner.nextLong(); } for(int i = 0;i< (n+m); i++) { taxiDrivers[i] = scanner.nextInt(); } int lastTaxiDriverIndex = -1; long[] riderCountArray = new long[(int) (m)]; long[] a1 = new long[(int)n]; long[] b1 = new long[(int)m]; int j=0, k=0; for(int i = 0;i< (n+m); i++) { if(taxiDrivers[i] == 0) { a1[j] = people[i]; j++; } else { b1[k] = people[i]; k++; } } int l = 0, q=0; for(int i=0;i<j;i++) { while ((l<m-1 && m>1) && Math.abs(a1[i] - b1[l]) > Math.abs(a1[i] - b1[l+1])) { l++; } riderCountArray[l]++; } for(int i = 0;i< (m); i++) { System.out.print(riderCountArray[i]+" "); } } }
linear
1075_B. Taxi drivers and Lyft
CODEFORCES
import java.io.*; import java.util.*; /** __ __ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ `-` / _____ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class C{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 10000001; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) // marking smallest prime factor for every // number to be itself. spf[i] = i; // separately marking spf for every even // number as 2 for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j<MAXN; j+=i) // marking spf[j] if it is not // previously marked if (spf[j]==j) spf[j] = i; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } InputReader in; PrintWriter out; public void solve(InputReader in, PrintWriter out) { this.in=in; this.out=out; int t=in.nextInt(); while(t-->0){ int n= in.nextInt(); int[] arr= new int[n]; for(int i=0;i<n;i++) arr[i]= in.nextInt(); int[] cur= new int[n]; int idx=0; for(int num: arr){ if(idx<n && num==cur[idx]+1){ cur[idx]=num; printRes(cur, idx); idx++; } else{ for(int i=idx;i>=0;i--){ if(i<n && num!=cur[i]+1) cur[i]=0; else{ cur[i]=num; printRes(cur,i); i++; idx=i; break; } } } } } } public void printRes(int[] cur, int idx){ for(int i=0;i<idx;i++) out.print(cur[i]+"."); out.println(cur[idx]); } public boolean ok(char[] s){ boolean allEqual = true; boolean Alternate = true; for (int i = 0; i < s.length - 1; i++){ if (s[i]!=s[i+1]){ allEqual = false; } else{ Alternate = false; } } if (s[0] == '0' || s[s.length-1] == '0'){ return false; } return allEqual || Alternate; } // private int cal() public static boolean nextPermutation(char[] array){ boolean hasNext = false; int i; for(i = array.length-2; i >= 0; i--){ if(array[i] < array[i+1]){ hasNext = true; break; } } if(!hasNext){// If all elements are arranged from largest to smallest, it means the largest string return false; } // Find backward from the subscript of i + 1 (must be monotonically decreasing), find a smallest element in the set larger than array [i] int j; for(j = i+1; j < array.length; j++){ if(array[j] <= array[i]){ break; } } j--; // Swap these two elements, and then reverse all the elements in i + 1 and later (i + 1, array.length) swap(array, i, j); reverse(array, i+1, array.length); return true; } public static void swap(char[] array, int i, int j) { char temp =array[i]; array[i] = array[j]; array[j] =temp; } public static void reverse(char[] array, int start, int end){ for(int i = start, j = end-1; i < j; i++, j--) { swap(array, i, j); } } public static class compareL implements Comparator<Tuple>{ @Override public int compare(Tuple t1, Tuple t2) { return t2.l - t1.l; } } public static class compareR implements Comparator<Tuple>{ @Override public int compare(Tuple t1, Tuple t2) { return t1.r - t2.r; } } public static class Tuple{ public int l, r, w; public Tuple(int l, int r,int w){ this.l = l; this.r= r; this.w =w; } } public static class Range implements Comparable<Range>{ public int l, r; List<Integer> data; int weight; public Range(int l, int r, List<Integer> data){ this.data = data; this.l = l; this.r =r; this.weight = (int)1e9; } @Override public int compareTo(Range o) { return this.l - o.l; } } public int _gcd(int a, int b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ return this.x-o.x; } } static class Pair implements Comparable<Pair>{ public int x; public 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; } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.awt.Point; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class sdffsdf { public static void main(String[] args) { try{ File file = new File("input.txt"); Scanner sc = new Scanner(file); String s = sc.nextLine(); String[] seperatedd = s.split(" "); int x = Integer.parseInt(seperatedd[0]); int y = Integer.parseInt(seperatedd[1]); int[][] grid = new int[x][y]; for(int i = 0; i < x; i++) { for(int j = 0; j < y; j++) { grid[i][j] = 0; } } s = sc.nextLine(); int z = Integer.parseInt(s); LinkedList<Point> BFS = new LinkedList<Point>(); s = sc.nextLine(); String[] seperated = s.split(" "); for(int i = 0; i < seperated.length; i = i + 2) { Point temp = new Point(); temp.x = Integer.parseInt(seperated[i])-1; temp.y = Integer.parseInt(seperated[i+1])-1; grid[temp.x][temp.y] = 1; BFS.addLast(temp); } while(!BFS.isEmpty()) { Point temp = new Point(); temp = BFS.removeFirst(); int k = temp.x; int l = temp.y; if(!(l+1 >= y || grid[k][l+1] == 1)) { Point temp1 = new Point(); temp1.x = k; temp1.y = l+1; grid[temp1.x][temp1.y] = 1; BFS.addLast(temp1); } if(!(k+1 >= x || grid[k+1][l] == 1)) { Point temp1 = new Point(); temp1.x = k+1; temp1.y = l; grid[temp1.x][temp1.y] = 1; BFS.addLast(temp1); } if(!(l-1 < 0 || grid[k][l-1] == 1)) { Point temp1 = new Point(); temp1.x = k; temp1.y = l-1; grid[temp1.x][temp1.y] = 1; BFS.addLast(temp1); } if(!(k-1 < 0 || grid[k-1][l] == 1)) { Point temp1 = new Point(); temp1.x = k-1; temp1.y = l; grid[temp1.x][temp1.y] = 1; BFS.addLast(temp1); } if(BFS.isEmpty()) { try { File fil = new File("output.txt"); PrintWriter out = new PrintWriter(fil); int v1 = (int)temp.getX() + 1; int v2 = (int)temp.getY() + 1; out.println(v1 + " " + v2); out.close(); } catch (Exception e) {} } } } catch (Exception e) { System.out.println("nbvnb"); } } }
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.StringTokenizer; public class Bag implements Runnable { private void solve() throws IOException { int xs = nextInt(); int ys = nextInt(); int n = nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = nextInt(); y[i] = nextInt(); } int[][] pair = new int[n][n]; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]); int[] single = new int[n]; for (int i = 0; i < n; ++i) { single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys)); } int[] best = new int[1 << n]; int[] prev = new int[1 << n]; for (int set = 1; set < (1 << n); ++set) { int i; for (i = 0; i < n; ++i) if ((set & (1 << i)) != 0) break; best[set] = best[set ^ (1 << i)] + single[i]; prev[set] = i + 1; for (int j = i + 1; j < n; ++j) if ((set & (1 << j)) != 0) { int cur = best[set ^ (1 << i) ^ (1 << j)] + pair[i][j]; if (cur < best[set]) { best[set] = cur; prev[set] = (i + 1) * 100 + (j + 1); } } } writer.println(best[(1 << n) - 1]); int now = (1 << n) - 1; writer.print("0"); while (now > 0) { int what = prev[now]; int wa = what % 100 - 1; int wb = what / 100 - 1; if (wa >= 0) { writer.print(" "); writer.print(wa + 1); now ^= 1 << wa; } if (wb >= 0) { writer.print(" "); writer.print(wb + 1); now ^= 1 << wb; } writer.print(" "); writer.print("0"); } writer.println(); } public static void main(String[] args) { new Bag().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
8_C. Looking for Order
CODEFORCES
import java.util.*; public class Main { public static int n, m; public static int[][] arr; public static class Item implements Comparable<Item> { int i, x; public Item(int i, int x) { this.i = i; this.x = x; } public int compareTo(Item other) { if (x == other.x) { return i - other.i; } return other.x - x; } } public static int calc(int[] cols, int k, String mask) { if (k == cols.length) { int res = 0; for (int i = 0; i < n; i++) { int max = 0; for (int j = 0; j < cols.length; j++) { int shift = mask.charAt(j) - '0'; max = Math.max(max, arr[(shift + i) % n][cols[j]]); } res += max; } return res; } else { int best = 0; for (int i = 0; i < n; i++) { best = Math.max(best, calc(cols, k + 1, mask + i)); } return best; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { n = in.nextInt(); m = in.nextInt(); arr = new int[n][m]; for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { arr[j][k] = in.nextInt(); } } Item[] max = new Item[m]; for (int j = 0; j < m; j++) { max[j] = new Item(j, 0); for (int k = 0; k < n; k++) { max[j].x = Math.max(max[j].x, arr[k][j]); } } Arrays.sort(max); int[] cols = new int[Math.min(n, m)]; for (int j = 0; j < cols.length; j++) { cols[j] = max[j].i; } System.out.println(calc(cols, 0, "")); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.io.*; public class Main { boolean[] b; int[] r; ArrayList<ArrayList<Integer>> q; public void dfs(int u, int p) { for (int i = 0; i < q.get(u).size(); i++) { int v = q.get(u).get(i); if (v != p) { r[v] = r[u] + 1; if (b[u]) { b[v] = b[u]; } dfs(v, u); } } } public void solve() throws IOException { long n = nextLong(); long s = nextLong(); long t = 0; if(s + 200 < n){ t = n - s - 200; } for(long i = s; i <= Math.min(s + 200,n); i++){ long p = 0; long u = i; while (u > 0){ p += u % 10; u /= 10; } if(i - p >= s){ t++; } } out.print(t); } BufferedReader br; StringTokenizer sc; PrintWriter out; public String nextToken() throws IOException { while (sc == null || !sc.hasMoreTokens()) { try { sc = new StringTokenizer(br.readLine()); } catch (Exception e) { return null; } } return sc.nextToken(); } public Integer nextInt() throws IOException { return Integer.parseInt(nextToken()); } public Long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { try { Locale.setDefault(Locale.US); } catch (Exception e) { } new Main().run(); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // br = new BufferedReader(new FileReader("lesson.in")); // out = new PrintWriter(new File("lesson.out")); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.DataInputStream; import java.io.InputStream; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; public class B { public static void main(String[] args) throws Exception { Parserdoubt2333 s = new Parserdoubt2333(System.in); int n = s.nextInt(); int k = s.nextInt(); int a[] = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = s.nextInt(); } TreeMap<Integer, Integer> tree = new TreeMap<Integer,Integer>(); int left = 0; int right = 0; for (right = 0; right < a.length; right++) { if(tree.containsKey(a[right])) tree.put(a[right], tree.get(a[right]) + 1); else tree.put(a[right],1); if(tree.size() == k) break; } if(tree.size() < k){ System.out.println("-1 -1"); return ; } // System.out.println(right); for (left = 0; left < a.length; left++) { int val = tree.get(a[left]); val--; if(val > 0) tree.put(a[left],val); if(val == 0) break; } left++; right++; System.out.println(left + " "+right); } } class Parserdoubt2333 { final private int BUFFER_SIZE = 1 << 18; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parserdoubt2333(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws Exception { StringBuffer sb=new StringBuffer(""); byte c = read(); while (c <= ' ') c = read(); do { sb.append((char)c); c=read(); }while(c>' '); return sb.toString(); } public char nextChar() throws Exception { byte c=read(); while(c<=' ') c= read(); return (char)c; } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
linear
224_B. Array
CODEFORCES
import static java.lang.Math.*; import static java.util.Arrays.*; import java.io.*; import java.util.*; public class Main { static boolean LOCAL = false;//System.getSecurityManager() == null; Scanner sc = new Scanner(System.in); void run() { char[] cs = sc.nextLine().toCharArray(); int res = 0; for (int s1 = 0; s1 < cs.length; s1++) { for (int s2 = s1 + 1; s2 < cs.length; s2++) { int len = 0; while (s2 + len < cs.length && cs[s1 + len] == cs[s2 + len]) { len++; } res = max(res, len); } } System.out.println(res); } class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } void eat(String s) { st = new StringTokenizer(s); } String nextLine() { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } String next() { hasNext(); return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } void debug(Object...os) { System.err.println(deepToString(os)); } public static void main(String[] args) { if (LOCAL) { try { System.setIn(new FileInputStream("in.txt")); } catch (Throwable e) { LOCAL = false; } } if (!LOCAL) { try { Locale.setDefault(Locale.US); System.setOut(new PrintStream(new BufferedOutputStream(System.out))); } catch (Throwable e) { } } new Main().run(); System.out.flush(); } }
cubic
23_A. You're Given a String...
CODEFORCES
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class ACMIND { static FastReader scan; static PrintWriter pw; static long MOD = 1_000_000_007; static long INF = 1_000_000_000_000_000_000L; static long inf = 2_000_000_000; public static void main(String[] args) { new Thread(null,null,"BaZ",1<<25) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static int n, g[], t[], T; static int dp[][]; static void solve() throws IOException { scan = new FastReader(); pw = new PrintWriter(System.out,true); StringBuilder fast = new StringBuilder(); n = ni(); T = ni(); g = new int[n]; t = new int[n]; for(int i=0;i<n;++i) { t[i] = ni(); g[i] = ni(); } int MAX = (1<<n); dp = new int[MAX][4]; for(int i=0;i<MAX;++i) { for(int j=0;j<4;++j) { dp[i][j] = -1; } } pl(f((1<<n)-1,0)); pw.flush(); pw.close(); } static int f(int mask, int prev) { if(dp[mask][prev]!=-1) { return dp[mask][prev]; } int left = T; for(int i=0;i<n;++i) { if((mask&(1<<i))==0) { left-=t[i]; } } if(left==0) { return 1; } int cnt = 0; for(int i=0;i<n;++i) { if((mask&(1<<i))!=0) { if(g[i]!=prev && left>=t[i]) { cnt+=f(mask^(1<<i), g[i]); if(cnt>=MOD) { cnt-=MOD; } } } } return dp[mask][prev] = cnt; } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static class FastReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastReader(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[1000000]; 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(); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/13/11 * Time: 6:10 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.io.IOException; public class DarkAssembly extends Thread { public DarkAssembly() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } class Senator { int loyalty; int level; public Senator(int level, int loyalty) { this.level = level; this.loyalty = loyalty; } } private static double doIt(Senator[] senators, int A) { double probability = .0; for (int mask = 0; mask < (1 << senators.length); ++mask) { int sum = A; double current = 1.0; for (int i = 0; i < senators.length; ++i) { if ((mask & (1 << i)) != 0) { current *= .01 * Math.min(senators[i].loyalty, 100); } else { current *= .01 * (100 - Math.min(senators[i].loyalty, 100)); sum += senators[i].level; } } if (getOnes(mask) > senators.length / 2) { probability += current; } else { probability += current * (double)A / sum; } } return probability; } private static double go(Senator []senators, int candies, int A, int current) { if (current == senators.length) { return doIt(senators, A); } else { double result = Double.MIN_VALUE; if (candies > 0) { senators[current].loyalty += 10; result = Math.max(result, go(senators, candies - 1, A, current)); senators[current].loyalty -= 10; } result = Math.max(result, go(senators, candies, A, current + 1)); return result; } } static int getOnes(int mask) { int result = 0; while (mask != 0) { mask &= mask - 1; ++result; } return result; } public void run() { try { int n = nextInt(); int k = nextInt(); int A = nextInt(); Senator[] senators = new Senator[n]; for (int i = 0; i < n; ++i) { senators[i] = new Senator(nextInt(), nextInt()); } output.printf("%.10f", go(senators, k, A, 0)); output.flush(); output.close(); } catch (Throwable e) { System.err.println(e.getMessage()); System.err.println(Arrays.deepToString(e.getStackTrace())); } } public static void main(String[] args) { new DarkAssembly().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n = scan.nextLong(); long k = scan.nextLong(); long D = 9 + 4 * (2 * k + 2 * n); long y = (- 3 + (long)Math.sqrt(D)) / 2; System.out.println(n - y); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.*; import java.util.*; public class LuckyDivision { public LuckyDivision(Scanner in) { int n; n = in.nextInt(); if ( (n % 4 == 0) || (n % 7 == 0) || (n % 44 == 0) || (n % 47 == 0) || (n % 74 == 0) || (n % 77 == 0) || (n % 444 == 0) || (n % 447 == 0) || (n % 474 == 0) || (n % 477 == 0) || (n % 744 == 0) || (n % 747 == 0) || (n % 774 == 0) || (n % 777 == 0) ) System.out.printf("YES%n"); else System.out.printf("NO%n"); } public static void main(String[] args) { new LuckyDivision(new Scanner(System.in)); } }
constant
122_A. Lucky Division
CODEFORCES
import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("input.txt"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("output.txt"); } catch (IOException e) { throw new RuntimeException(e); } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int[][] or; int n; int m; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); int k = in.nextInt(); ArrayList<Point> arr1 = new ArrayList<>(); ArrayList<Point> arr2 = new ArrayList<>(); for (int i = 0; i < k; i++) { arr1.add(new Point(in.nextInt(), in.nextInt())); } or = new int[n + 1][m + 1]; for (int i = 0; i < k; i++) { or[arr1.get(i).x][arr1.get(i).y] = -1; } Point lastValue = arr1.get(0); while (arr1.size() > 0 || arr2.size() > 0) { for (Point p : arr1) { if (valid(new Point(p.x - 1, p.y))) { arr2.add(new Point(p.x - 1, p.y)); } if (valid(new Point(p.x + 1, p.y))) { arr2.add(new Point(p.x + 1, p.y)); } if (valid(new Point(p.x, p.y - 1))) { arr2.add(new Point(p.x, p.y - 1)); } if (valid(new Point(p.x, p.y + 1))) { arr2.add(new Point(p.x, p.y + 1)); } } arr1.clear(); if (arr2.size() > 0) { lastValue = arr2.get(0); } for (Point p : arr2) { if (valid(new Point(p.x - 1, p.y))) { arr1.add(new Point(p.x - 1, p.y)); } if (valid(new Point(p.x + 1, p.y))) { arr1.add(new Point(p.x + 1, p.y)); } if (valid(new Point(p.x, p.y - 1))) { arr1.add(new Point(p.x, p.y - 1)); } if (valid(new Point(p.x, p.y + 1))) { arr1.add(new Point(p.x, p.y + 1)); } } arr2.clear(); if (arr1.size() > 0) { lastValue = arr1.get(0); } } out.println(lastValue.x + " " + lastValue.y); } boolean valid(Point p) { if ((p.x < 1 || p.x > n) || (p.y < 1 || p.y > m) || or[p.x][p.y] == -1) { return false; } or[p.x][p.y] = -1; return true; } class Point { int x; int y; public Point(int a, int b) { x = a; y = b; } } } 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()); } } }
cubic
35_C. Fire Again
CODEFORCES
import java.awt.*; import java.math.*; import java.util.regex.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.lang.Integer.parseInt; import static java.util.AbstractMap.*; import static java.lang.System.*; import static java.lang.Math.*; import java.awt.geom.*; import java.util.*; import java.text.*; import java.io.*; public class A { public static void main(String[] args) throws Exception { boolean submit = true; Scanner sc = submit ? new Scanner(System.in) : new Scanner(new File("A.in")); while(sc.hasNext()) { int n = sc.nextInt(), k = sc.nextInt(); boolean p[] = sieveOfEratosthenes(1001); ArrayList<Integer> nolds = new ArrayList<Integer>(); for(int i = 0, prev = 0; i < p.length; i++) { if(p[i]) { nolds.add(prev+i + 1); prev = i; } } //System.out.println(nolds); int c = 0; for(int i : nolds) if(i >= 2 && i <= n && p[i]) c++; System.out.println(c >= k ? "YES" : "NO"); } } //prime[i] = true iff i is prime, prime[0] = prime[1] = false and i can be from 0 to n (both inclusive) static boolean[] sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n+1]; fill(prime, 2, n, true); for(int i = 2; i <= n; i++) if(prime[i]) for(int j = i*i; j <= n; j+=i) //check for i*i overflow prime[j] = false; return prime; } }
linear
17_A. Noldbach problem
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.util.PriorityQueue; public class Main { static PrintWriter out; static InputReader ir; static void solve() { int t = ir.nextInt(); while (t-- > 0) { int n = ir.nextInt(); int m = ir.nextInt(); int[][] a = new int[n][]; for (int i = 0; i < n; i++) { a[i] = ir.nextIntArray(m); } int[][][] comx = new int[n + 1][m][2]; for (int i = 0; i < m; i++) { int[] b = new int[n]; for (int j = 0; j < n; j++) { b[j] = a[j][i]; } Arrays.sort(b); for (int j = 0; j < n; j++) { comx[j + 1][i][0] = comx[j][i][0] + b[n - 1 - j]; comx[j + 1][i][1] = i; } } int[][][] org = new int[n + 1][m][2]; for (int i = 0; i <= n; i++) for (int j = 0; j < m; j++) { for (int k = 0; k < 2; k++) { org[i][j][k] = comx[i][j][k]; } } for (int i = 1; i <= n; i++) Arrays.sort(comx[i], new Comparator<int[]>() { public int compare(int[] A, int[] B) { return A[0] - B[0]; } }); // tr(org); // tr(comx); if (n == 1) { out.println(comx[1][m - 1][0]); } else if (n == 2) { out.println(Math.max(comx[2][m - 1][0], m >= 2 ? comx[1][m - 1][0] + comx[1][m - 2][0] : 0)); } else if (n == 3) { int res = Math.max(comx[3][m - 1][0], m >= 3 ? comx[1][m - 1][0] + comx[1][m - 2][0] + comx[1][m - 3][0] : 0); if (m >= 2) { for (int i = 0; i < m; i++) { int p = comx[2][i][0]; int ma = 0; for (int j = 0; j < m; j++) { if (comx[2][i][1] == j) continue; ma = Math.max(org[1][j][0], ma); } res = Math.max(res, p + ma); } } out.println(res); } else { int res = Math.max(comx[4][m - 1][0], m >= 4 ? comx[1][m - 1][0] + comx[1][m - 2][0] + comx[1][m - 3][0] + comx[1][m - 4][0] : 0); if (m >= 2) { for (int i = 0; i < m; i++) { int p = comx[3][i][0]; int ma = 0; for (int j = 0; j < m; j++) { if (comx[3][i][1] == j) continue; ma = Math.max(org[1][j][0], ma); } res = Math.max(res, p + ma); } } if (m >= 3) { for (int i = 0; i < m; i++) { int p = comx[2][i][0]; PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); for (int j = 0; j < m; j++) { if (comx[2][i][1] == j) continue; pq.add(org[1][j][0]); } res = Math.max(res, p + pq.poll() + pq.poll()); } } if (m >= 2) { for (int i = 0; i < m; i++) { int p = 0; for (int j = 0; j < 4; j++) { p = Math.max(p, a[j][i] + a[(j + 1) % 4][i]); } int ma = 0; for (int j = 0; j < m; j++) { if (i == j) continue; for (int k = 0; k < 4; k++) { ma = Math.max(ma, a[k][j] + a[(k + 1) % 4][j]); } } res = Math.max(res, p + ma); } for (int i = 0; i < m; i++) { int p = 0; for (int j = 0; j < 4; j++) { p = Math.max(p, a[j][i] + a[(j + 2) % 4][i]); } int ma = 0; for (int j = 0; j < m; j++) { if (i == j) continue; for (int k = 0; k < 4; k++) { ma = Math.max(ma, a[k][j] + a[(k + 2) % 4][j]); } } res = Math.max(res, p + ma); } } out.println(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
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Main { protected static final double EPS = 1e-11; private static StreamTokenizer in; private static Scanner ins; private static PrintWriter out; protected static final Double[] BAD = new Double[]{null, null}; private boolean[][] layouts; private int c; private int b; private int a; private String word; public static void main(String[] args) { try { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); ins = new Scanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); try { if (System.getProperty("xDx") != null) { in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt"))); ins = new Scanner(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } } catch (Exception e) { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); ins = new Scanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); } new Main().run(); } catch (Throwable e) { // e.printStackTrace(); throw new RuntimeException(e); } finally { out.close(); } } private int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } private long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } private double nextDouble() throws IOException { in.nextToken(); return in.nval; } private String nextString() throws IOException { in.nextToken(); return in.sval; } private char nextChar() throws IOException { in.nextToken(); return (char) in.ttype; } private void run() throws Exception { /*int t = nextInt(); for (int i = 0; i < t; i++) { out.printf(Locale.US, "Case #%d: %d\n", i + 1, solve()); }*/ solve(); } private void solve() throws IOException { int n = ins.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = ins.nextInt(); } Map<Long, Integer> map = new HashMap<>(); BigInteger res = BigInteger.ZERO; long sum = 0; long amount = 0; for (int i = n - 1; i >= 0; i--) { long cur = a[i]; Pair same = getZeroAmount(cur, map); res = res.add(BigInteger.valueOf((sum - same.sum) - cur * (amount - same.amount))); amount++; sum += cur; map.put(cur, map.getOrDefault(cur, 0) + 1); } out.println(res); } class Pair { long amount; long sum; public Pair(long amount, long sum) { this.amount = amount; this.sum = sum; } } private Pair getZeroAmount(long cur, Map<Long, Integer> map) { long amount = 0; long sum = 0; for (long i = cur - 1; i <= cur + 1; i++) { long amountI = map.getOrDefault(i, 0); amount += amountI; sum += amountI * i; } return new Pair(amount, sum); } private List<Integer> iterate(List<Integer> a) { ArrayList<Integer> b = new ArrayList<>(); int prev = -1; for (int x : a) { if (x == prev) { b.add(x); } else { prev = x; } } return b; } private long gcd(long a, long b) { while (a > 0 && b > 0) { long k = a % b; a = b; b = k; } return a | b; } }
nlogn
903_D. Almost Difference
CODEFORCES
/* * Author- Priyam Vora * BTech 2nd Year DAIICT */ import java.awt.Checkbox; import java.awt.Point; import java.io.*; import java.math.*; import java.util.*; import java.util.Map.Entry; import javax.print.attribute.SetOfIntegerSyntax; public class Main{ private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; private static long count = 0,mod=1000000007; // private static TreeSet<Integer> ts=new TreeSet[200000]; public final static int INF = (int) 1E9; public static void main(String[] args) { InputReader(System.in); pw = new PrintWriter(System.out); new Thread(null ,new Runnable(){ public void run(){ try{ solve(); pw.close(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } public static void test(){ int t=nextInt(); while(t-->0){ solve(); } } public static long pow(long n, long p,long mod) { if(p==0) return 1; if(p==1) return n%mod; if(p%2==0){ long temp=pow(n, p/2,mod); return (temp*temp)%mod; }else{ long temp=pow(n,p/2,mod); temp=(temp*temp)%mod; return(temp*n)%mod; } } public static long pow(long n, long p) { if(p==0) return 1; if(p==1) return n; if(p%2==0){ long temp=pow(n, p/2); return (temp*temp); }else{ long temp=pow(n,p/2); temp=(temp*temp); return(temp*n); } } public static void Merge(long a[],int p,int r){ if(p<r){ int q = (p+r)/2; Merge(a,p,q); Merge(a,q+1,r); Merge_Array(a,p,q,r); } } public static void Merge_Array(long a[],int p,int q,int r){ long b[] = new long[q-p+1]; long c[] = new long[r-q]; for(int i=0;i<b.length;i++) b[i] = a[p+i]; for(int i=0;i<c.length;i++) c[i] = a[q+i+1]; int i = 0,j = 0; for(int k=p;k<=r;k++){ if(i==b.length){ a[k] = c[j]; j++; } else if(j==c.length){ a[k] = b[i]; i++; } else if(b[i]<c[j]){ a[k] = b[i]; i++; } else{ a[k] = c[j]; j++; } } } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd( y % x,x); } public static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static LinkedList<Integer> adj[]; static boolean Visited[]; static HashSet<Integer> exc; static long oddsum[]=new long[1000001]; static int co=0,ans=0; static int n,m; static String s[]; static int ind; public static void solve() { long n=nextLong(); long s=nextLong(); long low=1,high=n,ans=-1; while(low<=high){ long mid=(low+high)/2; if(check(mid,s)){ ans=mid; high=mid-1; }else { low=mid+1; } } if(ans==-1) pw.println(0); else pw.println(n-ans+1); } private static boolean check(long mid,long s){ long n=mid; int sum=0; while(mid>0){ sum+=(mid%10); mid/=10; } if(n-sum >=s) return true; return false; } static int[] levl; static int h_max=0; public static void dfs(int curr,int lev){ Visited[curr]=true; levl[curr]=lev; h_max=Math.max(h_max, levl[curr]); for(int x:adj[curr]){ if(!Visited[x]){ dfs(x,lev+1); } } } public static String reverseString(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return (sb.toString()); } private static void BFS(int sou,int dest){ Queue<Integer> q=new LinkedList<Integer>(); q.add(sou); Visited[sou]=true; while(!q.isEmpty()){ int top=q.poll(); for(int i:adj[top]){ //pw.println(i+" "+top); if(!Visited[i]) { q.add(i); } Visited[i]=true; if(i==dest){ pw.println("Yes"); return; } } } pw.println("No"); } private static long ncr(int n,int k){ if (k < 0 || k > n) return 0; if (n-k < k) k = n-k; BigInteger x = BigInteger.ONE; for (int i = 1; i <= k; i++) { x = x.multiply(new BigInteger(""+(n-i+1))); x = x.divide(new BigInteger(""+i)); } return x.longValue(); } private static long fact(long count){ long ans=1; for(int i=1;i<=count;i++){ ans*=i; } return ans; } static int state=1; static long no_exc=0,no_vert=0; static Stack<Integer> st; static HashSet<Integer> inset; private static void topo(int curr){ Visited[curr]=true; inset.add(curr); for(int x:adj[curr]){ if(adj[x].contains(curr) || inset.contains(x)){ state=0; return; } if(state==0) return; } st.push(curr); inset.remove(curr); } static HashSet<Integer> hs; private static void buildgraph(int n){ adj=new LinkedList[n+1]; Visited=new boolean[n+1]; for(int i=0;i<=n;i++){ adj[i]=new LinkedList<Integer>(); } } // To Get Input // Some Buffer Methods public static void sort(long a[]){ Merge(a, 0, a.length-1); } public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static 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++]; } private static int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static 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(); } private static int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private static long[][] next2dArray(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextLong(); } } return arr; } private static char[][] nextCharArray(int n,int m){ char [][]c=new char[n][m]; for(int i=0;i<n;i++){ String s=nextLine(); for(int j=0;j<s.length();j++){ c[i][j]=s.charAt(j); } } return c; } private static long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private static void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(boolean[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class Node{ int to; long dist; Node(int to,long dist){ this.to=to; this.dist=dist; } } /* class Pair implements Comparable<Pair>{ int ele,ind; Pair(int ele,int ind){ this.ele=ele; this.ind=ind; } @Override public int compareTo(Pair o) { return ele-o.ele; } public int hashCode() { //int hu = (int) (x ^ (x >>> 32)); //int hv = (int) (y ^ (y >>> 32)); //int hw = (int) (mass ^ (mass >>> 32)); //return 31 * hu + hv ; return 0; } public boolean equals(Object o) { Pair other = (Pair) o; // return x == other.x && y == other.y; return false; } } */class Dsu{ private int rank[], parent[] ,n; private static int[] parent1; Dsu(int size){ this.n=size+1; rank=new int[n]; //parent=new int[n]; parent=new int[n]; makeSet(); } void makeSet(){ for(int i=0;i<n;i++){ parent[i]=i; } } int find(int x){ if(parent[x]!=x){ parent[x]=find(parent[x]); } return parent[x]; } boolean union(int x,int y){ int xRoot=find(x); int yRoot=find(y); if(xRoot==yRoot) return false; if(rank[xRoot]<rank[yRoot]){ parent[xRoot]=yRoot; }else if(rank[yRoot]<rank[xRoot]){ parent[yRoot]=xRoot; }else{ parent[yRoot]=xRoot; rank[xRoot]++; } return true; } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new PrintStream(System.out)); StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); long[] arrB = new long[n]; long[] arrG = new long[m]; st=new StringTokenizer(f.readLine()); for(int i=0;i<n;i++){ arrB[i]=Long.parseLong(st.nextToken()); } st=new StringTokenizer(f.readLine()); for(int j=0;j<m;j++){ arrG[j]=Long.parseLong(st.nextToken()); } Arrays.sort(arrB); Arrays.sort(arrG); long ans = 0; // for (int i = 0; i < n; i++) ans += arrB[i] * m; // for (int i = 0; i < m - 1; i++) ans += arrG[i] - arrB[0]; // if (arrB[m - 1] != arrB[0]) { // if (arrB.length == 1) { // ans=-1; // } // else ans += arrG[m - 1] - arrB[1]; // } // if (arrG[m-1] < arrB[0]) { // ans=-1; // } for(int i=0;i<n;i++){ ans+=arrB[i]*(long)m; } for(int i=1;i<m;i++){ ans+=arrG[i]-arrB[n-1]; } if(arrB[n-1]!=arrG[0]){ if(n==1){ ans=-1; } else{ //smallest g goes to second to last ans+=arrG[0]-arrB[n-2]; } } if(arrB[n-1]>arrG[0]){ ans=-1; } System.out.println(ans); f.close(); out.close(); } }
nlogn
1159_C. The Party and Sweets
CODEFORCES
import java.io.*; import java.util.*; public class A { private static Scanner sc = new Scanner(new InputStreamReader(System.in)); public static void main (String[] args) throws IOException { BitSet b = new BitSet(1001); BitSet p = primes(1001); for (int i = 0; i < ps.length - 1; i++) { b.set(ps[i] + ps[i+1] + 1); } int n = sc.nextInt(), k = sc.nextInt(); for (int x = 0; x <= n; x++) { if (b.get(x) && p.get(x)) k--; } System.out.println(k > 0 ? "NO" : "YES"); } private static BitSet primes (int n) { BitSet b = new BitSet(n+1); b.set(2, n); for (int p = 2; p <= n; p++) { if (b.get(p)) { for (int x = p * 2; x <= n; x += p) { b.clear(x); } } } return b; } private static int [] ps = new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499}; }
linear
17_A. Noldbach problem
CODEFORCES
//david alexander import java.util.*; public class Subtract { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a,b; String answer = ""; while(n!=0){ a = sc.nextInt(); b = sc.nextInt(); answer += solve(a,b) + "\n"; n--; } System.out.println(answer); } public static int solve(int a, int b){ int count = 0; int div; int mod; while(true){ if(a >= b){ div = a/b; mod = a%b; count += div; if(mod==0){ return count; } else{ a = mod; } } else{ div = b/a; mod = b%a; count += div; if(mod==0){ return count; } else{ b = mod; } } } } }
constant
267_A. Subtractions
CODEFORCES
import java.util.*; public class maximus { static long GCD(long a,long b){ if(b==0)return a; return GCD(b,a%b); } public static void main(String [] args){ Scanner in=new Scanner(System.in); long n=in.nextInt(); if(n<=2){ System.out.print(n); return; } if(n%2==1){ System.out.print((n*(n-1)*(n-2))); return; } if(n%2==0 && n<=6){ System.out.print(n*(n-1)*(n-2)/2); return; } long temp=(n*(n-1)*(n-3))/GCD(n,n-3); System.out.print(Math.max((n-1)*(n-2)*(n-3),temp)); } }
constant
235_A. LCM Challenge
CODEFORCES
import java.util.Scanner; public class R113A { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(), k = in.nextInt(); int[] ind = new int[n]; int[] p = new int[n]; int[] t = new int[n]; for (int i = 0; i < n; i++){ ind[i] = i; p[i] = in.nextInt(); t[i] = in.nextInt(); } //System.out.println("erwer"); for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++){ if (p[i] < p[j] || (p[i] == p[j] && t[i] > t[j])){ int tmp = p[i]; p[i] = p[j]; p[j] = tmp; tmp = t[i]; t[i] = t[j]; t[j] = tmp; } } int i = k - 1; // System.out.println(i+" "+p[i]); while (i > 0 && p[i] == p[i - 1] && t[i] == t[i - 1]) i--; // System.out.println(i); int j = 0; while (i < n - 1 && p[i] == p[i + 1] && t[i] == t[i + 1]) { i++; j++; } // System.out.println(i); System.out.println(j + 1); } }
nlogn
166_A. Rank List
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} new Main().run(); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); int N; int M; boolean[][] used; Queue<Integer> queue; int[] dx = { -1, 0, 1, 0 }; int[] dy = { 0, -1, 0, 1 }; int ans = -1; void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter("output.txt"); N = nextInt(); M = nextInt(); used = new boolean [N][M]; queue = new ArrayDeque<Integer> (N * M); for (int K = nextInt(); K --> 0; ) addState(nextInt() - 1, nextInt() - 1); while (!queue.isEmpty()) { int cv = queue.poll(); int cx = cv / M; int cy = cv % M; for (int d = 0; d < dx.length; d++) { int nx = cx + dx[d]; int ny = cy + dy[d]; if (0 <= nx && nx < N && 0 <= ny && ny < M && !used[nx][ny]) addState(nx, ny); } } out.println((1 + ans / M) + " " + (1 + ans % M)); out.close(); } void addState(int x, int y) { used[x][y] = true; queue.add(ans = code(x, y)); } int code(int x, int y) { return x * M + y; } String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } 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 { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return true; } st = new StringTokenizer(s); } return false; } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { private static Parser in; private static PrintWriter out; public static void main(String[] args) { in = new Parser(System.in); out = new PrintWriter(System.out); int n= in.nextInt(); int min = 101; boolean b = false; int pmin = 101; int t= 0 ; for(int i=0; i<n; i++){ t = in.nextInt(); if (t<min){if(min != pmin)b=true; if(b) pmin = min; min = t; continue;} if (t>min && t<pmin){b=true; pmin = t; continue;} if (t>min && !b){b=true; pmin = t; continue;} //if (b){if(t<pmin){pmin = t; continue;}} //out.print(min); //out.print(pmin); } if (b) System.out.println(pmin); else System.out.println("NO"); //out.flush(); } } class Parser { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parser(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString(int size) { byte[] ch = new byte[size]; int point = 0; try { byte c = read(); while (c == ' ' || c == '\n' || c=='\r') c = read(); while (c != ' ' && c != '\n' && c!='\r') { ch[point++] = c; c = read(); } } catch (Exception e) {} return new String(ch,0,point); } public int nextInt() { int ret = 0; boolean neg; try { byte c = read(); while (c <= ' ') c = read(); neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; } catch (Exception e) {} return ret; } public long nextLong() { long ret = 0; boolean neg; try { byte c = read(); while (c <= ' ') c = read(); neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; } catch (Exception e) {} return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); } catch (Exception e) {} if (bytesRead == -1) buffer[0] = -1; } private byte read() { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
nlogn
22_A. Second Order Statistics
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 Vaibhav Pulastya */ 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); BSportMafia solver = new BSportMafia(); solver.solve(1, in, out); out.close(); } static class BSportMafia { public void solve(int testNumber, InputReader in, PrintWriter out) { long n = in.nextInt(); long k = in.nextInt(); long d = 9 + 4 * (2 * n + 2 * k); double smh = Math.sqrt(d); double ans = (-3 + smh) / 2; out.println(n - (int) ans); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.*; public class A72 { public static void main (String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); System.out.println(n * 3 / 2); } }
constant
84_A. Toy Army
CODEFORCES