src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.io.PrintWriter; import java.util.Locale; import java.util.Scanner; public class Main { public static void main(String args[]) { new Main().run(); } void run(){ Locale.setDefault(Locale.US); try(Scanner in=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out)){ solve(in, out); } catch (Exception e) { e.printStackTrace(); } } private void solve(Scanner in, PrintWriter out) { String a=in.nextLine(); out.println("25"); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); int ans = 0; for (int i = 0; i < s.length(); i++) { for (int j = i + 1; j <= s.length(); j++) { String t = s.substring(i, j); if (s.indexOf(t, i + 1)>=0) { ans = Math.max(ans, j - i); } } } System.out.println(ans); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { private void solve() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(), m = nextInt(), u = 1, d = n; while (u < d) { for (int i = 1; i <= m; i++) { out.println(u + " " + i); out.println(d + " " + (m - i + 1)); } u++; d--; } if (u == d) { int l = 1, r = m; while (l < r) { out.println(u + " " + l++); out.println(d + " " + r--); } if (l == r) out.println(u + " " + l); } out.close(); } public static void main(String[] args) { new D().solve(); } private BufferedReader br; private StringTokenizer st; private PrintWriter out; private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return st.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: piyushd * Date: 12/31/10 * Time: 1:30 PM * To change this template use File | Settings | File Templates. */ public class SimpleCycle { int first(int x){ return x - (x & (x - 1)); } void run(){ int N = nextInt(), M = nextInt(); int[] graph = new int[N]; for(int i = 0; i < M; i++){ int a = nextInt() - 1, b = nextInt() - 1; graph[a] |= (1<<b); graph[b] |= (1<<a); } int[] bitcount = new int[1<<N]; for(int i = 0; i < (1<<N); i++){ bitcount[i] = bitcount[i>>1]; if(i % 2 == 1) bitcount[i]++; } long[][] dp = new long[1<<N][N]; for(long[] f : dp) Arrays.fill(f, 0); long ans = 0; for(int mask = 1; mask < (1<<N); mask++){ for(int i = 0; i < N; i++)if((mask & (1<<i)) > 0){ if(bitcount[mask] == 1) dp[mask][i] = 1; else{ if(first(mask) != (1<<i)){ for(int j = 0; j < N; j++)if((graph[i] & (1<<j)) > 0 && (mask & (1<<j)) > 0){ dp[mask][i] += dp[mask - (1<<i)][j]; } } } if(bitcount[mask] >= 3 && (graph[i] & first(mask)) > 0) ans += dp[mask][i]; } } System.out.println(ans / 2); } int nextInt(){ try{ int c = System.in.read(); if(c == -1) return c; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return c; } if(c == '-') return -nextInt(); int res = 0; do{ res *= 10; res += c - '0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c = System.in.read(); if(c == -1) return -1; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return -1; } if(c == '-') return -nextLong(); long res = 0; do{ res *= 10; res += c-'0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(Character.isWhitespace(c)) c = System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(c == '\r' || c == '\n') c = System.in.read(); do{ res.append((char)c); c = System.in.read(); }while(c != '\r' && c != '\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new SimpleCycle().run(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * Author - * User: kansal * Date: 9/3/11 * Time: 5:28 PM */ public class CF85E { public static void main(String[] args) { reader = new BufferedReader(new InputStreamReader(System.in)); int height = nextInt(), width = nextInt(); if (width > height) { int t = width; width = height; height = t; } final int INF = height * width + 10; int[][][] dp = new int[height + 1][1 << width][1 << width]; for (int[][] ints : dp) { for (int[] anInt : ints) { Arrays.fill(anInt, INF); } } dp[0][0][0] = 0; for(int r = 0; r < height; ++r) { for(int uncovered = 0; uncovered < (1 << width); ++uncovered) { for(int mask = 0; mask < (1 << width); ++mask) { if (dp[r][uncovered][mask] == INF) { continue; } for(int curMask = uncovered; curMask < (1 << width); curMask = (curMask + 1) | uncovered) { int curUncovered = (1 << width) - 1; for(int i = 0; i < width; ++i) { if (hasBit(mask, i) || hasBit(curMask, i)) { curUncovered &= ~(1 << i); } if (i > 0 && hasBit(curMask, i-1)) { curUncovered &= ~(1 << i); } if (i < width-1 && hasBit(curMask, i+1)) { curUncovered &= ~(1 << i); } } dp[r+1][curUncovered][curMask] = Math.min(dp[r+1][curUncovered][curMask], dp[r][uncovered][mask] + Integer.bitCount(curMask)); } } } } int res = INF; for(int x: dp[height][0]) res = Math.min(res, x); System.out.println(height * width - res); } private static boolean hasBit(int mask, int bit) { return (((mask >> bit) & 1) == 1); } public static BufferedReader reader; public static StringTokenizer tokenizer = null; static String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } static public int nextInt() { return Integer.parseInt(nextToken()); } static public long nextLong() { return Long.parseLong(nextToken()); } static public String next() { return nextToken(); } static public String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } }
np
111_C. Petya and Spiders
CODEFORCES
import java.util.*; import java.io.*; public class code{ public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int ok,ok2; int va,vb; va = 0; vb = 0; out.println("? "+va+" "+vb); out.flush(); ok = sc.nextInt(); for(int i=29;i>=0;i--){ if(ok==0){ va += (1<<i); out.println("? "+va+" "+vb); out.flush(); ok2 = sc.nextInt(); if(ok2==1){ va -= (1<<i); }else{ vb += (1<<i); } }else{ va += (1<<i); vb += (1<<i); out.println("? "+va+" "+vb); out.flush(); ok2 = sc.nextInt(); if(ok==ok2){ vb -= (1<<i); out.println("? "+va+" "+vb); out.flush(); ok2 = sc.nextInt(); if(ok2==1){ va -= (1<<i); }else{ vb += (1<<i); } }else{ if(ok==1){ vb -= (1<<i); out.println("? "+va+" "+vb); out.flush(); ok = sc.nextInt(); } else { va -= (1<<i); out.println("? "+va+" "+vb); out.flush(); ok = sc.nextInt(); } } } } out.println("! "+va+" "+vb); out.flush(); } }
logn
1088_D. Ehab and another another xor problem
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; import java.math.BigInteger; import java.util.Arrays; /** * Built using CHelper plug-in * Actual solution is at the top * @author Erasyl Abenov * * */ public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); try (PrintWriter out = new PrintWriter(outputStream)) { TaskB solver = new TaskB(); solver.solve(1, in, out); } } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException{ String n = in.next(); out.println(25); } } class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(nextLine()); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public BigInteger nextBigInteger(){ return new BigInteger(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class D909 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] line = br.readLine().toCharArray(); int n = line.length; int l = 0; ArrayList<Node> groups = new ArrayList<>(); Node node = new Node(line[0], 1); groups.add(node); for (int i = 1; i < n; i++) { if (line[i] == groups.get(l).letter) { groups.get(l).count++; } else { node = new Node(line[i], 1); groups.add(node); l++; } } int moves = 0; ArrayList<Node> temp = new ArrayList<>(); while (groups.size() > 1) { moves++; l = groups.size(); groups.get(0).count--; groups.get(l - 1).count--; for (int i = 1; i < l - 1; i++) { groups.get(i).count -= 2; } int p; for (p = 0; p < l; p++) { if (groups.get(p).count > 0) { temp.add(groups.get(p)); break; } } int lTemp = temp.size(); for (p++; p < l; p++) { if (groups.get(p).count <= 0) { continue; } if (groups.get(p).letter == temp.get(lTemp - 1).letter) { temp.get(lTemp - 1).count += groups.get(p).count; } else { temp.add(groups.get(p)); lTemp++; } } groups.clear(); groups.addAll(temp); temp.clear(); } System.out.println(moves); } private static class Node { char letter; int count; Node(char letter, int count) { this.letter = letter; this.count = count; } } }
linear
909_D. Colorful Points
CODEFORCES
import java.io.*; import java.util.*; public class D { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; String toStr(long a) { String s = Long.toBinaryString(a); while (s.length() < 64) s = "0" + s; return s; } void solve() throws IOException { long a = nextLong(); long b = nextLong(); String sa = toStr(a); String sb = toStr(b); int i = 0; while (i < 64 && sa.charAt(i) == sb.charAt(i)) i++; int left = 64 - i; out.println((1L << left) - 1); } D() 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 D(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); FElongatedMatrix solver = new FElongatedMatrix(); solver.solve(1, in, out); out.close(); } static class FElongatedMatrix { int n; int m; int[][] arr; int[][] memo; int[][][] memo2; int first; public void readInput(Scanner sc) { n = sc.nextInt(); m = sc.nextInt(); arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = sc.nextInt(); } public void solve(int testNumber, Scanner sc, PrintWriter pw) { int tc = 1; while (tc-- > 0) { readInput(sc); int max = 0; memo2 = new int[2][n][n]; for (int[][] x : memo2) for (int[] y : x) Arrays.fill(y, -1); for (int i = 0; i < n; i++) { memo = new int[n][1 << n]; for (int[] y : memo) Arrays.fill(y, -1); first = i; max = Math.max(max, dp(1 << i, i)); } pw.println(max); } } private int dp(int msk, int prev) { if (msk == (1 << n) - 1) return getLast(first, prev); if (memo[prev][msk] != -1) return memo[prev][msk]; int max = 0; for (int i = 0; i < n; i++) { if ((msk & 1 << i) == 0) max = Math.max(max, Math.min(getDiff(prev, i), dp(msk | 1 << i, i))); } return memo[prev][msk] = max; } private int getLast(int i, int j) { if (memo2[0][i][j] != -1) return memo2[0][i][j]; int min = Integer.MAX_VALUE; for (int k = 0; k < m - 1; k++) min = Math.min(min, Math.abs(arr[i][k] - arr[j][k + 1])); return memo2[0][i][j] = min; } private int getDiff(int i, int j) { if (memo2[1][i][j] != -1) return memo2[1][i][j]; int min = Integer.MAX_VALUE; for (int k = 0; k < m; k++) min = Math.min(min, Math.abs(arr[i][k] - arr[j][k])); return memo2[1][i][j] = min; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public class CFTemplate { static final long MOD = 1000000007L; //static final long MOD2 = 1000000009L; //static final long MOD = 998244353L; //static final long INF = 500000000000L; static final int INF = 1100000000; static final int NINF = -100000; static FastScanner sc; static PrintWriter pw; static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}}; public static void main(String[] args) { sc = new FastScanner(); pw = new PrintWriter(System.out); ArrayList<Integer> primes = new ArrayList<Integer>(); for (int i = 2; i <= 3200; i++) { boolean p = true; for (int j = 2; j*j <= i; j++) { if (i%j==0) { p = false; break; } } if (p) primes.add(i); } int Q = sc.ni(); for (int q = 0; q < Q; q++) { int N = sc.ni(); int K = sc.ni(); int[] nums = new int[N+1]; for (int i = 1; i <= N; i++) nums[i] = sc.ni(); for (int i = 1; i <= N; i++) { for (int p: primes) { int c = 0; while (nums[i] % p == 0) { nums[i] /= p; c++; } if (c%2==1) nums[i] *= p; } } TreeSet<Integer> ts = new TreeSet<Integer>(); HashMap<Integer,Integer> last = new HashMap<Integer,Integer>(); int[][] dp = new int[N+1][K+1]; for (int i = 1; i <= N; i++) { if (last.containsKey(nums[i])) { ts.add(last.get(nums[i])); } last.put(nums[i],i); int[] inds = new int[K+1]; int ind = 0; for (int x: ts.descendingSet()) { inds[ind] = x; if (ind==K) break; ind++; } for (int j = 0; j <= K; j++) { dp[i][j] = INF; if (j > 0) dp[i][j] = dp[i][j-1]; for (int k = 0; k <= j; k++) { dp[i][j] = Math.min(dp[i][j],dp[inds[k]][j-k]+1); } } } pw.println(dp[N][K]); } pw.close(); } public static void sort(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } public static void sort(long[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } //Sort an array (immune to quicksort TLE) public static void sort(int[][] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int[] temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { return a[1]-b[1]; //Ascending order. } }); } public static void sort(long[][] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long[] temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr, new Comparator<long[]>() { @Override public int compare(long[] a, long[] b) { if (a[0] > b[0]) return 1; else if (a[0] < b[0]) return -1; else return 0; //Ascending order. } }); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[][] graph(int N, int[][] edges) { int[][] graph = new int[N][]; int[] sz = new int[N]; for (int[] e: edges) { sz[e[0]] += 1; sz[e[1]] += 1; } for (int i = 0; i < N; i++) { graph[i] = new int[sz[i]]; } int[] cur = new int[N]; for (int[] e: edges) { graph[e[0]][cur[e[0]]] = e[1]; graph[e[1]][cur[e[1]]] = e[0]; cur[e[0]] += 1; cur[e[1]] += 1; } return graph; } int[] intArray(int N, int mod) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = ni()+mod; return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N, long mod) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = nl()+mod; return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
1497E2
CODEFORCES
import java.util.*; import java.lang.Math.*; public class Main { static Scanner in = new Scanner(System.in); static Coor[] p; static Coor ori; static int n; static int dp[]; static Coor pre[]; public static void main(String[] args) { ori = new Coor(in.nextInt(),in.nextInt()); n = in.nextInt(); p = new Coor[n]; dp = new int[1<<n]; pre = new Coor[1<<n]; for (int i = 0;i < n;i++) { p[i] = new Coor(in.nextInt(),in.nextInt()); } Arrays.fill(dp,-1); dp[0] = 0; System.out.println( getdp((1<<n)-1)); //System.out.printf("%d",0); System.out.printf("%d",0); trace((1<<n)-1); System.out.println(); } static void trace(int mask) { if (mask == 0) return; if (pre[mask].y == -1) { System.out.printf(" %d %d",pre[mask].x+1,0); trace( mask - ( 1<< pre[mask].x ) ); } else { System.out.printf(" %d %d %d",pre[mask].x+1,pre[mask].y+1,0); trace( mask - ( 1<< pre[mask].x ) - (1<<pre[mask].y)); } } static int getdp(int mask) { if (dp[mask] != -1) return dp[mask]; int fr = 0; for (int i = 0;i < n;i++) if ( (mask & (1 << i)) != 0 ) { fr = i; break; } dp[mask] = getdp( mask - (1 << fr) ) + 2 * p[fr].dist(ori); pre[mask] = new Coor(fr,-1); for (int i = fr+1;i < n;i++) { int to = i; if ( (mask & (1 << i)) != 0) { int tmp = getdp( mask - (1<<fr) - (1<<i) ) + p[fr].dist(ori) + p[to].dist(ori) + p[fr].dist(p[to]); if (tmp < dp[mask]) { dp[mask] = tmp; pre[mask].y = i; } } } return dp[mask]; } } class Coor { int x,y; Coor(int _x,int _y) { x = _x;y = _y; } int dist(Coor o) { return ( (x-o.x) * (x-o.x) + (y-o.y) * (y-o.y) ); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; import java.util.*; public class CF1515E extends PrintWriter { CF1515E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1515E o = new CF1515E(); o.main(); o.flush(); } int[] ff, gg; int md; long ch(int n, int k) { return (long) ff[n] * gg[k] % md * gg[n - k] % md; } long inv(int a) { return a == 1 ? 1 : inv(a - md % a) * (md / a + 1) % md; } void main() { int n = sc.nextInt(); md = sc.nextInt(); int[] p2 = new int[n]; for (int p = 1, i = 0; i < n; i++) { p2[i] = p; p = p * 2 % md; } ff = new int[n + 1]; gg = new int[n + 1]; long f = 1; for (int i = 0; i <= n; i++) { gg[i] = (int) inv(ff[i] = (int) f); f = f * (i + 1) % md; } int[][] dp = new int[n + 1][n + 1]; dp[1][1] = 1; dp[2][2] = 2; for (int u = 3; u <= n; u++) for (int v = 1; v <= u; v++) { long x = v == u ? p2[u - 1] : 0; for (int k = 1; k < v && k <= u - 2; k++) x += dp[u - k - 1][v - k] * ch(v, k) % md * p2[k - 1] % md; dp[u][v] = (int) (x % md); } int ans = 0; for (int v = 1; v <= n; v++) ans = (ans + dp[n][v]) % md; println(ans); } }
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 in= new Scanner(System.in); int n=in.nextInt(); int a=in.nextInt(); int b=in.nextInt(); int []deals=new int[n]; for(int i=0; i<n; i++){ deals[i]=in.nextInt(); } Arrays.sort(deals); System.out.println(deals[b]-deals[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.min; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class F { static void solve() throws Exception { int n = scanInt(); long l[] = new long[n]; for (int i = 0; i < n; i++) { l[i] = scanLong(); } long e1 = 0, e2 = 0, ans = 0; boolean water = false; String types = scanString(); for (int i = 0; i < n; i++) { long li = l[i], cur; switch (types.charAt(i)) { case 'G': cur = min(e1, li); e1 -= cur; li -= cur; e2 += 2 * cur; ans += 2 * cur; e2 += li; ans += 3 * li; break; case 'W': water = true; e1 += li; ans += 2 * li; break; case 'L': cur = min(e1, li); e1 -= cur; li -= cur; ans += 2 * cur; cur = min(e2, li); e2 -= cur; li -= cur; ans += 3 * cur; ans += (water ? 4 : 6) * li; break; default: throw new AssertionError(); } } out.print(ans); } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
linear
1091_F. New Year and the Mallard Expedition
CODEFORCES
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.regex.*; import java.util.stream.LongStream; public class Main{ static ArrayList a[]=new ArrayList[5000001]; static Vector<pair>schedule_it(ArrayList<pair> v) { Vector<pair >ans=new Vector<>(); Collections.sort(v, new Comparator<pair>() { public int compare(pair p1,pair p2) { if(p1.y<p2.y) return -1; if(p1.y>p2.y) return 1; if(p1.x<p2.x) return -1; if(p1.x>p2.x) return 1; return 0; } }); int end=-1; for(int i=0;i<v.size();i++) { pair p=v.get(i); if(p.x>end) { ans.add(p); end=p.y; } } return ans; } public static void main(String[] args) { InputReader in=new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n=in.nextInt(); long arr[]=new long[n]; for(int i=0;i<n;i++) { arr[i]=in.nextLong(); } HashMap<Long,Integer>hm=new HashMap<>(); int id=0; for(int i=0;i<n;i++) { long sum=0; for(int j=i;j<n;j++) { sum+=arr[j]; if(!hm.containsKey(sum)) { hm.put(sum, id++); a[id-1]=new ArrayList<pair>(); } a[hm.get(sum)].add(new pair(i,j)); } } Vector<pair>fi=new Vector<>(); for(int i=0;i<id;i++) { Vector<pair> v=schedule_it(a[i]); if(v.size()>fi.size()) { fi=v; } } pw.println(fi.size()); for(int i=0;i<fi.size();i++) { pw.println((fi.get(i).x+1)+" "+(fi.get(i).y+1)); } pw.flush(); pw.close(); } private 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; } static class tri implements Comparable<tri> { int p, c, l; tri(int p, int c, int l) { this.p = p; this.c = c; this.l = l; } public int compareTo(tri o) { return Integer.compare(l, o.l); } } 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); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } /* public static long primeFactorization(long n) { HashSet<Integer> a =new HashSet<Integer>(); long cnt=0; for(int i=2;i*i<=n;i++) { while(a%i==0) { a.add(i); a/=i; } } if(a!=1) cnt++; //a.add(n); return cnt; }*/ public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x%M*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result%M * x%M)%M; x=(x%M * x%M)%M; n=n/2; } return result; } public static long modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } public static long[] shuffle(long[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } static class pair implements Comparable<pair>{ Integer x; Integer y; pair(int l,int id){ this.x=l; this.y=id; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString(){ return (x+" "+y); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author walker */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { long n = in.readInt(); if(n < 3){ out.print(n); } else if(n % 2 != 0) { out.print(n * (n-1) * (n-2)); } else if(n % 3 == 0) { out.print((n-1) * (n-2) * (n-3)); } else { out.print(n * (n-1) * (n-3)); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
constant
235_A. LCM Challenge
CODEFORCES
// upsolve with rainboy import java.io.*; import java.util.*; public class CF1187G extends PrintWriter { CF1187G() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; int k, l; byte[] bb = new byte[1 << 15]; byte getc() { if (k >= l) { k = 0; try { l = in.read(bb); } catch (IOException e) { l = 0; } if (l <= 0) return -1; } return bb[k++]; } int nextInt() { byte c = 0; while (c <= 32) c = getc(); int a = 0; while (c > 32) { a = a * 10 + c - '0'; c = getc(); } return a; } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1187G o = new CF1187G(); o.main(); o.flush(); } static final int INF = 0x3f3f3f3f; ArrayList[] aa_; int n_, m_; int[] pi, bb; int[] uu, vv, uv, cost; int[] cc; void init() { aa_ = new ArrayList[n_]; for (int u = 0; u < n_; u++) aa_[u] = new ArrayList<Integer>(); pi = new int[n_]; bb = new int[n_]; qq = new int[nq]; iq = new boolean[n_]; uu = new int[m_]; vv = new int[m_]; uv = new int[m_]; cost = new int[m_]; cc = new int[m_ * 2]; m_ = 0; } void link(int u, int v, int cap, int cos) { int h = m_++; uu[h] = u; vv[h] = v; uv[h] = u ^ v; cost[h] = cos; cc[h << 1 ^ 0] = cap; aa_[u].add(h << 1 ^ 0); aa_[v].add(h << 1 ^ 1); } int[] qq; int nq = 1 << 20, head, cnt; boolean[] iq; void enqueue(int v) { if (iq[v]) return; if (head + cnt == nq) { if (cnt * 2 <= nq) System.arraycopy(qq, head, qq, 0, cnt); else { int[] qq_ = new int[nq *= 2]; System.arraycopy(qq, head, qq_, 0, cnt); qq = qq_; } head = 0; } qq[head + cnt++] = v; iq[v] = true; } int dequeue() { int u = qq[head++]; cnt--; iq[u] = false; return u; } boolean spfa(int s, int t) { Arrays.fill(pi, INF); pi[s] = 0; head = cnt = 0; enqueue(s); while (cnt > 0) { int u = dequeue(); ArrayList<Integer> adj = aa_[u]; for (int h_ : adj) if (cc[h_] > 0) { int h = h_ >> 1; int p = pi[u] + ((h_ & 1) == 0 ? cost[h] : -cost[h]); int v = u ^ uv[h]; if (pi[v] > p) { pi[v] = p; bb[v] = h_; enqueue(v); } } } return pi[t] != INF; } void push(int s, int t) { int c = INF; for (int u = t, h_, h; u != s; u ^= uv[h]) { h = (h_ = bb[u]) >> 1; c = Math.min(c, cc[h_]); } for (int u = t, h_, h; u != s; u ^= uv[h]) { h = (h_ = bb[u]) >> 1; cc[h_] -= c; cc[h_ ^ 1] += c; } } void push1(int s, int t) { for (int u = t, h_, h; u != s; u ^= uv[h]) { h = (h_ = bb[u]) >> 1; cc[h_]--; cc[h_ ^ 1]++; } } int edmonds_karp(int s, int t) { while (spfa(s, t)) push1(s, t); int c = 0; for (int h = 0; h < m_; h++) c += cost[h] * cc[h << 1 ^ 1]; return c; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); int[] ii = new int[k]; for (int h = 0; h < k; h++) ii[h] = sc.nextInt() - 1; ArrayList[] aa = new ArrayList[n]; for (int i = 0; i < n; i++) aa[i] = new ArrayList<Integer>(); for (int h = 0; h < m; h++) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; aa[i].add(j); aa[j].add(i); } int t = n + k + 1; n_ = n * t + 1; m_ = k + (m * 2 * k + n) * (t - 1); init(); for (int i = 0; i < n; i++) { ArrayList<Integer> adj = aa[i]; for (int s = 0; s < t - 1; s++) { int u = i * t + s; for (int j : adj) { int v = j * t + s + 1; for (int x = 1; x <= k; x++) link(u, v, 1, c + (x * 2 - 1) * d); } } } for (int i = 0; i < n; i++) for (int s = 0; s < t - 1; s++) { int u = i * t + s, v = u + 1; link(u, v, k, i == 0 ? 0 : c); } for (int h = 0; h < k; h++) link(n_ - 1, ii[h] * t + 0, 1, 0); println(edmonds_karp(n_ - 1, 0 * t + t - 1)); } }
cubic
1187_G. Gang Up
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class A { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = 1; while(t-->0) solver.solve(1, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader scan, PrintWriter out) { int n = scan.nextInt(); int[] a = new int[n]; boolean[] b = new boolean[n]; int count = 0; for(int i = 0; i < n; i++) a[i] = scan.nextInt(); Arrays.sort(a); for(int i = 0; i < n; i++) { if(b[i]) continue; count++; for(int j = i; j < n; j++) { if(a[j]%a[i] == 0) b[j] = true; } } out.println(count); } } static void shuffle(int[] a) { Random get = new Random(); for(int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for(int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } 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
1209_A. Paint the Numbers
CODEFORCES
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; void solve() throws IOException { int n = nextInt(); long d = nextInt(); long[] arr = nextLongArr(n); Set<Long> res = new HashSet<>(); for (long cur : arr) { if (findMin(cur - d, arr) == d) { res.add(cur - d); } if (findMin(cur + d, arr) == d) { res.add(cur + d); } } outln(res.size()); } long findMin(long cur, long[] arr) { long res = Long.MAX_VALUE; for (long v : arr) { res = Math.min(res, Math.abs(v - cur)); } return res; } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { outln(String.format("%.9f%n", val)); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class D11 { static StreamTokenizer in; static PrintWriter out; static int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } static String nextString() throws IOException { in.nextToken(); return in.sval; } public static void main(String[] args) throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); n = nextInt(); m = nextInt(); g = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = nextInt()-1, b = nextInt()-1; g[a][b] = g[b][a] = true; } long ans = 0; for (int i = n; i > 0; i--) { //long cur = solve(i); long cur = calc(g, i-1); ans += cur; } out.println(ans/2); out.flush(); } static int n, m, V; static boolean[][] g; /*static long solve(int V) { int v = V-1; long[][] memo = new long[V][1 << V]; memo[v][1 << v] = 1; for (int mask = 1; mask < (1 << V); mask++) for (int i = 0; i < V; i++) if ((mask&(1 << i)) != 0) for (int j = 0; j < V; j++) if (g[i][j] && (mask&(1 << j)) == 0) memo[j][mask|(1 << j)] += memo[i][mask]; long res = 0; for (int mask = 1; mask < (1 << V); mask++) for (int i = 0; i < V; i++) if (Integer.bitCount(mask) > 2 && g[v][i]) res += memo[i][mask]; return res/2; }*/ static long calc(boolean[][] bs,int n){ long[][] dp=new long[1<<n][n]; for(int i=0;i<n;i++){ if(bs[i][n]) dp[1<<i][i] ++; } for(int i=1;i<1<<n;i++){ for(int j=0;j<n;j++)if(((i>>j)&1)==1) for(int k=0;k<n;k++)if(((i>>k)&1)==0 && bs[j][k]){//add dp[i|(1<<k)][k] += dp[i][j]; } } long res=0; for(int i=0;i<1<<n;i++)for(int j=0;j<n;j++)if(Integer.bitCount(i)>=2&&bs[j][n])res+=dp[i][j]; return res; } }
np
11_D. A Simple Task
CODEFORCES
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] = 1 << i; 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] = (1 << i) | (1 << j); } } } 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 java.util.Arrays; import java.util.Scanner; public class CF_111_A { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(), sum = 0, sum2 = 0; int[] a = new int[n]; for (int i = 0; i < n; i++){ a[i] = in.nextInt(); sum += a[i]; } Arrays.sort(a); for (int i = n - 1; i >=0; i--){ sum2 +=a[i]; if (sum2 * 2 > sum){ System.out.println(n - 1 - i + 1); System.exit(0); } } } }
nlogn
160_A. Twins
CODEFORCES
import java.io.*; import java.util.*; public class Answer17A{ public static void main(String[] args){ try{ BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); String[] tmp=reader.readLine().split(" "); int n=Integer.parseInt(tmp[0]); int k=Integer.parseInt(tmp[1]); boolean[] m=getPrime(n); ArrayList<Integer> prime=new ArrayList<Integer>(); for(int i=0;i<m.length;i++){ if(m[i])prime.add(i); } int sum=0; for(int i=2;i<=n;i++){ if(m[i]){ for(int j=0;j<prime.size()-1;j++){ if(i==prime.get(j)+prime.get(j+1)+1){ sum++; break; } } } } if(sum>=k){ System.out.println("YES"); }else{ System.out.println("NO"); } }catch(IOException e){ e.printStackTrace(); } } public static boolean[] getPrime(int N){ boolean[] memo=new boolean[N+1]; Arrays.fill(memo,true); memo[0]=false; memo[1]=false; for(int i=2;i*i<=N;i++){ if(memo[i]){ for(int j=i*i;j<=N;j+=i){ memo[j]=false; } } } return memo; } }
linear
17_A. Noldbach problem
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CF1197B { public static void main(String[] args) { FastReader input = new FastReader(); int n = input.nextInt(); int[] arr = new int[n]; int max = 0; int maxIndex = 0; for(int i = 0;i < n;i++){ arr[i] = input.nextInt(); if(arr[i] > max){ max = arr[i]; maxIndex = i; } } int j = maxIndex - 1; int k = maxIndex + 1; while (j >= 0 && k < n){ if(arr[j] > arr[k]){ if(arr[j] < max){ max = arr[j]; j--; } else { System.out.println("NO"); return; } } else{ if(arr[k] < max){ max = arr[k]; k++; } else{ System.out.println("NO"); return; } } } if(j >= 0){ while (j >= 0){ if(arr[j] < max){ max = arr[j]; j--; } else{ System.out.println("NO"); return; } } } if(k < n){ while (k < n){ if(arr[k] < max){ max = arr[k]; k++; } else{ System.out.println("NO"); return; } } } if(j == -1 && k == n){ System.out.println("YES"); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
linear
1197_B. Pillars
CODEFORCES
import java.io.*; import java.text.*; import java.math.*; import java.util.*; public class Hexadec implements Runnable { final static String taskname = "filename"; public void solve() throws Exception { // int n = iread(); int n = Integer.parseInt(in.readLine()); out.write(n + " "+0+" "+0); // out.write(ans_path + "\n"); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); // in = new BufferedReader(new FileReader(taskname + ".in")); // out = new BufferedWriter(new FileWriter(taskname + ".out")); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { // Locale.setDefault(Locale.US); new Thread(new Hexadec()).start(); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.util.*; public class c { public static void main(String[] args) { Scanner input = new Scanner(System.in); long a = input.nextLong(), b = input.nextLong(); System.out.println(gcd(a, b)); } static long gcd(long a, long b) { if(b==1) return a; if(a==1) return b; if(a>b) return a/b + gcd(b, a%b); return b/a + gcd(a, b%a); } }
constant
343_A. Rational Resistance
CODEFORCES
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** What do you think? What do you think? 1st on Billboard, what do you think of it Next is a Grammy, what do you think of it However you think, I’m sorry, but shit, I have no fcking interest ******************************* I'm standing on top of my Monopoly board That means I'm on top of my game and it don't stop til my hip don't hop anymore https://www.a2oj.com/Ladder16.html ******************************* 300iq as writer = Sad! */ import java.util.*; import java.io.*; import java.math.*; public class x1242C2 { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); long[] sums = new long[N]; ArrayList<Integer>[] boxes = new ArrayList[N]; for(int i=0; i < N; i++) { boxes[i] = new ArrayList<Integer>(); st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); while(a-->0) boxes[i].add(Integer.parseInt(st.nextToken())); for(int x: boxes[i]) sums[i] += x; } long lmaosum = 0L; for(long x: sums) lmaosum += x; if(Math.abs(lmaosum)%N != 0) { System.out.println("No"); return; } long target = lmaosum/N; //fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck HashMap<Long, Integer> map = new HashMap<Long, Integer>(); for(int k=0; k < N; k++) for(int x: boxes[k]) map.put((long)x, k); HashMap<Long, Long> edges = new HashMap<Long, Long>(); for(int k=0; k < N; k++) for(int x: boxes[k]) { long nextval = target-sums[k]+x; if(map.containsKey(nextval)) edges.put((long)x, nextval); } Node[] dp = new Node[1<<N]; dp[0] = new Node(-69, -69, 0); //precompute subsets ass Node[] subsets = new Node[1<<N]; for(int b=0; b < N; b++) for(int i=0; i < boxes[b].size(); i++) { if(!edges.containsKey((long)boxes[b].get(i))) continue; long curr = edges.get((long)boxes[b].get(i)); //shit shit shit shit shit shit shit shit shit shit int submask = 0; boolean cyclic = true; while(curr != boxes[b].get(i)) { int k = map.get(curr); if((submask&(1<<k)) > 0 || !edges.containsKey((long)curr)) { cyclic = false; break; } submask |= 1<<k; curr = edges.get((long)curr); } submask |= (1<<b); if(cyclic) subsets[submask] = new Node(-69, i, b); } for(int mask=1; mask < (1<<N); mask++) outer:for(int submask=mask; submask > 0; submask=(submask-1)&mask) if(dp[mask^submask] != null && subsets[submask] != null) { dp[mask] = new Node(mask^submask, subsets[submask].dex, subsets[submask].start); break outer; } if(dp[(1<<N)-1] == null) System.out.println("No"); else { StringBuilder sb = new StringBuilder("Yes\n"); long[][] res = new long[N][2]; for(int i=0; i < N; i++) res[i][1] = -1L; int currmask = (1<<N)-1; while(currmask != 0) { int submask = dp[currmask].mask; int i = dp[currmask].dex; int b = dp[currmask].start; long nextval = target-sums[b]+boxes[b].get(i); int curr = map.get(nextval); res[map.get(nextval)][0] = nextval; res[map.get(nextval)][1] = b; while(true) //lol { int lol = map.get(nextval); nextval = edges.get(nextval); res[map.get(nextval)][0] = nextval; if(res[map.get(nextval)][1] != -1) break; res[map.get(nextval)][1] = lol; } currmask = dp[currmask].mask; } for(int k=0; k < N; k++) sb.append(res[k][0]+" ").append(res[k][1]+1).append("\n"); System.out.print(sb); } } } class Node { public int mask; public int dex; public int start; public Node(int a, int b, int c) { mask = a; dex = b; start = c; } }
np
1242_C. Sum Balance
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class A { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void solve() throws IOException { final int mod = 1000*1000*1000+9; long n = readInt(); long m = readInt(); long k = readInt(); long fail = n-m; long posl = n / k ; if(n % k != 0) { posl++; } if(posl <= fail) { out.println(m); } else { long d = fail - posl; long res = (k-1) * fail; m -= (k-1) * fail; long z = m / k; res += m % k; res %= mod; long x = binpow(2, z+1, mod); x -= 2; x += mod; x %= mod; x *= k; res += x; res %= mod; out.println(res); } } long binpow (long a, long n, long mod) { long res = 1; while (n != 0) if ((n & 1) != 0) { res *= a; res = res % mod; --n; } else { a *= a; a = a % mod; n >>= 1; } return res; } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } int[] readArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = readInt(); } return res; } long[] readArrL(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = readLong(); } return res; } public static void main(String[] args) { new A().run(); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } }
logn
338_A. Quiz
CODEFORCES
import java.io.*; import java.util.*; import java.lang.*; import java.math.*; import static java.lang.Math.*; public class Solution implements Runnable { public long gcd(long a, long b) { long tmp; while (b > 0) { a %= b; tmp = a; a = b; b = tmp; } return a; } public void solve() throws Exception { long a = sc.nextLong(); long b = sc.nextLong(); long ans = 0; long k = 0; if (a == 1 || b == 1) { out.println(max(a, b)); return; } while (a > 1 && b > 1) { if (a > b) { k = a / b; ans += k; a -= (k * b); } else { k = b / a; ans += k; b -= (k * a); } k = gcd(a, b); a /= k; b /= k; } if (a == 1) ans += b; else ans += a; out.println(ans); } static Throwable throwable; BufferedReader in; PrintWriter out; FastScanner sc; public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); if (throwable != null) { throw throwable; } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable throwable) { this.throwable = throwable; } finally { out.close(); } } } class FastScanner { BufferedReader reader; StringTokenizer strTok; public FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws Exception { while (strTok == null || !strTok.hasMoreTokens()) { strTok = new StringTokenizer(reader.readLine()); } return strTok.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class LightItUp { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int previous = 0; int array[] = new int[n+1]; int answer = 0; StringTokenizer st1 = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++){ array[i] = Integer.parseInt(st1.nextToken()); if(i % 2 == 0){ answer += (array[i] - previous); } previous = array[i]; } if(n % 2 == 0){ answer += (m - previous); } previous = m; int max = Integer.MAX_VALUE; while(n-- != 0){ int temp = array[n]; if(n%2 == 0){ array[n] = array[n+1] - (previous - array[n]); } else{ array[n] = array[n+1] + (previous - array[n]); } previous = temp; max = Math.min(max, array[n]); } if(max>=-1){ System.out.println(answer); } else{ System.out.println(answer - (max+1)); } } }
linear
1000_B. Light It Up
CODEFORCES
import java.util.Scanner; public class Task1 { public static void main(String[] args) { int n = new Scanner(System.in).nextInt(); System.out.println(n*3/2); } }
constant
84_A. Toy Army
CODEFORCES
import java.io.*; import java.util.*; public class Sol2{ final public static int MXN = (1<<21); public static int good[][]; public static void main(String[] args) throws IOException{ FastIO sc = new FastIO(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int num[][] = new int[m][m]; String str = sc.next(); for(int i=0; i<str.length()-1; i++) { int a = str.charAt(i)-'a'; int b = str.charAt(i+1)-'a'; num[a][b]++; num[b][a]++; } int lowbit[] = new int[MXN]; int dp[] = new int[MXN]; for(int i=0; i<MXN; i++) { dp[i] = Integer.MAX_VALUE; } dp[0] = 0; good = new int[MXN][m]; for(int msk = 0; msk<(1<<m); msk++) { for(int i=0; i<m; i++) { int low = Integer.numberOfTrailingZeros(Integer.lowestOneBit(msk)); if(low==32) low = 0; good[msk][i] = good[msk^(1<<low)][i] + num[i][low]; } } for(int msk = 0; msk<(1<<m); msk++) { int bits = Integer.bitCount(msk)+1; for(int i=0; i<m; i++) { if((msk&(1<<i))!=0) continue; int nxt = msk|(1<<i); dp[nxt] = Math.min(dp[nxt], dp[msk] + bits*(good[msk][i]-good[((1<<m)-1)^nxt][i])); } } out.println(dp[(1<<m)-1]); out.close(); } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastIO { // Is your Fast I/O being bad? InputStream dis; byte[] buffer = new byte[1 << 17]; int pointer = 0; public FastIO(String fileName) throws IOException { dis = new FileInputStream(fileName); } public FastIO(InputStream is) throws IOException { dis = is; } int nextInt() throws IOException { int ret = 0; byte b; do { b = nextByte(); } while (b <= ' '); boolean negative = false; if (b == '-') { negative = true; b = nextByte(); } while (b >= '0' && b <= '9') { ret = 10 * ret + b - '0'; b = nextByte(); } return (negative) ? -ret : ret; } long nextLong() throws IOException { long ret = 0; byte b; do { b = nextByte(); } while (b <= ' '); boolean negative = false; if (b == '-') { negative = true; b = nextByte(); } while (b >= '0' && b <= '9') { ret = 10 * ret + b - '0'; b = nextByte(); } return (negative) ? -ret : ret; } byte nextByte() throws IOException { if (pointer == buffer.length) { dis.read(buffer, 0, buffer.length); pointer = 0; } return buffer[pointer++]; } String next() throws IOException { StringBuffer ret = new StringBuffer(); byte b; do { b = nextByte(); } while (b <= ' '); while (b > ' ') { ret.appendCodePoint(b); b = nextByte(); } return ret.toString(); } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.awt.Point; import java.io.*; import java.util.*; import static java.lang.Math.*; public class BetaRound35_C implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws IOException { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } @Override public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } public static void main(String[] args) { new Thread(new BetaRound35_C()).start(); } void solve() throws IOException { int n = readInt(); int m = readInt(); int k = readInt(); Queue<Point> q = new ArrayDeque<Point>(); boolean[][] visited = new boolean[n + 2][m + 2]; for (int j = 0; j < m + 2; j++) { visited[0][j] = true; visited[n + 1][j] = true; } for (int i = 0; i < n + 2; i++) { visited[i][0] = true; visited[i][m + 1] = true; } for (int i = 0; i < k; i++) { int x = readInt(); int y = readInt(); q.add(new Point(x, y)); visited[x][y] = true; } Point p = null; while (!q.isEmpty()) { p = q.poll(); int x = p.x, y = p.y; if (!visited[x + 1][y]) { q.add(new Point(x + 1, y)); visited[x + 1][y] = true; } if (!visited[x - 1][y]) { q.add(new Point(x - 1, y)); visited[x - 1][y] = true; } if (!visited[x][y + 1]) { q.add(new Point(x, y + 1)); visited[x][y + 1] = true; } if (!visited[x][y - 1]) { q.add(new Point(x, y - 1)); visited[x][y - 1] = true; } } out.print(p.x + " " + p.y); } }
cubic
35_C. Fire Again
CODEFORCES
//package practice; import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.Stack; import java.util.regex.Pattern; public class ROUGH { public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static long mod = (long) (1e9+7); static int N = (int) 1e5; // Scanner sc = new Scanner(System.in); public static void main(String[] args) { FastReader sc = new FastReader(); int n = sc.nextInt(); int[] a = new int[n]; TreeSet<Integer> set = new TreeSet<Integer>(); for(int i=0;i<n;++i) { a[i] = sc.nextInt(); set.add(a[i]); } long ans = 0; while(set.size() > 0) { ++ans; int min = set.first(); TreeSet<Integer> temp = new TreeSet<>(); for(int x : set) { if(x%min != 0) temp.add(x); } set = temp; } out.print(ans); out.close(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line = stdin.readLine(); int n = Integer.parseInt(line); if (n >= 0) { System.out.println(n); } else if (n > -10) { System.out.println(0); } else { String sa = line.substring(0, line.length() - 1); int a = Integer.parseInt(sa); String sb = line.substring(0, line.length() - 2) + line.charAt(line.length() - 1); int b = Integer.parseInt(sb); System.out.println(Math.max(a, b)); } } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.io.ObjectInputStream.GetField; import java.security.KeyStore.Entry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import javax.swing.JLabel; public class codeforcesreturn { static class edge { int u; int v; public edge(int u, int v) { this.u = u; this.v = v; } } static ArrayList<Integer>[] adjlist; static int[][] adjmatrix; static int[][] adjmatrix2; static boolean[] vis; static boolean[] intialvis; static boolean[] vis2; static int[] counter; static int V, E; static Stack<Integer> st; static ArrayList<Integer> arrylist; static boolean flag; static int[] dx = new int[] { 1, -1, 0, 0 }; static int[] dy = new int[] { 0, 0, 1, -1 }; static int[] Arr; static PrintWriter pw; static boolean ans = true;; public static long gcd(long u, long v) { if (u == 0) return v; return gcd(v % u, u); } public static void bib(int u) { vis[u] = true; for (int v : adjlist[u]) { if (!vis[v]) { counter[v] = 1 ^ counter[u]; bib(v); } else if (counter[v] != (1 ^ counter[u])) ans = false; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // FileWriter f = new FileWriter("C:\\Users\\Hp\\Desktop\\out.txt"); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); int sum = n; for (long i = 0; i < 1e5; i++) { if (i * (i + 1) / 2 - (n - i) == k) { System.out.println(n - i); break; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public 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(); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; 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); TaskA solver = new TaskA(); solver.solve(in, out); out.close(); } } class TaskA { int n; int m; String answer = "I'm too stupid to solve this problem"; public void solve(InputReader in, PrintWriter out) { n = in.nextInt(); out.println("0 0 " + n); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; // 1 -> n/2 XX n/2 + 1 -> n public class MotherOfDragons { static boolean[][] adjMatrix; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); // for (int i = 1; i <= n; i++) // System.err.printf("%d %.12f\n",i, (k*k*((i-1)/(2.0*i)))); adjMatrix = new boolean[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) adjMatrix[i][j] = sc.nextInt() == 1; long[] edges = new long[n]; for (int i = 0; i < n; i++) { long val = 0; for (int j = 0; j < n; j++) if(adjMatrix[i][j] || i == j) val |= 1l<<j; edges[i] = val; } int h = n/2; int[] cliques = new int[1<<h]; for (int i = 1; i < 1<<h; i++) { int nodes = i; for (int j = 0; j < h; j++) if((i & (1 << j)) != 0) nodes &= edges[j]; if(nodes == i) cliques[i] = Integer.bitCount(i); } for (int i = 1; i < 1<<h; i++) for (int j = 0; j < h; j++) if((i & (1 << j)) != 0) cliques[i] = Math.max(cliques[i], cliques[i ^ (1<<j)]); int max = 0; for (int i = 0; i < cliques.length; i++) max = Math.max(max, cliques[i]); for (int i = 1; i < 1<<(n-h); i++) { long all = -1l; long tmp = (1l*i)<<h; for (int j = h; j < n; j++) if((tmp & (1l << j)) != 0) all &= edges[j]; long node = all&tmp; if(node != tmp) continue; int connected = (int)(all & ((1<<h)-1)); max = Math.max(max, cliques[connected] + Integer.bitCount(i)); } System.out.printf("%.12f\n", (k*k*((max-1)/(2.0*max)))); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File((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 { return Double.parseDouble(next()); } } }
np
839_E. Mother of Dragons
CODEFORCES
import java.util.*; import java.io.*; public class Traffic extends Template{ public double search1(int a, int w, int d){ double s = 0; double l = 2*w+2*a*d; int repeat = 100; while( repeat-- > 0 ){ double x = (s+l)/2; if( a*a*x*x + 2*a*w*x - w*w - 4*a*d > 0 ){ l = x; } else { s = x; } } return l; } public double search2(int a, double lim, int k){ double s = 0; double l = lim + 2*a*k; int repeat = 100; while( repeat-- > 0 ){ double x = (s+l)/2; if( a*x*x + 2*lim*x - 2*k > 0 ){ l = x; } else { s = x; } } return l; } public void solve() throws IOException { int a = nextInt(); int v = nextInt(); int l = nextInt(); int d = nextInt(); int w = nextInt(); if( w > v ){ w = v; } double time_max = Math.sqrt((double)2*d/a); double time_d = search1(a,w,d); // writer.println(time_max*a < w); writer.println(v <= (w+a*time_d)/2); writer.println(w < v); double t1 = (time_max*a < w) ? time_max : (v >= (w+a*time_d)/2) ? time_d : (w < v) ? (double)(2*v*v-2*v*w+2*a*d+w*w)/(2*a*v) : (double)v/a + (double)(d-(double)v*v/(2*a))/v; double lim = (time_max*a < w) ? time_max*a : w; double t3 = Math.min((double)(v-lim)/a, search2(a, lim, l-d)); // double t = (Math.sqrt(limit*limit+2*a*(l-d))-limit)/a; double dist2 = (l-d) - t3*t3*a/2 - t3*lim; double t4 = dist2/v; // writer.println("t1 = " + t1); // writer.println("dist1 = " + dist1); // writer.println("t3 = " + t3); // writer.println("dist2 = " + dist2); // writer.println("t4 = " + t4); writer.println((t1+t3+t4)); } public static void main(String[] args){ new Traffic().run(); } } abstract class Template implements Runnable{ public abstract void solve() throws IOException; 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); } } public int nextInt() throws IOException{ return Integer.parseInt(nextToken()); } public String nextToken() throws IOException{ while( tokenizer == null || !tokenizer.hasMoreTokens() ){ tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class A { static StreamTokenizer st; static PrintWriter pw; static class Sort implements Comparable<Sort> { int x,y; public int compareTo(Sort arg0) { if (this.x==arg0.x) return this.y-arg0.y; return -(this.x-arg0.x); } } public static void main(String[] args) throws IOException{ st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int k = nextInt(); Sort[]a = new Sort[n+1]; for (int i = 1; i <= n; i++) { a[i] = new Sort(); a[i].x = nextInt(); a[i].y = nextInt(); } Arrays.sort(a,1, n+1); // for (int i = 1; i <= n; i++) { // System.out.println(a[i].x+" "+a[i].y); // } // int plase = 1; // if (k==1) { // int ans = 0; // for (int j = 1; j <= n; j++) { // if (a[j].x==a[1].x && a[j].y ==a[1].y) { // ans++; // } // } // System.out.println(ans); // return; // } // for (int i = 2; i <= n; i++) { // if (a[i].x==a[i-1].x && a[i].y==a[i-1].y) { // // } // else { // plase++; // if (plase==k) { // int ans = 0; // for (int j = 1; j <= n; j++) { // if (a[j].x==a[i].x && a[j].y ==a[i].y) { // ans++; // } // } // System.out.println(ans); // return; // } // } // } int ans = 0; for (int i = 1; i <= n; i++) { if (a[i].x==a[k].x && a[i].y==a[k].y) ans++; } System.out.println(ans); pw.close(); } private static int nextInt() throws IOException{ st.nextToken(); return (int) st.nval; } }
nlogn
166_A. Rank List
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); String[] s = {"XXXS", "XXS", "XS", "S", "M", "L", "XL", "XXL", "XXXL"}; int[] size = new int[9]; for(int i=0; i<N; i++){ String c = br.readLine(); for(int j=0; j<9; j++){ if(s[j].equals(c)){ size[j]++; } } } for(int i=0; i<N; i++){ String c = br.readLine(); for(int j=0; j<9; j++){ if(s[j].equals(c)){ size[j]--; } } } int sum = 0; for(int i=0; i<9; i++){ if(size[i]>0) sum += size[i]; } System.out.println(sum); } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.util.*; import static java.lang.Math.*; import java.io.*; public class SolutionB { public static void main(String args[])throws IOException{ Scanner sc = new Scanner(System.in); int a[] = new int[1501]; for(int i = 0; i < 3; i++){ a[sc.nextInt()]++; } if(a[1] > 0 || a[2] > 1 || a[3] > 2 || (a[4] == 2 && a[2] == 1)){ System.out.println("YES"); }else{ System.out.println("NO"); } } }
constant
911_C. Three Garlands
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.InputMismatchException; public class F547 { public static void main(String[] args) { FastScanner in = new FastScanner(System.in); int N = in.nextInt(); int[] arr = new int[N]; for(int i = 0; i < N; i++) arr[i] = in.nextInt(); long[] sum = new long[arr.length + 1]; for(int i = 1; i < sum.length; i++) sum[i] = sum[i-1] + arr[i-1]; HashMap<Long, ArrayList<Pair>> map = new HashMap<>(); for(int i = 0; i < sum.length; i++) { for(int j = i+1; j < sum.length; j++) { long diff = sum[j] - sum[i]; if(!map.containsKey(diff)) map.put(diff, new ArrayList<>()); ArrayList<Pair> list = map.get(diff); list.add(new Pair(i, j)); } } for(long key : map.keySet()) { ArrayList<Pair> list1 = map.get(key); Collections.sort(list1); ArrayList<Pair> list2 = new ArrayList<>(); int end = 0; for(Pair p : list1) { if(end <= p.a) { list2.add(p); end = p.b; } } map.put(key, list2); } long maxKey = -1; int max = -1; for(long key : map.keySet()) { if(map.get(key).size() > max) { max = map.get(key).size(); maxKey = key; } } ArrayList<Pair> list = map.get(maxKey); StringBuilder sb = new StringBuilder(); sb.append(list.size()); sb.append("\n"); for(Pair p : list) { sb.append((1 + p.a) + " " + p.b); sb.append("\n"); } System.out.println(sb.toString()); } static class Pair implements Comparable<Pair> { int a, b; public Pair(int x, int y) { a = x; b = y; } public int compareTo(Pair other) { if(b != other.b) { return b - other.b; } return other.a - a; } public String toString() { return "(" + a + ", " + b + ")"; } } /** * Source: Matt Fontaine */ static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int chars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (chars == -1) throw new InputMismatchException(); if (curChar >= chars) { curChar = 0; try { chars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (chars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } } /* 7 4 1 2 2 1 5 3 outputCopy 3 7 7 2 3 4 5 inputCopy 11 -5 -4 -3 -2 -1 0 1 2 3 4 5 outputCopy 2 3 4 1 1 inputCopy 4 1 1 1 1 outputCopy 4 4 4 1 1 2 2 3 3 */
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class C{ static int n; static double sqr(double v) {return (v*v);} static double sqrt(double v) {return Math.sqrt(v);} static double r,x[],res[]; static void MainMethod()throws Exception{ n=reader.nextInt(); r=reader.nextDouble(); int i,j; x=new double[n]; res=new double[n]; for (i=0;i<n;i++)x[i]=reader.nextDouble(); res[0]=r; for (i=1;i<n;i++) { res[i]=r; for (j=0;j<i;j++) { if (Math.abs(x[i]-x[j])<=(2*r)) { res[i]=Math.max(res[i], sqrt(sqr(2*r)-sqr(x[i]-x[j]))+res[j] ); } } } for (i=0;i<n;i++) printer.print(res[i]+" "); } public static void main(String[] args)throws Exception{ MainMethod(); printer.close(); } static void halt(){ printer.close(); System.exit(0); } static PrintWriter printer=new PrintWriter(new OutputStreamWriter(System.out)); static class reader{ static BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer token=new StringTokenizer(""); static String readNextLine() throws Exception{ return bReader.readLine(); } static String next() throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return token.nextToken(); } static int nextInt()throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return Integer.parseInt(token.nextToken()); } static long nextLong()throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return Long.parseLong(token.nextToken()); } static double nextDouble()throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return Double.parseDouble(token.nextToken()); } } static class MyMathCompute{ static long [][] MatrixMultiplyMatrix(long [][] A, long [][] B, long mod) throws Exception{ int n=A.length, m=B[0].length; int p=A[0].length; int i,j,k; if (B.length!=p) throw new Exception("invalid matrix input"); long [][] res=new long [n][m]; for (i=0;i<n;i++) for (j=0;j<m;j++){ if (A[i].length!=p) throw new Exception("invalid matrix input"); res[i][j]=0; for (k=0;k<p;k++) res[i][j]=(res[i][j]+((A[i][k]*B[k][j])% mod))% mod; } return res; } static double [][] MatrixMultiplyMatrix(double [][] A, double [][] B ) throws Exception{ int n=A.length, m=B[0].length; int p=A[0].length; int i,j,k; if (B.length!=p) throw new Exception("invalid matrix input"); double [][] res=new double [n][m]; for (i=0;i<n;i++) for (j=0;j<m;j++){ if (A[i].length!=p) throw new Exception("invalid matrix input"); res[i][j]=0; for (k=0;k<p;k++) res[i][j]=res[i][j]+(A[i][k]*B[k][j]); } return res; } static long [][] MatrixPow(long [][] A,long n, long mod) throws Exception{ if (n==1) return A; long [][] res=MatrixPow(A, n/2, mod); res=MatrixMultiplyMatrix(res, res, mod); if ((n % 2) == 1) res=MatrixMultiplyMatrix(A,res, mod); return res; } static double [][] MatrixPow(double [][] A,long n) throws Exception{ if (n==1) return A; double[][] res=MatrixPow(A, n/2); res=MatrixMultiplyMatrix(res, res); if ((n % 2) == 1) res=MatrixMultiplyMatrix(A,res); return res; } static long pow(long a,long n,long mod){ a= a % mod; if (n==0) return 1; long k=pow(a,n/2,mod); if ((n % 2)==0) return ((k*k)%mod); else return (((k*k) % mod)*a) % mod; } static double pow(double a,long n){ if (n==0) return 1; double k=pow(a,n/2); if ((n % 2)==0) return (k*k); else return (((k*k) )*a) ; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; public class ProblemA { public static void main(String[] args) throws Exception{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(bf.readLine()); StringTokenizer st1 = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); int[] xcoords = new int[n]; for(int i = 0;i<n;i++){ xcoords[i] = Integer.parseInt(st1.nextToken()); } double[] ycoords = new double[n]; for(int i = 0;i<n;i++){ ArrayList<Integer> nodes = new ArrayList<Integer>(); for(int j = 0;j<i;j++){ if (Math.abs(xcoords[j] - xcoords[i]+0.0) <= 2*r) nodes.add(j); } if (nodes.isEmpty()){ ycoords[i] = r; continue; } else{ double min = -1; for(int k = 0;k<nodes.size();k++){ double tmp = ycoords[nodes.get(k)] + Math.sqrt(4*r*r - (xcoords[i] - xcoords[nodes.get(k)])*(xcoords[i] - xcoords[nodes.get(k)])); if (tmp > min){ min = tmp; } } ycoords[i] = min; } } for(int i = 0;i<ycoords.length;i++){ System.out.print(ycoords[i] + " "); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; import java.awt.Point; public class Main{ public static void main(String[] args)throws FileNotFoundException,IOException{ File file = new File("input.txt"); Scanner sc = new Scanner(file); File outFile = new File("output.txt"); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(outFile))); int w = sc.nextInt(); int h = sc.nextInt(); boolean[][] map = new boolean[h+1][w+1]; //false:�u�G�v���ĂȂ� int x = -1, y = -1; Queue<Point> open = new LinkedList<Point>(); int k = sc.nextInt(); for(int i=0;i<k;i++){ int tx = sc.nextInt(); int ty = sc.nextInt(); map[ty][tx] = true; x = tx; y = ty; open.add(new Point(x,y)); } int dx[] = {1,-1,0,0}; int dy[] = {0,0,1,-1}; while(!open.isEmpty()){ Point p = open.poll(); for(int i=0;i<4;i++){ int nx = p.x + dx[i]; int ny = p.y + dy[i]; if(nx>0 && nx<=w && ny>0 && ny<=h && !map[ny][nx]){ map[ny][nx] = true; x = nx; y = ny; open.add(new Point(nx,ny)); } } } pw.println(x + " " + y); pw.close(); } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedInputStream; import java.util.Scanner; public class HamstersAndTigers { //Round #XX - Hamsters and Tigers public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); int numAnimals = sc.nextInt(); String positions = sc.next(); int numTigers = 0; int numHamsters = 0; for(int i = 0; i < positions.length(); i++) { if(positions.charAt(i) == 'T') { numTigers++; } else { numHamsters++; } } int minDifference = Integer.MAX_VALUE; StringBuilder tigerChars = new StringBuilder(1000); StringBuilder hamsterChars = new StringBuilder(1000); for(int i = 0; i < numHamsters; i++) { hamsterChars.append('H'); } StringBuilder remainingTigerChars = new StringBuilder(1000); for(int i = 0; i < numTigers; i++) { remainingTigerChars.append('T'); } for(int i = 0; i <= numTigers; i++) { StringBuilder generated = new StringBuilder(); generated.append(tigerChars); generated.append(hamsterChars); generated.append(remainingTigerChars); //System.out.println(generated); if(remainingTigerChars.length() >= 1) { remainingTigerChars.deleteCharAt(remainingTigerChars.length() - 1); } tigerChars.append('T'); int diffCount = stringDiffCount(positions, generated.toString()); if(diffCount < minDifference) { minDifference = diffCount; } } //System.out.println(""); hamsterChars = new StringBuilder(1000); tigerChars = new StringBuilder(1000); for(int i = 0; i < numTigers; i++) { tigerChars.append('T'); } StringBuilder remainingHamsterChars = new StringBuilder(1000); for(int i = 0; i < numHamsters; i++) { remainingHamsterChars.append('H'); } for(int i = 0; i <= numHamsters; i++) { StringBuilder generated = new StringBuilder(); generated.append(hamsterChars); generated.append(tigerChars); generated.append(remainingHamsterChars); //System.out.println(generated); if(remainingHamsterChars.length() >= 1) { remainingHamsterChars.deleteCharAt(remainingHamsterChars.length() - 1); } hamsterChars.append('H'); int diffCount = stringDiffCount(positions, generated.toString()); if(diffCount < minDifference) { minDifference = diffCount; } } System.out.println(minDifference / 2); } private static int stringDiffCount(String strOne, String strTwo) { int diffCount = 0; for(int i = 0; i < strOne.length(); i++) { if(strOne.charAt(i) != strTwo.charAt(i)) { diffCount++; } } return diffCount; } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class P35C { public static void main(String[] args) throws FileNotFoundException { InputStream inputStream = new FileInputStream("input.txt"); OutputStream outputStream = new FileOutputStream("output.txt"); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } static class Task { private class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } private int dis(int i, int j, Point p2) { return Math.abs(i - p2.x) + Math.abs(j - p2.y); } public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); int k = in.nextInt(); Point[] ps = new Point[k]; for (int i = 0; i < k; i++) { ps[i] = new Point(in.nextInt() - 1, in.nextInt() - 1); } int max = 0; Point argmax = ps[0]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int val = dis(i, j, ps[0]); for (int l = 1; l < k; l++) { val = Math.min(val, dis(i, j, ps[l])); } if (val > max) { max = val; argmax = new Point(i, j); } } } out.println((argmax.x + 1) + " " + (argmax.y + 1)); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } }
cubic
35_C. Fire Again
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.StringTokenizer; public class ProblemA { String fileName = "prizes"; public void solve() throws IOException { int n = nextInt(); int d = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } int ans = 2; for (int i = 1; i < n; i++) { if (a[i] - a[i - 1] == 2 * d) ans++; if (a[i] - a[i - 1] > 2 * d) ans += 2; } out.println(ans); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out, true); // out = new PrintWriter(fileName + ".out"); // br = new BufferedReader(new FileReader(fileName + ".in")); // out = new PrintWriter(fileName + ".out"); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } BufferedReader br; StringTokenizer in; static PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { new ProblemA().run(); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
/************************************************************************* > File Name: cf111c.java > Author: Yuchen Wang > Mail: wyc8094@gmail.com > Created Time: Sat Feb 11 16:51:01 2017 ************************************************************************/ import java.util.*; import java.io.*; public class cf111c { public static int n,m,maxm; public static int[][][] dp; public static int[] s; public static int cal(int cur) { int res = 0; while(cur>0){ res ++; cur = cur&(cur-1); } return res; } public static boolean check(int a,int b,int c) { int res = (maxm-1) & (b | (b<<1) | (b>>1) | a | c); if(res == maxm-1)return true; else return false; } public static void main(String[] argv) { Scanner in = new Scanner(System.in); n = in.nextInt(); m = in.nextInt(); if(n<m){ int t = m; m = n; n = t; } maxm = 1<<m; int i,j,k,l; dp = new int[n+1][1<<m][1<<m]; s = new int[1<<m]; for(i=0;i<n+1;i++){ for(j=0;j<maxm;j++){ Arrays.fill(dp[i][j],100); } } for(i=0;i<maxm;i++){ s[i] = cal(i); dp[0][0][i] = 0; } for(i=1;i<=n;i++){ for(j=0;j<maxm;j++){ for(k=0;k<maxm;k++){ for(l=0;l<maxm;l++){ if(dp[i-1][k][l]!=100 && check(k,l,j)){ dp[i][l][j] = Math.min(dp[i-1][k][l]+s[l],dp[i][l][j]); } } } } } int ans = 100; for(i=0;i<maxm;i++) ans = Math.min(dp[n][i][0],ans); System.out.println(n*m-ans); return; } }
np
111_C. Petya and Spiders
CODEFORCES
import java.io.*; import java.util.*; public class j { public static void main(String a[])throws IOException { BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); int k=0,i=0,j=0,n=0,p=0,t=0; String s; s=b.readLine(); StringTokenizer c=new StringTokenizer(s); n=Integer.parseInt(c.nextToken()); k=Integer.parseInt(c.nextToken()); int d[]=new int[n]; int e[]=new int[n]; for(i=0;i<n;i++) { s=b.readLine(); StringTokenizer z=new StringTokenizer(s); d[i]=Integer.parseInt(z.nextToken()); e[i]=Integer.parseInt(z.nextToken()); } for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { if(d[j]<d[i]) { t=d[j]; d[j]=d[i]; d[i]=t; t=e[j]; e[j]=e[i]; e[i]=t; } } } for(i=0;i<n-1;i++) { if(((d[i+1]-e[i+1]/2.0)-(d[i]+e[i]/2.0))>k) p+=2; if(((d[i+1]-e[i+1]/2.0)-(d[i]+e[i]/2.0))==k) p++; } System.out.print(p+2); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class CodeForces { public void solve() throws IOException { int n=nextInt(); int t=nextInt(); double larr[]=new double [n]; double rarr[]=new double [n]; for(int i=0;i<n;i++){ double x=nextDouble(); double r=nextDouble(); larr[i]=x-r/2; rarr[i]=x+r/2; } Arrays.sort(larr); Arrays.sort(rarr); int counter=2; for(int i=1;i<n;i++){ if(larr[i]-rarr[i-1]>t){ counter+=2; } else if(larr[i]-rarr[i-1]==t){ counter++; } } writer.print(counter); } public static void main(String[] args) { new CodeForces().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); //reader = new BufferedReader(new FileReader("input.txt")); tokenizer = null; writer = new PrintWriter(System.out); //writer = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); // long t=new Date().getTime(); solve(); // writer.println(t-new Date().getTime()); 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(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.*; public class E implements Runnable { public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();} long oo = (long)2e18; public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println("Go!"); int t = fs.nextInt(); while(t-->0) { int n = fs.nextInt(); long k = fs.nextLong(); long toCut = 1, numSquares = 1, free = 0; int cuts = 0; while(true) { if(cuts >= n) { k = oo; break; } k -= toCut; if(k < 0) { k = oo; break; } cuts++; try { free = Math.addExact(free, Math.multiplyExact(numSquares, getVal(n-cuts))); } catch (Exception e) { k = 0; break; } if(free >= k) { k = 0; break; } toCut += (1L<<cuts); numSquares += (1L<<(cuts+1)); } if(k == 0) { out.printf("YES %d\n", n-cuts); } else { out.printf("NO\n"); } } out.close(); } long getVal(int n) { if(n > 31) return oo; long last = 0, cur = 0; for(int i = 1; i <= n; i++) { cur = 1 + 4*last; last = cur; } return cur; } 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) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), 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; } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.util.*; public final class PythonIndentation { public static void main(String[] args) { new PythonIndentation(System.in, System.out); } static class Solver implements Runnable { static final int MOD = (int) 1e9 + 7; int n; char[] arr; long[][] dp; BufferedReader in; PrintWriter out; void solve() throws IOException { n = Integer.parseInt(in.readLine()); arr = new char[n]; dp = new long[n + 1][n + 1]; for (int i = 0; i < n; i++) arr[i] = in.readLine().charAt(0); for (int i = 0; i <= n; i++) Arrays.fill(dp[i], -1); dp[0][0] = 1; if (arr[0] == 's') out.println(find(1, 0)); else out.println(find(1, 1)); } long find(int curr, int backIndents) { if (backIndents < 0) return 0; if (curr == n) return 1; if (dp[curr][backIndents] != -1) return dp[curr][backIndents]; long ans; if (arr[curr] == 's') ans = find(curr + 1, backIndents); else ans = find(curr + 1, backIndents + 1); if (arr[curr - 1] != 'f') ans = CMath.mod(ans + find(curr, backIndents - 1), MOD); return dp[curr][backIndents] = ans; } public Solver(BufferedReader in, PrintWriter out) { this.in = in; this.out = out; } @Override public void run() { try { solve(); } catch (IOException e) { e.printStackTrace(); } } } static class CMath { static long mod(long number, long mod) { return number - (number / mod) * mod; } } private PythonIndentation(InputStream inputStream, OutputStream outputStream) { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); PrintWriter out = new PrintWriter(outputStream); Thread thread = new Thread(null, new Solver(in, out), "PythonIndentation", 1 << 29); try { thread.start(); thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } out.flush(); out.close(); } } }
quadratic
909_C. Python Indentation
CODEFORCES
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** What do you think? What do you think? 1st on Billboard, what do you think of it Next is a Grammy, what do you think of it However you think, I’m sorry, but shit, I have no fcking interest ******************************* I'm standing on top of my Monopoly board That means I'm on top of my game and it don't stop til my hip don't hop anymore https://www.a2oj.com/Ladder16.html ******************************* 300IQ as writer = Sad! */ import java.util.*; import java.io.*; import java.math.*; public class F { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int[][] grid = new int[N][M]; for(int i=0; i < N; i++) grid[i] = readArr(M, infile, st); int[][] mindiff = new int[N][N]; for(int a=0; a < N; a++) for(int b=a+1; b < N; b++) { int val = Integer.MAX_VALUE; for(int i=0; i < M; i++) val = Math.min(val, Math.abs(grid[a][i]-grid[b][i])); mindiff[a][b] = mindiff[b][a] = val; } int res = 0; for(int start=0; start < N; start++) { int[][] dp = new int[1<<N][N]; Arrays.fill(dp[0], Integer.MAX_VALUE); for(int mask=0; mask < (1<<N); mask++) { if(Integer.bitCount(mask) == 1 && mask != (1<<start)) continue; for(int prev=0; prev < N; prev++) if((mask&(1<<prev)) > 0 || mask == 0) { for(int b=0; b < N; b++) if((mask&(1<<b)) == 0) { int submask = mask|(1<<b); if(mask == 0) dp[submask][b] = Integer.MAX_VALUE; else dp[submask][b] = Math.max(dp[submask][b], Math.min(dp[mask][prev], mindiff[prev][b])); } } } for(int b=0; b < N; b++) { int temp = dp[(1<<N)-1][b]; for(int i=0; i < M-1; i++) temp = Math.min(temp, Math.abs(grid[b][i]-grid[start][i+1])); res = Math.max(res, temp); } } System.out.println(res); } public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } }
np
1102_F. Elongated Matrix
CODEFORCES
import org.omg.PortableServer.AdapterActivator; import java.io.*; import java.lang.reflect.Array; import java.net.CookieHandler; import java.util.*; import java.math.*; import java.lang.*; import java.util.concurrent.LinkedBlockingDeque; import static java.lang.Math.*; public class TaskA implements Runnable { long m = (int)1e9+7; PrintWriter w; InputReader c; public void run() { c = new InputReader(System.in); w = new PrintWriter(System.out); int n = c.nextInt(); int a[] = scanArrayI(n); int maxtime = Integer.MAX_VALUE,ind = -1; for(int i=0;i<n;i++){ int time = Integer.MAX_VALUE; if(a[i]<i+1) time = i; else{ time = (int)ceil((a[i] - i)/(double)n) * n + i; } if(time<maxtime){ maxtime = time; ind = i; } } w.println(ind+1); w.close(); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static void sortbyColumn(int arr[][], int col){ Arrays.sort(arr, new Comparator<int[]>() { public int compare(int[] o1, int[] o2){ return(Integer.valueOf(o1[col]).compareTo(o2[col])); } }); } public static class DJSet { public int[] upper; public DJSet(int n) { upper = new int[n]; Arrays.fill(upper, -1); } public int root(int x) { return upper[x] < 0 ? x : (upper[x] = root(upper[x])); } public boolean equiv(int x, int y) { return root(x) == root(y); } public boolean union(int x, int y) { x = root(x); y = root(y); if (x != y) { if (upper[y] < upper[x]) { int d = x; x = y; y = d; } upper[x] += upper[y]; upper[y] = x; } return x == y; } } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i]; int[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } public void printArray(int[] a){ for(int i=0;i<a.length;i++) w.print(a[i]+" "); w.println(); } public int[] scanArrayI(int n){ int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = c.nextInt(); return a; } public long[] scanArrayL(int n){ long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = c.nextLong(); return a; } public void printArray(long[] a){ for(int i=0;i<a.length;i++) w.print(a[i]+" "); w.println(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new TaskA(),"TaskA",1<<26).start(); } }
nlogn
996_B. World Cup
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class CF113_Div2_A implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok; final boolean ONLINE_JUDGE = (System.getProperty("ONLINE_JUDGE") != null); public static void main(String[] args) { new Thread(null, new CF113_Div2_A(), "", 256 * (1L << 20)).start(); } @Override public void run() { try { long startTime = System.currentTimeMillis(); if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } Locale.setDefault(Locale.US); tok = new StringTokenizer(""); solve(); in.close(); out.close(); long endTime = System.currentTimeMillis(); System.err.println("Time = " + (endTime - startTime)); long freeMemory = Runtime.getRuntime().freeMemory(); long totalMemory = Runtime.getRuntime().totalMemory(); System.err.println("Memory = " + ((totalMemory - freeMemory) >> 10)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } /** http://pastebin.com/j0xdUjDn */ static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static final int MAGIC_VALUE = 50; private static void mergeSort(int[] a, int leftIndex, int rightIndex) { if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } void debug(Object... o) { if (!ONLINE_JUDGE) { System.err.println(Arrays.deepToString(o)); } } // solution class Team implements Comparable<Team>{ int cnt, time; public Team(int cnt, int time) { this.cnt = cnt; this.time = time; } @Override public int compareTo(Team x) { if (cnt == x.cnt) return time - x.time; return x.cnt - cnt; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + cnt; result = prime * result + time; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Team other = (Team) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (cnt != other.cnt) return false; if (time != other.time) return false; return true; } private CF113_Div2_A getOuterType() { return CF113_Div2_A.this; } } void solve() throws IOException { int n = readInt(); int k = readInt(); k--; Team[] a = new Team[n]; for (int i =0 ; i < n; i++) { a[i] = new Team(readInt(), readInt()); } Arrays.sort(a); int res = 1; for (int i = k-1; i >= 0; i--) { if (a[k].equals(a[i])) res++; } for (int i = k+1; i < n; i++) { if (a[k].equals(a[i])) res++; } out.print(res); } }
nlogn
166_A. Rank List
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ int q=in.nextInt(); for(int i=0;i<q;i++) { out.println(work()); } out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } int id[]; long work() { int n=in.nextInt(); int m=in.nextInt(); long ret=0; PriorityQueue<int[]> pq=new PriorityQueue<>(new Comparator<int[]>() { public int compare(int[] arr1,int[] arr2) { return arr1[2]-arr2[2]; } }); long sum=0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int v=in.nextInt(); pq.add(new int[] {i,j,v}); sum+=v; if(pq.size()>6)pq.poll(); } } if(m==1)return sum; if(n<=3) { while(pq.size()>0) { int[] p=pq.poll(); if(pq.size()<n) { ret+=p[2]; } } return ret; } int[][] A=new int[6][]; for(int i=0;pq.size()>0;i++) { A[i]=pq.poll(); } for(int i=0;i<6;i++) { for(int j=i+1;j<6;j++) { for(int k=j+1;k<6;k++) { out: for(int p=k+1;p<6;p++) { int s=A[i][2]+A[j][2]+A[k][2]+A[p][2]; HashMap<Integer,ArrayList<Integer>> map=new HashMap<>(); if(map.get(A[i][1])==null) { map.put(A[i][1],new ArrayList<>()); } if(map.get(A[j][1])==null) { map.put(A[j][1],new ArrayList<>()); } if(map.get(A[k][1])==null) { map.put(A[k][1],new ArrayList<>()); } if(map.get(A[p][1])==null) { map.put(A[p][1],new ArrayList<>()); } map.get(A[i][1]).add(A[i][0]); map.get(A[j][1]).add(A[j][0]); map.get(A[k][1]).add(A[k][0]); map.get(A[p][1]).add(A[p][0]); if(map.size()!=2) { ret=Math.max(ret, s); continue; } Integer l1=null,l2=null,r1=null,r2=null; for(int key:map.keySet()) { ArrayList<Integer> list=map.get(key); if(map.get(key).size()!=2) { ret=Math.max(ret, s); continue out; } if(l1==null) { l1=list.get(0); l2=list.get(1); }else { r1=list.get(0); r2=list.get(1); } } if((Math.abs(l1-l2)==2&&Math.abs(r1-r2)==2)||(Math.abs(l1-l2)!=2&&Math.abs(r1-r2)!=2)) { ret=Math.max(ret, s); } } } } } return ret; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(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()); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class D911 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); StringTokenizer st; int n = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine()); int[] num = new int[n]; for (int i = 0; i < n; i++) { num[i] = Integer.parseInt(st.nextToken()); } int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (num[i] < num[j]) { count++; } } } boolean ans = count % 2 == 0; for (int m = Integer.parseInt(br.readLine()); m-- > 0; ) { st = new StringTokenizer(br.readLine()); int l = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); if (((r - l + 1) / 2) % 2 != 0) { ans = !ans; } out.println(ans ? "even" : "odd"); } out.close(); } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception { //System.setIn(new FileInputStream("1")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } private static void solve() throws Exception { int n = nextInt(); int co = 0, ce = 0; int[] v = new int[n]; for (int i = 0; i < n; i++) { v[i] = nextInt(); } for (int i = 0; i < n; i++) { if (v[i] % 2 == 0) { co++; } else { ce++; } } if (co == 1) { for (int i = 0; i < n; i++) { if (v[i] % 2 == 0) { out.println(i + 1); return; } } } else { for (int i = 0; i < n; i++) { if (v[i] % 2 != 0) { out.println(i + 1); return; } } } } private static BufferedReader in; private static PrintWriter out; private static StringTokenizer st; static String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextString()); } static double nextDouble() throws IOException { return Double.parseDouble(nextString()); } }
linear
25_A. IQ test
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int r = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); double[] ans = new double[n]; for (int i = 0; i < n; i++) { double max = 0; for (int j = 0; j < i; j++) { int difx = Math.abs(arr[i] - arr[j]); if (difx <= 2 * r) { max = Math.max(max, ans[j] + Math.sqrt(4 * r * r - difx * difx)); } } ans[i] = max; } PrintWriter pw = new PrintWriter(System.out); for (int i = 0; i < n; i++) pw.print(ans[i] + r + " "); pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; //201920181 public class Polycarp{ public static void main(String args[]){ Scanner s = new Scanner(System.in); int rem[] = new int[3]; Arrays.fill(rem,-1); rem[0] = 0; char ch[] = s.next().toCharArray(); int n = ch.length; long dp[] = new long[n]; int sum = 0; for(int i=0;i<ch.length;i++){ sum = sum + (ch[i]-48); if(rem[sum%3] != -1) if(i>0){ dp[i] = Math.max(dp[i-1],dp[rem[sum%3]]+1);} else dp[i] = 1; else if(i>0) dp[i] = dp[i-1]; rem[sum%3] = i; sum = sum%3; } System.out.println(dp[n-1]); } }
linear
1005_D. Polycarp and Div 3
CODEFORCES
//package CF; // Div One import java.util.*; public class CFA_200 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long x = sc.nextLong(); long y = sc.nextLong(); System.out.println(Wilf_tree(x, y)); sc.close(); } static long Wilf_tree(long a,long b) { if(a==0||b==0) return 0; if(a>=b) return a/b+Wilf_tree(a%b, b); else return b/a+Wilf_tree(a, b%a); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Iterator; import java.util.Set; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Map; import java.util.Map.Entry; 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); PrintWriter out = new PrintWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Map<Integer, List<Range>> rgs = new HashMap<Integer, List<Range>>(); for (int i = 0; i < n; i++) { int s = 0; for (int j = i; j < n; j++) { s += a[j]; if (rgs.get(s) == null) { rgs.put(s, new ArrayList<Range>()); } rgs.get(s).add(new Range(i, j)); } } Iterator it = rgs.entrySet().iterator(); List<Range> ans = new ArrayList<Range>(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); int sum = (int) pair.getKey(); List<Range> ranges = rgs.get(sum); List<Range> cand = new ArrayList<Range>(); for (Range r : ranges) { if (cand.size() == 0) { cand.add(r); continue; } if (cand.get(cand.size() - 1).j < r.i) { cand.add(r); } else { if (cand.get(cand.size() - 1).j > r.j) { cand.remove(cand.size() - 1); cand.add(r); } } } if (cand.size() > ans.size()) { ans = cand; } } out.println(ans.size()); for (Range r : ans) { out.println((r.i + 1) + " " + (r.j + 1)); } } public class Range implements Comparable { public int i; public int j; public Range(int i, int j) { this.i = i; this.j = j; } public int compareTo(Object o) { Range t = (Range) o; if (this.i == t.i) { if (this.j < t.j) return 1; else return 0; } if (this.i < t.i) return 1; return 0; } } } 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()); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class pr988B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); ArrayList<String> a = new ArrayList<>(); for (int i = 0; i < n; i++) { a.add(br.readLine()); } if(solve(n, a)){ out.println("YES"); for (String s : a) { out.println(s); } } else out.println("NO"); out.flush(); out.close(); } private static boolean solve(int n, ArrayList<String> a) { a.sort(Comparator.comparingInt(String::length)); for (int i = 0; i < n - 1; i++) { if(!a.get(i+1).contains(a.get(i))) return false; } return true; } }
nlogn
988_B. Substrings Sort
CODEFORCES
import java.util.*; import java.io.*; public class A { public static void main(String ar[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s1[]=br.readLine().split(" "); int n=Integer.parseInt(s1[0]); int S=Integer.parseInt(s1[1]); if(S%n==0) System.out.println(S/n); else System.out.println(S/n+1); } }
constant
1061_A. Coins
CODEFORCES
import java.util.*; import java.io.*; public class D { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { boolean even = true; int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); for (int j = 0; j < i; j++) { if (a[j] > a[i]) { even = !even; } } } int m = in.nextInt(); for (int i = 0; i < m; i++) { if ((1 - in.nextInt() + in.nextInt()) / 2 % 2 == 1) { even = !even; } if (even) out.println("even"); else out.println("odd"); } finish(); } public static void finish() { out.close(); in.close(); System.exit(0); } static class InputReader implements Iterator<String>, Closeable { // Fast input reader. Based on Kattio.java from open.kattis.com // but has method names to match Scanner private BufferedReader r; private String line; private StringTokenizer st; private String token; public InputReader(InputStream i) { r = new BufferedReader(new InputStreamReader(i)); } public boolean hasNext() { return peekToken() != null; } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public String next() { return nextToken(); } public String nextLine() { try { line = r.readLine(); } catch (IOException e) { line = null; } token = null; st = null; return line; } public void close() { try { r.close(); } catch (IOException e) { } } private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; public class HexadecimalTheorem { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); PrintWriter out = new PrintWriter(System.out); out.printf("%d %d %d%n", 0, 0, n); out.flush(); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
//Author: Patel Rag //Java version "1.8.0_211" import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long modExp(long x, long n, long mod) //binary Modular exponentiation { long result = 1; while(n > 0) { if(n % 2 == 1) result = (result%mod * x%mod)%mod; x = (x%mod * x%mod)%mod; n=n/2; } return result; } static long gcd(long a, long b) { if(a==0) return b; return gcd(b%a,a); } public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); int n = fr.nextInt(); int q = fr.nextInt(); long[] a = new long[n]; long[] k = new long[q]; for(int i = 0; i < n; i++) a[i] = fr.nextLong(); for(int i = 0; i < q; i++) k[i] = fr.nextLong(); long[] pre = new long[n]; pre[0] = a[0]; for(int i = 1; i < n; i++) pre[i] = pre[i-1] + a[i]; long pd = 0; for(int i = 0; i < q; i++) { int l = 0; int r = n - 1; while(r > l) { int mid = (l + r) >> 1; if(pre[mid] - pd < k[i]) { l = mid + 1; } else if(pre[mid] - pd > k[i]) { r = mid - 1; } else { l = r = mid; } } int ans = 0; if(pre[l] - pd <= k[i]) { ans = n - l - 1; } else { ans = n - l; } if(ans == 0) ans = n; pd = pd + k[i]; if(pd >= pre[n-1]) pd = 0; System.out.println(ans); } } } class pair { public int first; public int second; public pair(int first,int second) { this.first = first; this.second = second; } public pair(pair p) { this.first = p.first; this.second = p.second; } public int first() { return first; } public int second() { return second; } public void setFirst(int first) { this.first = first; } public void setSecond(int second) { this.second = second; } } class myComp implements Comparator<pair> { public int compare(pair a,pair b) { if(a.first != b.first) return (a.first - b.first); return (b.second - a.second); } } class BIT //Binary Indexed Tree aka Fenwick Tree { public long[] m_array; public BIT(long[] dat) { m_array = new long[dat.length + 1]; Arrays.fill(m_array,0); for(int i = 0; i < dat.length; i++) { m_array[i + 1] = dat[i]; } for(int i = 1; i < m_array.length; i++) { int j = i + (i & -i); if(j < m_array.length) { m_array[j] = m_array[j] + m_array[i]; } } } public final long prefix_query(int i) { long result = 0; for(++i; i > 0; i = i - (i & -i)) { result = result + m_array[i]; } return result; } public final long range_query(int fro, int to) { if(fro == 0) { return prefix_query(to); } else { return (prefix_query(to) - prefix_query(fro - 1)); } } public void update(int i, long add) { for(++i; i < m_array.length; i = i + (i & -i)) { m_array[i] = m_array[i] + add; } } }
nlogn
975_C. Valhalla Siege
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); String inp = in.nextLine(); System.out.println(25); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; import java.util.Comparator; public class Main { private static StreamTokenizer in; private static PrintWriter out; private static int nextInt() throws Exception { in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } public static void main(String[] args) throws Exception { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); int n = nextInt(), t = nextInt() * 2; int[][] a = new int[n][2]; for (int i=0; i<n; i++) { a[i][0] = nextInt() * 2; a[i][1] = nextInt() * 2; } Arrays.sort(a, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[0]>b[0]?1:a[1]<b[1]?-1:0; } }); int s = 2; for (int i=0; i<n-1; i++) { int g = (a[i+1][0]-a[i][0])-(a[i+1][1]+a[i][1])/2; if (g > t) s += 2; if (g == t) s+= 1; } out.println(s); out.flush(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; public class GFG { static int count=0; public static void main (String[] args) { Scanner ob=new Scanner(System.in); int n; long MOD=(long)(1e9+7); int f=0,s=0; n=ob.nextInt(); long dp[][]=new long[n+2][n+2]; dp[0][1]=1; char ch='s'; char p; for(int i=1;i<=n;i++) { p=ch; ch=ob.next().charAt(0); if(p=='f') { for(int j=1;j<=n;j++) dp[i][j+1]=dp[i-1][j]; } else { for(int j=n;j>0;j--) { dp[i][j]=(dp[i][j+1]+dp[i-1][j])%MOD; } } } long ans=0; for(int i=1;i<=n;i++) { ans=(ans+dp[n][i])%MOD; } System.out.println(ans); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.*; import java.util.*; public class Main implements Runnable { public void _main() throws IOException { long n = nextLong(); long m = nextLong(); long k = nextLong(); long numBlocks = Math.min(Math.min(n / k, n - m), m / (k - 1)); n -= numBlocks * k; m -= numBlocks * (k - 1); long numFullBlocks = m / k; long rem = m % k; long res = 0; res = (res + ((p2(numFullBlocks + 1) + MOD - 2) % MOD) * k) % MOD; res = (res + rem) % MOD; res = (res + numBlocks * (k - 1)) % MOD; out.println(res); } final int MOD = 1000000009; private long p2(long s) { long res = 1; long x = 2; while (s > 0) { if (s % 2 == 1) { res = res * x % MOD; } x = x * x % MOD; s /= 2; } return res; } private BufferedReader in; private PrintWriter out; private StringTokenizer st; private String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String rl = in.readLine(); if (rl == null) return null; st = new StringTokenizer(rl); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) { Locale.setDefault(Locale.UK); new Thread(new Main()).start(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //in = new BufferedReader(new FileReader("a.in")); //out = new PrintWriter(new FileWriter("a.out")); _main(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(202); } } }
logn
338_A. Quiz
CODEFORCES
import static java.lang.Math.max; import static java.lang.Math.min; import static java.util.Arrays.copyOf; import static java.util.Arrays.deepToString; import java.io.*; import java.math.BigInteger; import java.util.*; public class C { static int[] dx = new int[] { 0, 1, 0, -1, 0 }; static int[] dy = new int[] { 0, 0, -1, 0, 1 }; static int[][] g; static int ans; static void fill() { cache[1][1] = 0; cache[1][1] = 0; cache[2][1] = 1; cache[1][2] = 1; cache[2][2] = 2; cache[2][2] = 2; cache[3][1] = 2; cache[1][3] = 2; cache[3][2] = 4; cache[2][3] = 4; cache[3][3] = 6; cache[3][3] = 6; cache[4][1] = 2; cache[1][4] = 2; cache[4][2] = 5; cache[2][4] = 5; cache[4][3] = 8; cache[3][4] = 8; cache[4][4] = 12; cache[4][4] = 12; cache[5][1] = 3; cache[1][5] = 3; cache[5][2] = 7; cache[2][5] = 7; cache[5][3] = 11; cache[3][5] = 11; cache[5][4] = 14; cache[4][5] = 14; cache[5][5] = 18; cache[5][5] = 18; cache[6][1] = 4; cache[1][6] = 4; cache[6][2] = 8; cache[2][6] = 8; cache[6][3] = 13; cache[3][6] = 13; cache[6][4] = 17; cache[4][6] = 17; cache[6][5] = 22; cache[5][6] = 22; cache[6][6] = 26; cache[6][6] = 26; cache[7][1] = 4; cache[1][7] = 4; cache[7][2] = 10; cache[2][7] = 10; cache[7][3] = 15; cache[3][7] = 15; cache[7][4] = 21; cache[4][7] = 21; cache[7][5] = 26; cache[5][7] = 26; cache[8][1] = 5; cache[1][8] = 5; cache[8][2] = 11; cache[2][8] = 11; cache[8][3] = 17; cache[3][8] = 17; cache[8][4] = 24; cache[4][8] = 24; cache[8][5] = 29; cache[5][8] = 29; cache[9][1] = 6; cache[1][9] = 6; cache[9][2] = 13; cache[2][9] = 13; cache[9][3] = 20; cache[3][9] = 20; cache[9][4] = 26; cache[4][9] = 26; cache[10][1] = 6; cache[1][10] = 6; cache[10][2] = 14; cache[2][10] = 14; cache[10][3] = 22; cache[3][10] = 22; cache[10][4] = 30; cache[4][10] = 30; cache[11][1] = 7; cache[1][11] = 7; cache[11][2] = 16; cache[2][11] = 16; cache[11][3] = 24; cache[3][11] = 24; cache[12][1] = 8; cache[1][12] = 8; cache[12][2] = 17; cache[2][12] = 17; cache[12][3] = 26; cache[3][12] = 26; cache[13][1] = 8; cache[1][13] = 8; cache[13][2] = 19; cache[2][13] = 19; cache[13][3] = 29; cache[3][13] = 29; cache[14][1] = 9; cache[1][14] = 9; cache[14][2] = 20; cache[2][14] = 20; cache[15][1] = 10; cache[1][15] = 10; cache[15][2] = 22; cache[2][15] = 22; cache[16][1] = 10; cache[1][16] = 10; cache[16][2] = 23; cache[2][16] = 23; cache[17][1] = 11; cache[1][17] = 11; cache[17][2] = 25; cache[2][17] = 25; cache[18][1] = 12; cache[1][18] = 12; cache[18][2] = 26; cache[2][18] = 26; cache[19][1] = 12; cache[1][19] = 12; cache[19][2] = 28; cache[2][19] = 28; cache[20][1] = 13; cache[1][20] = 13; cache[20][2] = 29; cache[2][20] = 29; cache[21][1] = 14; cache[1][21] = 14; cache[22][1] = 14; cache[1][22] = 14; cache[23][1] = 15; cache[1][23] = 15; cache[24][1] = 16; cache[1][24] = 16; cache[25][1] = 16; cache[1][25] = 16; cache[26][1] = 17; cache[1][26] = 17; cache[27][1] = 18; cache[1][27] = 18; cache[28][1] = 18; cache[1][28] = 18; cache[29][1] = 19; cache[1][29] = 19; cache[30][1] = 20; cache[1][30] = 20; cache[31][1] = 20; cache[1][31] = 20; cache[32][1] = 21; cache[1][32] = 21; cache[33][1] = 22; cache[1][33] = 22; cache[34][1] = 22; cache[1][34] = 22; cache[35][1] = 23; cache[1][35] = 23; cache[36][1] = 24; cache[1][36] = 24; cache[37][1] = 24; cache[1][37] = 24; cache[38][1] = 25; cache[1][38] = 25; cache[39][1] = 26; cache[1][39] = 26; cache[40][1] = 26; cache[1][40] = 26; } static void go(int n, int m, long used, long left) { // debug(Long.toBinaryString(used) + " " + Long.toBinaryString(left)); if (left == 0) { ans = max(ans, n * m - Long.bitCount(used)); return; } if (n * m - Long.bitCount(used) <= ans) return; int who = Long.numberOfTrailingZeros(left); // debug(who); for (int w : g[who]) { long nused = used | (1L << w); long nleft = left; for (int v : g[w]) { nleft &= ~(1L << v); } go(n, m, nused, nleft); } } static int solve(int n, int m) throws Exception { ans = 0; g = new int[n * m][]; for (int x = 0; x < m; x++) { for (int y = 0; y < n; y++) { int[] w = new int[5]; int cnt = 0; for (int dir = 0; dir < 5; dir++) { int nx = x + dx[dir]; int ny = y + dy[dir]; if (nx >= 0 && nx < m && ny >= 0 && ny < n) { w[cnt++] = ny * m + nx; } } g[y * m + x] = copyOf(w, cnt); } } go(n, m, 0, (1L << (n * m)) - 1); return ans; } static int[][] cache; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // debug(solve(1, 4)); // debug(solve(6, 6)); // debug(solve(7,5) == solve(5,7)); // PrintWriter out2 = new PrintWriter("file.txt"); // // cache = new int[41][41]; fill(); // // // for (int i = 1; i <= 40; i++) { // for (int j = 1; j <= i; j++) { // if (i * j <= 40) { // int k = solve(i, j); // out2.printf("cache[%d][%d] = %d;\n", i, j, k); // out2.printf("cache[%d][%d] = %d;\n", j, i, k); // // cache[i][j] = solve(i, j); // debug(i + " " + j); // } // } // } // out2.close(); int n = nextInt(); int m = nextInt(); //int res = solve(n, m); out.println(cache[n][m]); // for (int i = 1; i <= 5; i++) { // for (int j = 1; j <= 5; j++) { // assert(solve(i, j) == cache[i][j]); // //debug(i + " " + j + " " + solve(i, j)); // } // } out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static long launchTimer; static void debug(Object... o) { System.err.println(deepToString(o)); } static void setTime() { launchTimer = System.currentTimeMillis(); } static void printTime() { System.err.println(System.currentTimeMillis() - launchTimer); } static void printMemory() { System.err.println((Runtime.getRuntime().totalMemory() - Runtime .getRuntime().freeMemory()) / 1000 + "kb"); } static boolean hasMoreTokens() throws IOException { while (tok == null || !tok.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return false; } tok = new StringTokenizer(line); } return true; } static String next() throws IOException { return hasMoreTokens() ? tok.nextToken() : null; } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static BigInteger nextBig() throws IOException { return new BigInteger(next()); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.Locale; import java.util.Queue; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Solution implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(nextToken()); } long nextLong() throws Exception { return Long.parseLong(nextToken()); } double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } void solve() throws Exception { int n = nextInt(); Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } Integer[] b = a.clone(); Arrays.sort(b); int d = 0; for (int i = 0; i < n; i++) { if (!a[i].equals(b[i])) d++; } out.println(d > 2? "NO" : "YES"); } public void run() { try { Locale.setDefault(Locale.UK); in = new BufferedReader(new InputStreamReader(System.in)); // in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(System.out); // out = new PrintWriter("output.txt"); solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { out.close(); } } public static void main(String[] args) { // new Thread(null, new Solution(), "1", 1 << 28).start(); (new Solution()).run(); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class Naldbah implements Runnable { boolean isLocalMode = false; public static void main(String[] args) { new Naldbah().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(getReader()); tokenizer = null; writer = new PrintWriter(System.out); //do job doJob(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private void doJob() throws IOException { int n = nextInt(); int k = nextInt(); boolean[] primes = sieve(n + 1); for(int i=n;i>=2;i--){ if(primes[i]){ int solve = i-1; int sn=getNextD(primes,solve); int en = getNextD(primes,n); while(en!=-1&&sn+en>=solve){ if((sn+en)==solve)k--; sn=en; en=getNextD(primes,en); } } } writer.write(k<=0?"YES":"NO"); } private int getNextD(boolean[] primes, int i) { for(int p = i-1;p>=2;p--){ if(primes[p])return p; } return -1; } public boolean[] sieve(int n) { boolean[] prime=new boolean[n+1]; Arrays.fill(prime,true); prime[0]=false; prime[1]=false; int m= (int) Math.sqrt(n); for (int i=2; i<=m; i++) if (prime[i]) for (int k=i*i; k<=n; k+=i) prime[k]=false; return prime; } 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(); } public Reader getReader() throws FileNotFoundException { if (isLocalMode) { return new FileReader("input.txt"); } else { return new InputStreamReader(System.in); } } }
linear
17_A. Noldbach problem
CODEFORCES
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here long n,s,p; Scanner in=new Scanner(System.in); n=in.nextLong(); s=in.nextLong(); if(n==1 && s<=1) { System.out.print(n-1); } else if(s<n) { if(s%2!=0) {System.out.print(s/2);} else {System.out.print(s/2-1);} } else if(s==n) { if(s%2==0) {System.out.println((n/2)-1);} else {System.out.println(n/2);} } else if(s<=(2*n-1)) { System.out.print((2*n+1-s)/2); } else { System.out.print(0); } } }
constant
1023_B. Pair of Toys
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Solution { static BufferedReader br; static int[] ans; public static void main(String[] args) throws Exception{ br = new BufferedReader(new InputStreamReader(System.in)); ans = new int[8]; int n = Integer.parseInt(br.readLine()); System.out.println("?"+"1 1 "+n+" "+n); System.out.flush(); int q = Integer.parseInt(br.readLine()); cut(n); System.out.print("! "); for(int i=0 ; i<8 ; i++) System.out.print(ans[i]+" "); System.out.println(); } public static void solve(int x1, int y1, int x2, int y2, int t) throws Exception{ int l=x1, r=x2; int xx1,yy1,xx2,yy2; while(l<r){ int mid = (l+r)/2; if(query(x1,y1,mid,y2)==1) r=mid; else l=mid+1; } xx2 = l; l=x1; r=x2; while(r>l){ int mid = (l+r+1)/2; if(query(mid,y1,x2,y2)==1) l = mid; else r=mid-1; } xx1 = l; l=y1; r=y2; while(l<r){ int mid = (l+r)/2; if(query(x1,y1,x2,mid)==1) r=mid; else l=mid+1; } yy2=l; l=y1;r=y2; while(r>l){ int mid = (l+r+1)/2; if(query(x1,mid,x2,y2)==1) l=mid; else r=mid-1; } yy1 = l; ans[t] = xx1; ans[t+1] = yy1 ; ans[t+2] = xx2; ans[t+3] = yy2; // System.out.println("!"+xx1+" "+yy1+" "+xx2+" "+yy2); } public static void cut(int n) throws Exception{ int l=1, r=n; while(l<r){ int mid = (l+r)/2; if(query(1,1,n,mid)==0) l=mid+1; else r = mid; } if(query(1,1,n,l)==1 && query(1,l+1,n,n)==1){ solve(1,1,n,l,0); solve(1,l+1,n,n,4); return; } l=1;r=n; while(l<r){ int mid = (l+r)/2; if(query(1,1,mid,n)==0) l=mid+1; else r=mid; } solve(1,1,l,n,0); solve(l+1,1,n,n,4); } public static int query(int x1, int y1, int x2, int y2) throws Exception{ System.out.println("?"+x1+" "+y1+" "+x2+" "+y2); System.out.flush(); int q = Integer.parseInt(br.readLine()); return q; } }
logn
713_B. Searching Rectangles
CODEFORCES
//package que_a; import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; long mod = (long)(1e9 + 7), inf = (long)(3e18); void solve() { //SZ = sieve(); //SZ = 1000001; int q = ni(); while(q-- > 0) { long n = nl(), k = nl(); if(n <= 31) { long m = (long)(Math.pow(4, n)); long x = (m - 1) / 3; if(k > x) { out.println("NO"); continue; } long b = 0, p = 1, d = 1; x = 2; while(k > b) { n--; k -= p; m /= 4; if(m == 0) break; b += d * (m - 1) / 3; p += x; x <<= 1; d += x; } out.println((n >= 0 && k >= 0 && k <= b) ? ("YES "+ n) : "NO"); } else { out.println("YES "+ (n-1)); } } } long mp(long b, long e, long mod) { b %= mod; long r = 1; while(e > 0) { if((e & 1) == 1) { r *= b; r %= mod; } b *= b; b %= mod; e >>= 1; } return r; } //---------- I/O Template ---------- public static void main(String[] args) { new utkarsh().run(); } void run() { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.util.*; import java.io.*; public class _1036_B_DiagonalWalkingV2 { public static void main(String[] args) throws IOException { int Q = readInt(); while(Q-- > 0) { long n = readLong(), m = readLong(), k = readLong(); if(Math.max(n, m) > k) println(-1); else { long ans = k; if(n%2 != k%2) ans--; if(m%2 != k%2) ans--; println(ans); } } exit(); } final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = Read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public static String read() throws IOException { byte[] ret = new byte[1024]; int idx = 0; byte c = Read(); while (c <= ' ') { c = Read(); } do { ret[idx++] = c; c = Read(); } while (c != -1 && c != ' ' && c != '\n' && c != '\r'); return new String(ret, 0, idx); } public static int readInt() throws IOException { int ret = 0; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public static long readLong() throws IOException { long ret = 0; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public static double readDouble() throws IOException { double ret = 0, div = 1; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (c == '.') { while ((c = Read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte Read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } static void print(Object o) { pr.print(o); } static void println(Object o) { pr.println(o); } static void flush() { pr.flush(); } static void println() { pr.println(); } static void exit() throws IOException { din.close(); pr.close(); System.exit(0); } }
linear
1036_B. Diagonal Walking v.2
CODEFORCES
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Dzmitry Paulenka */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { long n = in.nextLong(); long k = in.nextLong(); if (n == 1) { out.println(0); return; } if (k * (k - 1) < 2 * (n - 1)) { out.println(-1); return; } long sq2 = 4 * k * k - 4 * k + 1 - 4 * (2 * n - 2); double sqrt = Math.sqrt(sq2); long sq = (long) sqrt; if ((sq + 1) * (sq + 1) == sq2) { sq = sq + 1; } else if ((sq - 1) * (sq - 1) == sq2) { sq = sq - 1; } if (sq*sq == sq2) { long kmin = (sq + 3) / 2; out.println(k - kmin + 1); } else { long km = Math.max(2, (long) ((sqrt + 3) / 2.0) - 2); while (((km + k - 2)*(k - km + 1) >= 2*(n-1))) { ++km; } out.println(k - km + 2); } } }
logn
287_B. Pipeline
CODEFORCES
/** * * @author Mohammad Hadi */ public class A630 { public static void main(String[] args) { System.out.println(25); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.util.*; import java.io.*; /* * Heart beats fast * Colors and promises * How to be brave * How can I love when I am afraid... */ public class Main { public static void main(String[]args) throws Exception { int n=ni(); double ke=ni(); boolean[][]a=new boolean[n][n]; for(int i=0; i<n; i++) for(int j=0; j<n; j++) a[i][j]=ni()==0; int left=n/2; int[]ldp=new int[1<<left]; int[]rdp=new int[1<<(n-left)]; int[]pow=new int[25]; pow[0]=1; for(int i=1; i<25; i++) pow[i]=pow[i-1]<<1; for(int i=0; i<pow[left]; i++) ou:for(int j=0; j<left; j++) if((i>>j)%2==0) { int te=i; for(int k=0; te>0; k++,te>>=1) if(a[j][k]&&(te&1)!=0) { ldp[i+pow[j]]=max(ldp[i+pow[j]],ldp[i]); continue ou; } ldp[i+pow[j]]=max(ldp[i+pow[j]],ldp[i]+1); } int right=n-left; for(int i=0; i<pow[right]; i++) ou:for(int j=0; j<right; j++) if((i>>j)%2==0) { int lul=j+left; int te=i; for(int k=left; te>0; k++,te>>=1) if(a[lul][k]&&(te&1)!=0) { rdp[i+pow[j]]=max(rdp[i+pow[j]],rdp[i]); continue ou; } rdp[i+pow[j]]=max(rdp[i+pow[j]],rdp[i]+1); } int maxi=0; for(int i=0; i<pow[left]; i++) { int lol=0; int te=i; for(int j=0; te>0; j++,te>>=1) if((te&1)!=0) for(int k=0; k<right; k++) if(a[j][k+left]) lol|=pow[k]; maxi=max(maxi,ldp[i]+rdp[pow[right]-1-lol]); } pr((ke*ke*(maxi-1))/(2*maxi)); System.out.println(output); } /////////////////////////////////////////// /////////////////////////////////////////// ///template from here // static final int mod=998_244_353; static final int mod=1000_000_007; static final double eps=1e-7; static final long inf=1000_000_000_000_000_000L; static class pair { int a,b; pair(){} pair(int c,int d){a=c;b=d;} @Override public int hashCode() { return (a+" "+b).hashCode(); } public boolean equals(Object c) { return (a==(((pair)c).a)&&b==(((pair)c).b)); } } public static void sort(int[][]a) { Arrays.sort(a, new Comparator<int[]>() { public int compare(int[]a,int[]b) { if(a[0]>b[0]) return 1; if(a[0]<b[0]) return -1; return 0; } }); } static interface combiner { public int combine(int a, int b); } static void pr(Object a){output.append(a+"\n");} static void pr(){output.append("\n");} static void p(Object a){output.append(a);} static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");} static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");} static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");} static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");} static void sop(Object a){System.out.println(a);} static void flush(){System.out.print(output);output=new StringBuilder();} static int ni(){return Integer.parseInt(in.next());} static long nl(){return Long.parseLong(in.next());} static String ns(){return in.next();} static double nd(){return Double.parseDouble(in.next());} static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;} static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;} static Reader in=new Reader(); static StringBuilder output=new StringBuilder(); static Random rn=new Random(); static void reverse(int[]a){for(int i=0; i<a.length/2; i++){a[i]^=a[a.length-i-1];a[a.length-i-1]^=a[i];a[i]^=a[a.length-i-1];}} static int log2n(long a) { int te=0; while(a>0) { a>>=1; ++te; } return te; } static class vectorl implements Iterable<Long> { long a[]; int size; vectorl(){a=new long[10];size=0;} vectorl(int n){a=new long[n];size=0;} public void add(long b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Long> iterator() { Iterator<Long> hola=new Iterator<Long>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Long next() { return a[cur++]; } }; return hola; } } static class vector implements Iterable<Integer> { int a[],size; vector(){a=new int[10];} vector(int n){a=new int[n];} public void add(int b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Integer> iterator() { Iterator<Integer> hola=new Iterator<Integer>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Integer next() { return a[cur++]; } }; return hola; } } static void exit(){System.out.print(output);System.exit(0);} static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;} static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;} static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;} static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;} static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;} static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;} static String pr(String a, long b){String c="";while(b>0){if(b%2==1)c=c.concat(a);a=a.concat(a);b>>=1;}return c;} static long powm(long a, long b, long mod2){long an=1;long c=a%mod2;while(b>0){if(b%2==1)an=(an*c)%mod2;c=(c*c)%mod2;b>>=1;}return an;} static long pow(long a, long b){long an=1;long c=a;while(b>0){if(b%2==1)an*=c;c*=c;b>>=1;}return an;} static int gcd(int a, int b){if(b==0)return a;return gcd(b, a%b);} static long gcd(long a, long b){if(b==0)return a;return gcd(b, a%b);} static class Reader{ public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in)); 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(); } } }
np
839_E. Mother of Dragons
CODEFORCES
import java.lang.*; import java.math.BigInteger; import java.io.*; import java.util.*; public class Solution implements Runnable{ public static BufferedReader br; public static PrintWriter out; public static StringTokenizer stk; public static boolean isStream = true; public static void main(String[] args) throws IOException { if (isStream) { br = new BufferedReader(new InputStreamReader(System.in)); } else { br = new BufferedReader(new FileReader("in.txt")); } out = new PrintWriter(System.out); new Thread(new Solution()).start(); } public void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } public String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String nextWord() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return stk.nextToken(); } public Integer nextInt() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Integer.valueOf(stk.nextToken()); } public Long nextLong() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Long.valueOf(stk.nextToken()); } public Double nextDouble() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Double.valueOf(stk.nextToken()); } public Float nextFloat() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Float.valueOf(stk.nextToken()); } public void run() { int n = nextInt(); int[] arr = new int[n]; for (int i = 0; i < n;i++) { arr[i] = nextInt(); } Arrays.sort(arr); if (arr[n-1] != 1) arr[n-1] = 1; else arr[n-1] = 2; Arrays.sort(arr); for (int i = 0; i < n; i++) { out.print(arr[i]+" "); } out.println(); out.flush(); } }
nlogn
135_A. Replacement
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; public class C{ public static void main (String[] args) throws java.lang.Exception{ Scanner scan=new Scanner(System.in); long x=scan.nextLong(), k=scan.nextLong(); long MOD = 1000000007; if(x==0){ System.out.println("0"); return; } x %= MOD; long ans= (((new myC()).fastPow(2L, k+1)*x)%MOD - (new myC()).fastPow(2L, k) + MOD + 1)% MOD; ans %= MOD; System.out.println(ans); } } class myC{ long MOD = 1000000007; long fastPow(long x, long k){ long bb=x%MOD, ans=1; while(k > 0){ if((k&1)==1){ ans=(ans*bb)%MOD; } bb=(bb*bb)%MOD; k>>=1; } return ans; } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
/* package whatever; // don't place package name! */ import java.util.*; ; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner s = new Scanner(System.in); long n = s.nextLong(); System.out.println(25); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.*; import java.util.*; public class D11 { static boolean[][] g; static int n, m; public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); n = input.nextInt(); m = input.nextInt(); g = new boolean[n][n]; for(int i = 0; i<m; i++) { int a = input.nextInt()-1, b = input.nextInt()-1; g[a][b] = g[b][a] = true; } long res = 0; map = new HashMap<Integer, Long>(); for(int i = n-1; i>=0; i--) { memo = new long[i+1][1<<(i+1)]; for(long[] A : memo) Arrays.fill(A, -1); res += count(i, i, 1<<i)/2; } out.println(res); out.close(); } static long[][] memo; static HashMap<Integer, Long> map; static long count(int at, int start, int mask) { if(memo[at][mask] != -1) return memo[at][mask]; int bits = Integer.bitCount(mask); if(at == start && bits > 2) return 1; long res = 0; for(int i = 0; i<=start; i++) { if(!g[at][i]) continue; if(i != start && (mask & (1<<i)) > 0) continue; if(i == start && bits <= 2) continue; res += count(i, start, mask | (1<<i)); } return memo[at][mask] = res; } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; public class substring { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s = input.nextLine(); Boolean found = false; int i = s.length(); while(found==false) { i--; ArrayList<String> sub = new ArrayList<String>(); for(int j = 0; j <= s.length() - i; j++) { if(sub.contains(s.substring(j, j+i))) found = true; else sub.add(s.substring(j, j+i)); } } System.out.println(i); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; public class Main { static Scanner sc = new Scanner (System.in); public static void main(String[] args) { int n = sc.nextInt(); int k = sc.nextInt(); char str[][] = new char[5][n]; for(int i = 0;i < 4;i ++){ for(int j = 0;j < n;j ++) str[i][j] = '.'; } if(k % 2 == 0){ k /= 2; for(int i = 1;i <= 2;i++){ for(int j = 1;j <= k;j++) str[i][j] = '#'; } } else{ str[1][n / 2] = '#'; if(k != 1){ int tmp = n / 2; if(k <= n - 2){ for(int i = 1;i<= (k - 1) / 2;i++){ str[1][i] = '#'; str[1][n - 1 - i] = '#'; } } else{ for(int i = 1;i <= n - 2;i++) str[1][i] = '#'; k -= n - 2; for(int i = 1;i <= k/2;i++){ str[2][i] = '#'; str[2][n - 1 - i]='#'; } } } } System.out.println("YES"); for(int i = 0;i < 4;i ++){ System.out.println(str[i]); } } }
linear
980_B. Marlin
CODEFORCES
import java.io.PrintWriter; import java.util.*; /* 10 R1C1 A1 R1C26 Z1 R1C27 AA1 R1C28 AB1 R1C52 AZ1 */ public class Main { Scanner in; PrintWriter out; boolean isFirst(String line){ int pos = 0; while( pos<line.length() && Character.isLetter(line.charAt(pos))){ pos++; } while( pos<line.length() && Character.isDigit(line.charAt(pos))){ pos++; } return pos!=line.length(); } void solve() { int n = in.nextInt(); in.nextLine(); for (int i = 1; i<=n; i++){ String line = in.nextLine(); line = line.toUpperCase(); if (isFirst(line)){ int pos = 1; long row = 0; while(Character.isDigit(line.charAt(pos))){ row*=10; row+=line.charAt(pos)-'0'; pos++; } pos++; long col = 0; while(pos<line.length() && Character.isDigit(line.charAt(pos))){ col*=10; col+=line.charAt(pos)-'0'; pos++; } StringBuilder sb = new StringBuilder(); while(col>0){ sb.append((char)('A'+((col-1)%26))); col--; col/=26; } sb = sb.reverse(); out.print(sb); out.println(row); // ��������� � 1 ������� }else{ // ��������� �� 2 ������� int pos = 0; long col = 0; while( pos<line.length() && Character.isLetter(line.charAt(pos))){ col*=26; col+=line.charAt(pos)-'A'+1; pos++; } long row = 0; while(pos<line.length() && Character.isDigit(line.charAt(pos))){ row*=10; row+=line.charAt(pos)-'0'; pos++; } out.println("R"+row+"C"+col); } } } void run() { in = new Scanner(System.in); out = new PrintWriter(System.out); try { solve(); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class OlyaAndMagicalSquare { public static void solveCase(FastIO io) { int N = io.nextInt(); long K = io.nextLong(); CountMap cm = new CountMap(); cm.increment(N, BigInteger.ONE); long rem = K; int moves = 1; int sqSize = N; while (sqSize > 0) { long need = (1L << moves) - 1; BigInteger biNeed = BigInteger.valueOf(need); cm.decrement(sqSize, biNeed); if (need > rem) { break; } cm.increment(sqSize - 1, biNeed.multiply(BigInteger.valueOf(4))); rem -= need; ++moves; --sqSize; } BigInteger biRem = BigInteger.valueOf(rem); for (int i = N; i > 0; --i) { BigInteger have = cm.getCount(i); if (have.compareTo(biRem) >= 0) { biRem = BigInteger.ZERO; break; } biRem = biRem.subtract(have); cm.decrement(i, have); cm.increment(i - 1, have.multiply(BigInteger.valueOf(4))); } if (biRem.equals(BigInteger.ZERO)) { io.printf("YES %d\n", sqSize); } else { io.println("NO"); } } private static class CountMap extends HashMap<Integer, BigInteger> { public void increment(int k, BigInteger v) { put(k, getCount(k).add(v)); } public void decrement(int k, BigInteger v) { BigInteger next = getCount(k).subtract(v); if (next.equals(BigInteger.ZERO)) { remove(k); } else { put(k, next); } } public BigInteger getCount(int k) { return getOrDefault(k, BigInteger.ZERO); } } public static void solve(FastIO io) { int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.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 nextString() { 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 nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } 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 printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
logn
1080_D. Olya and magical square
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.util.Arrays; import java.util.StringTokenizer; public class Solution { private BufferedReader cin; private PrintWriter cout; private StringTokenizer strtok; public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Solution sol = new Solution(); final boolean CONTEST = true; if (CONTEST) { sol.cin = new BufferedReader(new InputStreamReader(System.in)); sol.cout = new PrintWriter(System.out); } else { sol.cin = new BufferedReader(new FileReader("input.txt")); sol.cout = new PrintWriter("output.txt"); } sol.solve(); sol.cin.close(); sol.cout.close(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } private String nextToken() throws IOException { while (strtok == null || !strtok.hasMoreTokens()) { strtok = new StringTokenizer(cin.readLine()); } return strtok.nextToken(); } private void solve() throws IOException { int n = nextInt(); if (n % 2 == 0) { cout.println(n - 4 + " " + 4); } else { cout.println(n - 9 + " " + 9); } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.IOException; import java.util.StringTokenizer; /* * @author Tnascimento */ public class MaeDosDragoes { public static PrintWriter saida = new PrintWriter(System.out, false); public static class Escanear { BufferedReader reader; StringTokenizer tokenizer; public Escanear() { this(new InputStreamReader(System.in)); } public Escanear(Reader in) { reader = new BufferedReader(in); } String proximo() { while (tokenizer == null || !tokenizer.hasMoreElements()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(proximo()); } } public static void main(String[] args) { Escanear fastScanner = new Escanear(); int proximoInt = fastScanner.nextInt(); double proximoDouble = fastScanner.nextInt(); long[] graph = new long[proximoInt]; for(Integer i = 0; i < proximoInt; i++) { for(Integer j =0; j < proximoInt; j++) { Integer val = fastScanner.nextInt(); if (val.equals(1) || i.equals(j)) { graph[i] |= 1L << j; } } } int szLeft = proximoInt/2; int szRight = proximoInt - szLeft; int[] dp = new int[1 << szLeft]; int maxMask = 1 << szLeft; for(int mask = 1; mask <maxMask; mask++) { int curMask = mask; for(int j = 0; j < szLeft; j++) { if (((1 << j) & mask) > 0) { curMask &= graph[j + szRight] >> szRight; dp[mask] = Math.max(dp[mask], dp[mask ^ (1 << j)]); } } if (mask == curMask) { dp[mask] = Math.max(dp[mask],Integer.bitCount(mask)); } } int ans = 0; int rmaxMask = 1 << szRight; for(int mask = 0; mask < rmaxMask; mask++) { int curMask = mask; int oMask = maxMask -1; for(int j = 0; j < szRight; j++) { if (((1 << j) & mask) > 0) { curMask &= (graph[j] & (rmaxMask-1)); oMask &= graph[j] >> szRight; } } if (curMask != mask) continue; ans = Math.max(ans, Integer.bitCount(mask) + dp[oMask]); } proximoDouble/=ans; saida.println(proximoDouble * proximoDouble * (ans * (ans-1))/2); saida.flush(); } }
np
839_E. Mother of Dragons
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; 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 Lynn */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { Scanner in; PrintWriter out; public void solve(int testNumber, Scanner in, PrintWriter out) { this.in = in; this.out = out; run(); } void run() { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[][][] dis = new int[n][m][4]; int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int tmp; final int M = (int) (1e8); Algo.fill(dis, M); for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { tmp = in.nextInt(); dis[i][j][0] = tmp; dis[i][j + 1][1] = tmp; } } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { tmp = in.nextInt(); dis[i][j][2] = tmp; dis[i + 1][j][3] = tmp; } } int[][] ans = new int[n][m]; if (k % 2 == 1) { Algo.fill(ans, -1); } else { int halfK = k / 2; int[][][] dp = new int[halfK + 1][n][m]; Algo.fill(dp, M); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[0][i][j] = 0; } } for (int step = 1; step <= halfK; step++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int d = 0; d < dir.length; d++) { int toX = i + dir[d][0]; int toY = j + dir[d][1]; if (toX < 0 || toY < 0 || toX >= n || toY >= m) continue; dp[step][i][j] = Math.min(dp[step - 1][toX][toY] + 2 * dis[i][j][d], dp[step][i][j]); } } } } ans = dp[halfK]; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(ans[i][j]); out.print(' '); } out.println(""); } } } static class Algo { public static void fill(int[][] iss, int v) { for (int[] is : iss) Arrays.fill(is, v); } public static void fill(int[][][] isss, int v) { for (int[][] iss : isss) Algo.fill(iss, v); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String s) { st = new StringTokenizer(s); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; import java.util.Collections; import java.util.HashSet; /* 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 { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); ArrayList<String> s1=new ArrayList<String> (); ArrayList<String> s2=new ArrayList<String> (); ArrayList<String> s3=new ArrayList<String> (); int i; for(i=0;i<n;i++) s1.add(sc.next()); for(i=0;i<n;i++) s2.add(sc.next()); s3.addAll(s2); for(i=0;i<n;i++) { if(s2.contains(s1.get(i))) s3.remove(s1.get(i)); } System.out.println(s3.size()); } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakhar897 */ 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); APaintTheNumbers solver = new APaintTheNumbers(); solver.solve(1, in, out); out.close(); } static class APaintTheNumbers { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int arr[] = in.nextIntArray(n); Arrays.sort(arr); int ans = 0; for (int i = 0; i < n; i++) { if (arr[i] == -1) continue; else { //out.println(arr[i]); ans++; for (int j = i + 1; j < n; j++) { if (arr[j] % arr[i] == 0) arr[j] = -1; } arr[i] = -1; //out.println(arr); } } out.println(ans); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; public class cf256b { public static void main(String[] args) { Scanner in = new Scanner(System.in); long n = in.nextLong(); long x = in.nextLong()-1; long y = in.nextLong()-1; long c = in.nextLong(); long lo = 0, hi = 2*n+10; while(hi - lo > 2) { long mid = (hi+lo)/2; if(calc(n,x,y,mid) >= c) hi = mid; else lo = mid; } while(calc(n,x,y,lo) < c) lo++; System.out.println(lo); } static long calc(long n, long x, long y, long t) { long ans = (2*t)*(t+1)+1; long top = Math.max(0,t-x); long bottom = Math.max(0,t-(n-1-x)); long left = Math.max(0,t-y); long right = Math.max(0,t-(n-1-y)); ans -= top*top + bottom*bottom + left*left + right*right; long tl = Math.max(0, t - (x+y+1)); long tr = Math.max(0, t - (x+(n-1-y)+1)); long bl = Math.max(0, t - ((n-1-x)+y+1)); long br = Math.max(0, t - ((n-1-x) + (n-1-y) + 1)); ans += (tl*tl+tl)/2 + (tr*tr+tr)/2 + (bl*bl+bl)/2 + (br*br+br)/2; return ans; } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class f { static int n, m; static int start; static int[][] memo; static int[][] arr; static int[][] costs; static int[][] wrapCosts; public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); n = in.nextInt(); m = in.nextInt(); arr = new int[n][m]; costs = new int[n][n]; wrapCosts = new int[n][n]; for (int r = 0; r < n; r++) { for (int c = 0; c < m; c++) { arr[r][c] = in.nextInt(); } } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { costs[i][j] = Integer.MAX_VALUE; for (int c = 0; c < m; c++) { costs[i][j] = Math.min(costs[i][j], Math.abs(arr[i][c] - arr[j][c])); } costs[j][i] = costs[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { wrapCosts[i][j] = Integer.MAX_VALUE; for (int c = 0; c < m - 1; c++) { wrapCosts[i][j] = Math.min(wrapCosts[i][j], Math.abs(arr[i][c + 1] - arr[j][c])); } } } memo = new int[n][1 << n]; long best = 0; for (start = 0; start < n; start++) { for (int[] a : memo) Arrays.fill(a, -1); best = Math.max(best, go(start, (1 << n) - 1 - (1 << start))); } out.println(best); out.close(); } static int go(int cur, int mask) { if (mask == 0) { return wrapCosts[start][cur]; } if (memo[cur][mask] != -1) return memo[cur][mask]; int ans = 0; for (int next = 0; next < n; next++) { int bit = 1 << next; if ((mask & bit) == 0) continue; ans = Math.max(ans, Math.min(costs[cur][next], go(next, mask ^ bit))); } return memo[cur][mask] = ans; } //@ static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws IOException { if(st.hasMoreTokens()) return st.nextToken(); else st = new StringTokenizer(br.readLine()); return next(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } //# public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } //$ } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.util.*; import java.io.*; public class C { FastScanner in; PrintWriter out; boolean systemIO = true; public static void quickSort(int[] a, int from, int to) { if (to - from <= 1) { return; } int i = from; int j = to - 1; int x = a[from + (new Random()).nextInt(to - from)]; while (i <= j) { while (a[i] < x) { i++; } while (a[j] > x) { j--; } if (i <= j) { int t = a[i]; a[i] = a[j]; a[j] = t; i++; j--; } } quickSort(a, from, j + 1); quickSort(a, j + 1, to); } long mod = 1000000007; public long pow(long k) { if (k == 0) { return 1L; } if (k == 1) { return 2L; } if (k % 2 == 1) { return (2L * pow(k - 1)) % mod; } long x = pow(k / 2); return (x * x) % mod; } public void solve() { long x = in.nextLong(); if (x == 0) { out.println(0); return; } x %= mod; long k = in.nextLong(); long pow = pow(k); long ans = 1; ans = (ans - pow + mod) % mod; ans = (ans + (((2 * pow) % mod) * x) % mod) % mod; out.println(ans); } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { 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()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] args) { new C().run(); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES