src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.util.*; import java.io.*; public class P220A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; List<Integer> b = new ArrayList<Integer>(n); for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); b.add(a[i]); } Collections.sort(b); int c = 0; for (int i = 0; i < n; i++) { if (a[i] != b.get(i)) c++; } if (c == 0 || c == 2) { System.out.println("YES"); } else { System.out.println("NO"); } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.TreeSet; public class B { public static void main(String[] args) { MScanner sc = new MScanner(); PrintWriter out = new PrintWriter(System.out); long N = sc.nextLong(); long X = sc.nextLong(); long Y = sc.nextLong(); long C = sc.nextLong(); long low = 0; long high = N*2; long mid = 0; long ans = 0; while (low <= high) { mid = (low + high) >> 1; long painted = F(mid, X-1, Y-1, N); if (painted < C) { low = mid + 1; } else { ans = mid; high = mid - 1; } } out.println(ans); out.close(); } private static long F(long mid, long x, long y, long n) { long base = 2 * mid * (mid + 1) + 1; base -= excess(mid - x); base -= excess(mid - y); base -= excess(mid - (n-1-x)); base -= excess(mid - (n-1-y)); base += corner(mid - (x + y + 1)); base += corner(mid - (x + (n - y - 1) + 1)); base += corner(mid - ((n - x - 1) + y + 1)); base += corner(mid - (1 + (n - 1 - y) + (n - 1 - x))); return base; } private static long corner(long a) { if (a < 0)return 0; return (a * a + a) >> 1; } private static long excess(long thing) { if(thing<0)return 0; return thing * thing; } static class MScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public MScanner() { stream = System.in; // stream = new FileInputStream(new File("dec.in")); } int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } int[] nextInt(int N) { int[] ret = new int[N]; for (int a = 0; a < N; a++) ret[a] = nextInt(); return ret; } int[][] nextInt(int N, int M) { int[][] ret = new int[N][M]; for (int a = 0; a < N; a++) ret[a] = nextInt(M); return ret; } long nextLong() { return Long.parseLong(next()); } long[] nextLong(int N) { long[] ret = new long[N]; for (int a = 0; a < N; a++) ret[a] = nextLong(); return ret; } double nextDouble() { return Double.parseDouble(next()); } double[] nextDouble(int N) { double[] ret = new double[N]; for (int a = 0; a < N; a++) ret[a] = nextDouble(); return ret; } 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(); } String[] next(int N) { String[] ret = new String[N]; for (int a = 0; a < N; a++) ret[a] = next(); return ret; } 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(); } String[] nextLine(int N) { String[] ret = new String[N]; for (int a = 0; a < N; a++) ret[a] = nextLine(); return ret; } } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import static java.util.Arrays.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import java.util.*; import java.math.*; import java.io.*; public class A implements Runnable { String file = "input"; void init() throws IOException { //input = new BufferedReader(new FileReader(file + ".in")); input = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); } void solve() throws IOException { String s = next(); int res = 0; int L = s.length(); for(int i = 0; i < L; i++) for(int j = i + 1; j <= L; j++) { String ss = s.substring(i, j); int k = s.indexOf(ss); //print(ss, k); if(k >= 0) { if(s.substring(k + 1).indexOf(ss) >= 0) res = max(res, j - i); } } System.out.println(res); } String next() throws IOException { if(st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } void print(Object... o) { System.out.println(deepToString(o)); } void gcj(Object o) { String s = String.valueOf(o); out.println("Case #" + test + ": " + s); System.out.println("Case #" + test + ": " + s); } BufferedReader input; PrintWriter out; StringTokenizer st; int test; public static void main(String[] args) throws IOException { new Thread(null, new A(), "", 1 << 20).start(); } public void run() { try { init(); solve(); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }
cubic
23_A. You're Given a String...
CODEFORCES
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.ArrayList; import java.util.Scanner; /** * * @author Ahmed */ public class Watermelon { static class Passengers { public int floor ; public int time; public Passengers( int floor , int time){ this.floor =floor; this.time =time; } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner in = new Scanner(System.in); int x = in.nextInt() , y = in.nextInt(); ArrayList<Passengers> list = new ArrayList<>(); for(int i = 1 ; i <= x ; ++i){ list.add(new Passengers(in.nextInt(), in.nextInt())); } int sum = 0 ; for(int i = list.size() - 1 ; i >= 0 ; --i) { int s = y - list.get(i).floor; sum = sum + s ; if(sum < list.get(i).time) { sum = sum + ( list.get(i).time - sum); } y = list.get(i).floor; } if( list.get(list.size() - 1).floor != 0){ sum = sum + (list.get(0).floor); } System.out.println(sum); } }
linear
608_A. Saitama Destroys Hotel
CODEFORCES
import java.util.Scanner; public class codef8 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int beacon[] = new int[1000001]; int pos[] = new int[num]; for (int i = 0; i < num; i++) { int position = sc.nextInt(); beacon[position] = sc.nextInt(); pos[i] = position; } int dp[] = new int[1000001]; int max = 1; if (beacon[0] != 0) dp[0] = 1; for (int i = 1; i <= 1000000; i++) { if (beacon[i] == 0) { dp[i] = dp[i-1]; } else { int j = i - beacon[i] - 1; if (j < 0) { dp[i] = 1; } else { dp[i] = dp[j] + 1; } } max = Math.max(max, dp[i]); } System.out.println(num-max); } }
linear
608_C. Chain Reaction
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Scanner; public class CF_2020_GlobalRound_E { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static InputReader reader; static long[][] binom; static void buildBinom(int N){ int MAX=N+1; binom=new long[MAX+1][]; for (int i=0;i<MAX+1;i++) binom[i]=new long[i+1]; binom[0][0]=1; for (int i=1;i<MAX;i++){ binom[i][0]=1; binom[i][i]=1; for (int j=0;j<i;j++) { binom[i+1][j+1]=(binom[i][j]+binom[i][j+1])%mod; } //log(binom[i]); } log("binom done"); } static long mod; static long solve(int n) { long[] pow2=new long[n+1]; pow2[0]=1; for (int i=1;i<=n;i++) { pow2[i]=pow2[i-1]<<1; while (pow2[i]>=mod) pow2[i]-=mod; } buildBinom(n); long[][] dp=new long[n+1][n+1]; dp[1][1]=1; for (int i=1;i<=n;i++) { dp[i][i]=pow2[i-1]; //log("base:"+dp[i][i]); for (int j=1;j<i-1;j++){ int me=i-j-1; for (int cn=1;cn<=j;cn++) { //log("j:"+j+" cn:"+cn+" dp:"+dp[j][cn]); //log("perm:"+binom[cn+me][cn]); long a=dp[j][cn]*binom[cn+me][cn]; if (a>=mod) a%=mod; a*=pow2[me-1]; if (a>=mod) a%=mod; dp[i][cn+me]+=a; if (dp[i][cn+me]>=mod) dp[i][cn+me]-=mod; } } } long ans=0; for (int i=n/2;i<=n;i++) { ans+=dp[n][i]; ans%=mod; } return ans; } public static void main(String[] args) throws Exception { log(400*400*400); reader=new InputReader(System.in); int n=reader.readInt(); mod=reader.readInt(); System.out.println(solve(n)); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res=new StringBuilder(); do { res.append((char)c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.StringTokenizer; public class Solution { static final int INF = (int) 1e9; static final int mod = (int) (1e9 + 7); static final short UNCALC = -1; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int[] a = sc.nextIntArray(n); long[] cum = new long[n]; cum[0] = a[0]; for (int i = 1; i < n; i++) cum[i] = a[i] + cum[i - 1]; HashMap<Long, ArrayList<Pair>> hm = new HashMap<>(); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { long cur = get(cum, i, j); if (!hm.containsKey(cur)) hm.put(cur, new ArrayList<>()); hm.get(cur).add(new Pair(i, j)); } } int max = 0; StringBuilder ans = new StringBuilder(); for (long sum : hm.keySet()) { ArrayList<Pair> cur = hm.get(sum); Collections.sort(cur); int poss = 0; int r = -1; StringBuilder sb = new StringBuilder(); for (int i = 0; i < cur.size(); i++) { if (cur.get(i).left > r) { poss++; r = cur.get(i).right; sb.append(cur.get(i)); } } if (poss> max){ max = poss; ans = sb; } } out.println(max); out.println(ans); out.flush(); out.close(); } static long get(long[] a, int i, int j) { return a[j] - (i > 0 ? a[i - 1] : 0); } static class Pair implements Comparable<Pair> { int left, right; public Pair(int left, int right) { this.left = left; this.right = right; } @Override public int compareTo(Pair o) { return right - o.right; } @Override public String toString() { return (left + 1) + " " + (right + 1) + "\n"; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.*; import static java.lang.Math.*; import java.util.*; import java.util.function.*; import java.lang.*; public class Main { final static boolean debug = false; final static String fileName = ""; final static boolean useFiles = false; public static void main(String[] args) throws FileNotFoundException { long start; if (debug) start = System.nanoTime(); InputStream inputStream; OutputStream outputStream; if (useFiles) { inputStream = new FileInputStream(fileName + ".in"); outputStream = new FileOutputStream(fileName + ".out"); } else { inputStream = System.in; outputStream = System.out; } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(in, out); solver.solve(); if(debug) out.println((System.nanoTime() - start) / 1e+9); out.close(); } } 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 double nextDouble() { return Double.parseDouble(next()); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public byte nextByte() { return Byte.parseByte(next()); } byte[][] nextBitMatrix(int n, int m) { byte[][] a = new byte[n][m]; for (int i = 0; i < n; i++) { String s = next(); for (int j = 0; j < m; j++) { a[i][j] = (byte) (s.charAt(j) - '0'); } } return a; } char[][] nextCharMatrix(int n, int m) { char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { String s = next(); for (int j = 0; j < m; j++) { a[i][j] = s.charAt(j); } } return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } } class Task { boolean get(int mask, int i){ return (mask & (1 << i)) > 0; } int zero(int mask, int i){ return mask & (~(1 << i)); } public void solve() { int n = in.nextInt(); double[][] a = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) a[i][j] = in.nextDouble(); } double[] d = new double[1 << n]; d[(1 << n) - 1] = 1; for (int mask = (1 << n) - 1; mask >= 0; mask--) { int bits = Integer.bitCount(mask); double transfer = 1.0 / (bits * (bits - 1) / 2); for (int i = 0; i < n; i++) { if (get(mask, i)) { for (int j = i + 1; j < n; j++) { if (get(mask, j)) { d[zero(mask, j)] += a[i][j] * transfer * d[mask]; d[zero(mask, i)] += a[j][i] * transfer * d[mask]; } } } } } for(int i = 0; i < n; i++) out.print(d[1 << i] + " "); } private InputReader in; private PrintWriter out; Task(InputReader in, PrintWriter out) { this.in = in; this.out = out; } }
np
16_E. Fish
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; public class a { private void solve() throws Exception { int n = nextInt(), t = nextInt(); int[] x = new int[n], a = new int[n]; for (int i = 0; i < n; ++i){ x[i] = nextInt(); a[i] = nextInt(); } for (int i = 0; i < n; ++i) for (int j = 0; j < n - 1; ++j){ if (x[j] > x[j + 1]){ int tmp = x[j]; x[j] = x[j + 1]; x[j + 1] = tmp; tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } int res = 2; for (int i = 1; i < n; ++i){ int betw = (x[i] - x[i - 1]) * 2 - a[i] - a[i - 1]; if (betw == t * 2) ++res; else if (betw > t * 2) res += 2; } out.print(res); } public void run() { try { solve(); } catch (Exception e) { NOO(e); } finally { out.close(); } } PrintWriter out; BufferedReader in; StringTokenizer St; void NOO(Exception e) { e.printStackTrace(); System.exit(1); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String nextToken() { while (!St.hasMoreTokens()) { try { String line = in.readLine(); St = new StringTokenizer(line); } catch (Exception e) { NOO(e); } } return St.nextToken(); } private a(String name) { try { in = new BufferedReader(new FileReader(name + ".in")); St = new StringTokenizer(""); out = new PrintWriter(new FileWriter(name + ".out")); } catch (Exception e) { NOO(e); } } private a() { try { in = new BufferedReader(new InputStreamReader(System.in)); St = new StringTokenizer(""); out = new PrintWriter(System.out); } catch (Exception e) { NOO(e); } } public static void main(String[] args) { new a().run(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = in.readLine(); int n = line.length(); int maxlenght = 0; for (int i = 0; i < n; i++) { int j = line.indexOf(line.charAt(i), i + 1); while (j != -1) { int k = i; int l = j; while (k < n && l < n && line.charAt(k) == line.charAt(l)) { k++; l++; } if (k - i > maxlenght) { maxlenght = k - i; } j = line.indexOf(line.charAt(i), j + 1); } } System.out.println(maxlenght); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author George Marcus */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { long a = in.nextLong(); long b = in.nextLong(); long res = 0; while(a > 1 && b > 1) { if(a < b) { res += b / a; b %= a; } else { res += a / b; a %= b; } } if(a == 1) res += b; else res += a; out.println(res); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public long nextLong() { return Long.parseLong(nextString()); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.FileInputStream; import java.io.InputStream; import java.util.Iterator; import java.util.LinkedList; import java.util.Scanner; import java.util.regex.Pattern; //Stephen Fulwider //Parser class for efficient input in Java // Use just as you would Scanner. // Make sure any method that uses this class throws Exception. // Email any bugs or problems found to knightry@gmail.com class Parser { final private int BUFFER_SIZE = 1 << 16; private java.io.DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parser(java.io.InputStream in) { din = new java.io.DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public int nextInt() throws Exception { byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); int ret = 0; do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); bufferPointer--; if (neg) return -ret; return ret; } public long nextLong() throws Exception { byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); long ret = 0; do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); bufferPointer--; if (neg) return -ret; return ret; } public double nextDouble() throws Exception { byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); boolean seenDot = false; double div = 1; double ret = 0; do { if (c == '.') seenDot = true; else { if (seenDot) div *= 10; ret = ret * 10 + c - '0'; } c = read(); } while (c > ' '); bufferPointer--; ret /= div; if (neg) return -ret; return ret; } public char nextChar() throws Exception { byte c = read(); while (c <= ' ') c = read(); return (char) c; } public String next() throws Exception { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret.append((char) c); c = read(); } while (c > ' '); bufferPointer--; return ret.toString(); } // read a string into an ALREADY ALLOCATED array, returns the number of characters read public int next(char[] ret) throws Exception { byte c = read(); while (c <= ' ') c = read(); int bRead = 0; do { ret[bRead++] = (char) c; c = read(); } while (c > ' '); bufferPointer--; return bRead; } public String nextLine() throws Exception { StringBuilder ret = new StringBuilder(); byte c = read(); while (c != '\r' && c != '\n' && c != -1) { ret.append((char) c); c = read(); } if (c == '\r') read(); return ret.toString(); } public boolean hasNext() throws Exception { byte c; do { c = read(); if (c == -1) { bufferPointer--; return false; } } while (c <= ' '); bufferPointer--; return true; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); if (bytesRead == -1) return -1; return buffer[bufferPointer++]; } } class Printer { final private int BUFFER_SIZE = 1 << 16; private java.io.DataOutputStream dout; private byte[] buffer; private int bufferPointer; Printer(java.io.OutputStream out) throws Exception { dout = new java.io.DataOutputStream(out); buffer = new byte[BUFFER_SIZE]; bufferPointer = 0; } public void println() throws Exception { write((byte) '\n'); } // print int public void println(int n) throws Exception { print(n); println(); } public void print(int n) throws Exception { if (n >= 0) print(n, true); else { write((byte) '-'); print(-n, true); } } private void print(int n, boolean first) throws Exception { if (n == 0) { if (first) write((byte) (n + '0')); } else { print(n / 10, false); write((byte) ((n % 10) + '0')); } } // print long public void println(long n) throws Exception { print(n); println(); } public void print(long n) throws Exception { if (n >= 0) print(n, true); else { write((byte) '-'); print(-n, true); } } private void print(long n, boolean first) throws Exception { if (n == 0) { if (first) write((byte) (n + '0')); } else { print(n / 10, false); write((byte) ((n % 10) + '0')); } } // print double public void println(double d) throws Exception { print(d); println(); } public void print(double d) throws Exception { print("double printing is not yet implemented!"); } // print char public void println(char c) throws Exception { print(c); println(); } public void print(char c) throws Exception { write((byte) c); } // print String public void println(String s) throws Exception { print(s); println(); } public void print(String s) throws Exception { int len = s.length(); for (int i = 0; i < len; i++) print(s.charAt(i)); } public void close() throws Exception { flushBuffer(); } private void flushBuffer() throws Exception { dout.write(buffer, 0, bufferPointer); bufferPointer = 0; } private void write(byte b) throws Exception { buffer[bufferPointer++] = b; if (bufferPointer == BUFFER_SIZE) flushBuffer(); } } public class Main { public static void main(String[] args) throws Exception { new Main(); } final int oo = (int)1e9; // InputStream stream = new FileInputStream("in"); InputStream stream = System.in; Parser in = new Parser(stream); Printer out = new Printer(System.out); Printer err = new Printer(System.err); long start_time = System.nanoTime(); // PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); // PrintWriter err = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err))); int Sn; char[] S = new char[1000]; char[] B = new char[1000]; Main() throws Exception { for (int T=in.nextInt(); T-->0; ) { Sn = in.next(S); if (matchRxCy()) toLet(); else toNum(); } long end_time = System.nanoTime(); err.println("Time: " + ((end_time-start_time)/1e9) + "(s)."); if (stream instanceof FileInputStream) { err.println("~~~~~~~~~~~~~~~~~~~~~~~~~~!!!!!!!!!!!!!!!!!!!!!!!!!~~~~~~~~~~~~~~~~~~~~~~~~~~"); err.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~CHANGE INPUT STREAM~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); err.println("~~~~~~~~~~~~~~~~~~~~~~~~~~!!!!!!!!!!!!!!!!!!!!!!!!!~~~~~~~~~~~~~~~~~~~~~~~~~~"); } out.close(); err.close(); } boolean matchRxCy() { boolean ok=S[0]=='R'&&(S[1]>='0'&&S[1]<='9'); if (!ok) return false; int i; for (i=2; i<Sn && S[i]!='C'; ++i); return i<Sn; } void toLet() throws Exception { int r = 0; int i=1; while (S[i]!='C') r=r*10+S[i++]-'0'; int c = 0; ++i; while (i<Sn) c=c*10+S[i++]-'0'; int bi=0; while (c>0) { B[bi++]=(char)((c-1)%26+'A'); c=(c-1)/26; } for (int j=bi-1; j>=0; --j) out.print(B[j]); i=1; while (S[i]!='C') out.print(S[i++]); out.println(); } void toNum() throws Exception // this works fine now, i think { int c=0; int i=0; int v=1; while (Character.isLetter(S[i++])) v*=26; v/=26; i=0; while (Character.isLetter(S[i])) { c+=v*(S[i++]-'A'+1); v/=26; } int r=0; while (i<Sn) r=r*10+S[i++]-'0'; out.print('R'); out.print(r); out.print('C'); out.print(c); out.println(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.*; import java.util.*; import java.util.Queue; import java.util.LinkedList; import java.util.Stack; public class Main { @SuppressWarnings("unchecked") public static void main(String args[])throws IOException { Reader ob=new Reader(); Writer out=new Writer(System.out); Random oo=new Random(); long k=ob.nL(),ans=0,p=9,num=0; for(int i=1;i<18;i++) { if(num+i*p<k) { num+=i*p;p*=10; ans=0; for(int j=0;j<i;j++) ans=9+ans*10; } else { long left=k-num; long r=left/i; left-=r*i; ans+=r; if(left>0) { String s=Long.toString(ans+1); out.pln(s.charAt((int)left-1)); } else { String s=Long.toString(ans); out.pln(s.charAt(i-1-(int)left)); } break; } } out.flush(); } static void sort(int a[]) { RA(a); Arrays.sort(a); } public static Pairs[] RA(Pairs [] array){ Random rgen = new Random(); // Random number generator for (int i=0; i<array.length; i++) { int randomPosition = rgen.nextInt(array.length); Pairs temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } public static int[] RA(int [] array){ Random rgen = new Random(); // Random number generator for (int i=0; i<array.length; i++) { int randomPosition = rgen.nextInt(array.length); int temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } static void sort(long a[]) { RA(a); Arrays.sort(a); } public static long[] RA(long [] array){ Random rgen = new Random(); // Random number generator for (int i=0; i<array.length; i++) { int randomPosition = rgen.nextInt(array.length); long temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } static void sort(String a[]) { RA(a); Arrays.sort(a); } public static String[] RA(String [] array){ Random rgen = new Random(); // Random number generator for (int i=0; i<array.length; i++) { int randomPosition = rgen.nextInt(array.length); String temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } static long inverse(long x, long p) { return pow(x, p - 2, p); } static boolean isPrime(long n) { long h=(long)Math.sqrt(n); for(long i=2;i<=h;i++) if(n%i==0) return false; return true&&n!=1; } static long gcd(long a,long b) { if(a<b) return gcd(b,a); else if(b==0) return a; else return gcd(b,a%b); } static long pow(long a,long b,long mod){ if(b == 0) return 1; long t = pow(a,b>>1,mod); t = (t * t) % mod; if((b & 1) == 1) t = (t * a); if(t >= mod) t %= mod; return t; } static long pow(long a,long b){ if(b == 0) return 1; long t = pow(a,b>>1); t = (t * t); if((b & 1) == 1) t = (t * a); return t; } static void seive(int n,int prime[])//1 for prime -1 for not prime { for(int i=2;i<=n;i++) if(prime[i]==0) { prime[i]=1; for(int j=2;j*i<=n;j++) prime[j*i]=-1; } } static int max(int ...a) { int m=a[0]; for(int i=0;i<a.length;i++) m=Math.max(m,a[i]); return m; } static long max(long ...a) { long m=a[0]; for(int i=0;i<a.length;i++) m=Math.max(m,a[i]); return m; } static int min(int ...a) { int m=a[0]; for(int i=0;i<a.length;i++) m=Math.min(m,a[i]); return m; } static long min(long ...a) { long m=a[0]; for(int i=0;i<a.length;i++) m=Math.min(m,a[i]); return m; } static class Pair<T1,T2> { T1 x;T2 y; Pair(T1 xx,T2 yy) { x=xx; y=yy; } } static class Writer { private final PrintWriter p; Writer(OutputStream o) { p = new PrintWriter(new BufferedWriter(new OutputStreamWriter(o))); } void p(Object... o1) { for (Object o11 : o1) { p.print(o11 + "" ); } } <T>void pa(T a[]) { for(T i:a) System.out.print(i+" "); System.out.println(); } void p(String s) { p.print(s); } void pln(Object... o1) { p(o1); p.println(); } void flush() { p.flush(); } void close() { p.close(); } } static class Reader { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; int flag=0; FileReader file; Reader() { } Reader(String x)throws IOException { flag=1; file=new FileReader(x); } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nl() { 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 n() { 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 nL() { 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 nI() { 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 int[] NIA(int n) //nextINtArray { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nI(); } return arr; } public int[] NIA1(int n) //nextINtArray { int[] arr = new int[n+1]; for (int i = 1; i <=n; i++) { arr[i] = nI(); } return arr; } public long[] NLA(int n) //nextLongArray { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nL(); } return arr; } public long[] NLA1(int n) //nextLongArray { long[] arr = new long[n+1]; for (int i = 1; i <=n; i++) { arr[i] = nL(); } 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; } } static class DSU { int a[],size[],c=1,m; HashMap<String,Integer> hm=new HashMap<String,Integer>(); DSU(int n) { a=new int[n+1]; m=n; size=new int[n+1]; for(int i=1;i<=n;i++) { a[i]=i; size[i]=1; } } void add(String x,int i) { hm.put(x,i); } int find(int n) { while(a[n]!=n) { a[n]=a[a[n]]; n=a[n]; } return n; } int[] eval() { int y[]=new int[m+1]; for(int i=1;i<=m;i++) y[find(i)]++; return y; } void union(int a1,int b) { int x=find(a1); int y=find(b); if(size[x]>size[y]) { a[y]=x; size[x]+=size[y]; } else { a[x]=y; size[y]+=size[x]; } } //System.out.println(Arrays.toString(a)); } class Segment { int sum[]; void build(int a[],int v,int l,int r) { if(l==r) sum[v]=a[l]; else { int m=(l+r)/2; build(a,v*2,l,m); build(a,2*v+1,m+1,r); sum[v]=sum[v*2]+sum[2*v+1]; } } void update(int a[],int l,int r,int x,int v,int y) { if(l==r&&r==y) sum[v]+=x; else if(l>y||y>r) return; else { int m=(l+r)/2; update(a,l,m,x,2*v,y); update(a,m+1,r,x,2*v+1,y); sum[v]=sum[2*v]+sum[2*v+1]; } } int query(int v,int l,int r,int x,int y) { if(x>r||y<l) return 0; else if(x<=l&&r<=y) return sum[v]; else { int m=(l+r)/2; return query(2*v,l,m,x,y)+query(2*v+1,m+1,r,x,y); } } } static class Trie { Trie child[]=new Trie[26]; int count=0; } /* void insert(String a) { Trie tmp=root; for(int i=0;i<a.length();i++) { int v=a.charAt(i)-'a'; if(tmp.child[v]==null) { tmp.child[v]=new Trie(); } tmp=tmp.child[v]; } if(tmp.count==0) r++; tmp.count=1; }*/ } class Pairs implements Comparable<Pairs> { int x,y;String z; Pairs(int a,int b) { x=a;y=b; } @Override public int compareTo(Pairs a) { if(a.x>this.x||(a.x==this.x&&a.y<this.y)||(a.x==this.x&&a.y==this.y&&(a.z).equals("BhayanakMaut"))) return 1; else return -1; } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; public class Solution { private BufferedReader in; private PrintWriter out; private StringTokenizer st; void solve() throws IOException { double a = nextDouble(); double v = nextDouble(); double l = nextDouble(); double d = nextDouble(); double w = nextDouble(); if (w > v) { w = v; } double ans1 = 0.; double v1; { double l_ = 0., r_ = 1e+9; for (int it = 0; it < 100; ++it) { double mid = (l_ + r_) / 2.; double V = a * mid; double t1 = (V + w) / 2. / a; double t2 = mid - t1; t1 = Math.min(t1, v / a); t2 = Math.min(t2, (v - w) / a); if (V < w) { t1 = mid; t2 = 0.; } double dist = t1 * t1 * a / 2. + t2 * (w + t2 * a / 2.) + v * (mid - t1 - t2); if (dist < d) { l_ = mid; } else { r_ = mid; } } ans1 = (l_ + r_) / 2.; v1 = Math.min(ans1 * a, w); } double ans2 = 0.; { double tSp = (v - v1) / a; double l_ = 0., r_ = 1e+9; for (int it = 0; it < 100; ++it) { double mid = (l_ + r_) / 2.; double dist = Math.min(tSp, mid) * (v1 + Math.min(tSp, mid) * a / 2.); dist += (mid - Math.min(tSp, mid)) * v; if (dist < l - d) { l_ = mid; } else { r_ = mid; } } ans2 = (l_ + r_) / 2.; } out.println(ans1 + ans2); } Solution() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new Solution(); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.util.*; public class E { static InputStream is; //String INPUT = ""; public static void main(String[] args) throws IOException { is = System.in; int n = ni(); int k = ni(); int[][] aj = new int[n][n]; for (int i = 0; i < aj.length; i++) { aj[i] = na(n); } int F = (n+1)/2; int B = n-F; int[] spanftf = new int[F]; int[] spanftb = new int[F]; for(int i =0; i < F; i++){ for(int j =0; j < F; j++){ if(i == j || aj[i][j] == 1){ spanftf[i] |= 1<<j; } } for(int j =0; j< B; j++){ if(aj[i][F+j] == 1){ spanftb[i] |= 1<<j; } } } int[] maxes = new int[1<<B]; for(int bm = 0; bm < (1<<F); bm++){ int anded = (1<<F)-1; int spanToBack = (1<<B)-1; for(int i =0; i < F; i++){ if((1<<i & bm) != 0){ anded &= spanftf[i]; spanToBack &= spanftb[i]; } } if((anded & bm) == bm){ maxes[spanToBack] = Math.max(maxes[spanToBack], Integer.bitCount(bm)); } } int[] spanbtb = new int[B]; for(int i =0; i < B; i++){ for(int j =0; j< B; j++){ if(aj[F+i][F+j] == 1 || i == j){ spanbtb[i] |= 1<<j; } } } boolean[] isgood = new boolean[1<<B]; for(int bm =0; bm < (1<<B); bm++){ int anded = (1<<B)-1; for(int i =0; i < B; i++){ if((1<<i & bm) != 0){ anded &= spanbtb[i]; } } if((anded & bm) == bm){ isgood[bm] = true; } } bybc[] tosort = new bybc[1<<B]; for (int i = 0; i < tosort.length; i++) { tosort[i]= new bybc(i); } Arrays.sort(tosort); int best = 1; for (int i = 0; i < tosort.length; i++) { int at =tosort[i].mask; if(isgood[at]){ best = Math.max(best, maxes[at]+Integer.bitCount(at)); } for(int j =0; j < B; j++){ if((1<<j & at) != 0){ int to = at - (1<<j); maxes[to] = Math.max(maxes[to], maxes[at]); } } } //System.out.println("best: " + best); double ans= best*(best-1)/2.0 * (k*k/(double)(best*best)); System.out.println(ans); } static class bybc implements Comparable<bybc>{ int mask; public bybc(int mask) { super(); this.mask = mask; } @Override public int compareTo(bybc o) { return Integer.bitCount(o.mask) - Integer.bitCount(mask); } } private static byte[] inbuf = new byte[1024]; public static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double nd() { return Double.parseDouble(ns()); } private static char nc() { return (char)skip(); } private static String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private static int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private static int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } //private boolean oj = System.getProperty("ONLINE_JUDGE") != null; //private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
np
839_E. Mother of Dragons
CODEFORCES
import java.io.OutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.FileInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("input.txt"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("output.txt"); } catch (IOException e) { throw new RuntimeException(e); } FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int m = in.nextInt(); int p = in.nextInt(); int[] x = new int[p]; int[] y = new int[p]; for (int i = 0; i < p; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } int X = x[0]; int Y = y[0]; int D = -1; for (int dx = 1; dx <= n; dx++) { int x1 = dx; int y1 = 1; int xx = 0; int yy = 0; int minD = Integer.MAX_VALUE; for (int j = 0; j < p; j++) { int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]); if (d < minD) { minD = d; xx = x1; yy = y1; } } if (D < minD && minD != 0 && minD != Integer.MAX_VALUE) { D = minD; X = xx; Y = yy; } } for (int dx = 1; dx <= n; dx++) { int x1 = dx; int y1 = m; int xx = 0; int yy = 0; int minD = Integer.MAX_VALUE; for (int j = 0; j < p; j++) { int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]); if (d < minD) { minD = d; xx = x1; yy = y1; } } if (D < minD && minD != 0 && minD != Integer.MAX_VALUE) { D = minD; X = xx; Y = yy; } } for (int dy = 1; dy <= m; dy++) { int x1 = 1; int y1 = dy; int xx = 0; int yy = 0; int minD = Integer.MAX_VALUE; for (int j = 0; j < p; j++) { int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]); if (d < minD) { minD = d; xx = x1; yy = y1; } } if (D < minD && minD != 0 && minD != Integer.MAX_VALUE) { D = minD; X = xx; Y = yy; } } for (int dy = 1; dy <= m; dy++) { int x1 = n; int y1 = dy; int xx = 0; int yy = 0; int minD = Integer.MAX_VALUE; for (int j = 0; j < p; j++) { int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]); if (d < minD) { minD = d; xx = x1; yy = y1; } } if (D < minD && minD != 0 && minD != Integer.MAX_VALUE) { D = minD; X = xx; Y = yy; } } for (int i = 1; i <= Math.min(m, n); i++) { int x1 = i; int y1 = i; int xx = 0; int yy = 0; int minD = Integer.MAX_VALUE; for (int j = 0; j < p; j++) { int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]); if (d < minD) { minD = d; xx = x1; yy = y1; } } if (D < minD && minD != 0 && minD != Integer.MAX_VALUE) { D = minD; X = xx; Y = yy; } } for (int i = 1, ii = m; i <= n && ii >= 1; i++, ii--) { int x1 = i; int y1 = ii; int xx = 0; int yy = 0; int minD = Integer.MAX_VALUE; for (int j = 0; j < p; j++) { int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]); if (d < minD) { minD = d; xx = x1; yy = y1; } } if (D < minD && minD != 0 && minD != Integer.MAX_VALUE) { D = minD; X = xx; Y = yy; } } out.println(X + " " + Y); } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static long[][] memo; static boolean[][] adjMat; static int N, endNode; static ArrayList<Integer>[] bits; static long dp(int idx, int msk) //complexity = N * 2^(N + 1) { if(memo[idx][msk] != -1) return memo[idx][msk]; long ret = adjMat[idx][endNode] ? 1 : 0; for(int i = 0, sz = bits[msk].size(); i < sz; ++i) { int j = bits[msk].get(i); if(j > endNode) break; if(adjMat[idx][j]) ret += dp(j, msk | 1 << j); } return memo[idx][msk] = ret; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); adjMat = new boolean[N][N]; bits = new ArrayList[1 << N]; for(int i = 0; i < 1 << N; ++i) { bits[i] = new ArrayList<>(1); for(int j = 0; j < N; ++j) if((i & 1 << j) == 0) bits[i].add(j); } int M = sc.nextInt(); while(M-->0) { int u = sc.nextInt() - 1, v = sc.nextInt() - 1; adjMat[u][v] = adjMat[v][u] = true; } long ans = 0; for(int i = N; i > 1; --i) { memo = new long[i][1 << i]; for(long[] x: memo) Arrays.fill(x, -1); ans += dp(endNode = i - 1, 1 << endNode); } for(int i = 0; i < N; ++i) for(int j = i + 1; j < N; ++j) if(adjMat[i][j]) --ans; out.println(ans >> 1); out.flush(); out.close(); } 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();} } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class TemnayaAssambleya implements Runnable { public static void main(String[] args) { new Thread(new TemnayaAssambleya()).run(); } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer in; PrintWriter out = new PrintWriter(System.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()); } int[] l; int[] ln; int[] pw; int[] p; int A; double max = 0; public void gen(int n, int k) { if (n == 0) { n = p.length; p[0] = k; for (int i = 0; i < n; i++) { ln[i] = l[i] + p[i] * 10; if (ln[i] > 100) ln[i] = 100; } double ans = 0; for (int mask = 0; mask < 1 << n; mask++) { int z = 0; double pos = 1; int power = 0; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) > 0) { z++; pos *= ln[i] * 1. / 100; } else { pos *= (100 - ln[i]) * 1. / 100; power += pw[i]; } } if (z > n / 2) { ans += pos; } else { ans += pos * A / (A + power); } } max = Math.max(ans, max); return; } for (int i = 0; i <= Math.min(k, 10 - l[n] / 10); i++) { p[n] = i; gen(n - 1, k - i); } } public void solve() throws IOException { int n = nextInt(); int k = nextInt(); A = nextInt(); p = new int[n]; pw = new int[n]; l = new int[n]; ln = new int[n]; for (int i = 0; i < n; i++) { pw[i] = nextInt(); l[i] = nextInt(); } gen(n - 1, k); out.println(max); } public void run() { try { solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ static ArrayList a[]=new ArrayList[200001]; static int Count(int a[][],int n) { dsu d=new dsu(n); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(a[i][j]==0) { d.union(i, j); } } } int cnt=0; boolean chk[]=new boolean [n]; for(int i=0;i<n;i++) { int p=d.root(i); if(!chk[p]) { chk[p]=true; cnt++; } } return cnt; } public void solve () { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n=in.nextInt(); int a=in.nextInt(); int b=in.nextInt(); if(a==1 || b==1) { int ans[][]=new int [n][n]; int temp=(a==1)?b:a; for(int i=1;i<=n-temp;i++) { ans[i][i-1]=1; ans[i-1][i]=1; } int freq=Count(ans,n); if(freq!=1) { pw.println("NO"); } else { pw.println("YES"); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) { pw.print(0); } else pw.print((ans[i][j]+((temp==b)?1:0))%2); } pw.println(); } } } else { pw.print("NO"); } pw.flush(); pw.close(); } public static void main(String[] args) throws Exception { new Thread(null,new Runnable() { public void run() { new Main().solve(); } },"1",1<<26).start(); } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public 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 void extended(int a,int b) { if(b==0) { d=a; p=1; q=0; } else { extended(b,a%b); int temp=p; p=q; q=temp-(a/b)*q; } } public static long[] shuffle(long[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; long 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 HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } 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); } static class pair implements Comparable<pair> { Integer x; Long y; pair(int x,long y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } } class pair implements Comparable<pair> { Integer x; Long y; pair(int x,long y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } class dsu{ int parent[]; dsu(int n){ parent=new int[n+1]; for(int i=0;i<=n;i++) { parent[i]=i; } } int root(int n) { while(parent[n]!=n) { parent[n]=parent[parent[n]]; n=parent[n]; } return n; } void union(int _a,int _b) { int p_a=root(_a); int p_b=root(_b); parent[p_a]=p_b; } boolean find(int a,int b) { if(root(a)==root(b)) return true; else return false; } }
quadratic
990_D. Graph And Its Complement
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; public class RENAMETHISBITCH { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { int n = sc.nextInt(); BigInteger m = sc.nextBigInteger(); System.out.println(m.mod(BigInteger.valueOf(2).pow(n))); } catch (Exception e) { e.printStackTrace(); } } }
constant
913_A. Modular Exponentiation
CODEFORCES
import java.util.*; public class A { public static int palin(String str) { int flag=0; int l=str.length(); for(int i=0;i<l/2;i++) { if(str.charAt(i)!=str.charAt(l-i-1)) { flag=1; break; } } if(flag==1) return 0; else return 1; } public static void main(String args[]) { Scanner sc=new Scanner(System.in); String str=sc.next(); HashSet<Character> hs=new HashSet<>(); for(int i=0;i<str.length();i++) { hs.add(str.charAt(i)); } if(hs.size()==1) System.out.println(0); else if(palin(str)==0) System.out.println(str.length()); else System.out.println(str.length()-1); } }
linear
981_A. Antipalindrome
CODEFORCES
import java.io.*; import java.util.*; public class Main { public void solve() { int n = ni(); int a = ni(); int b = ni(); long ans = 0; HashMap<Long, Long> m = new HashMap<>(); HashMap<String, Long> s = new HashMap<>(); for (int i = 0; i < n; i++) { ni(); long vx = ni(); long vy = ni(); long v = (long) a * vx - vy; String k = vx + "|" + vy; long cs = s.getOrDefault(k, 0L); long c = m.getOrDefault(v, 0L); ans += c - cs; m.put(v, c + 1); s.put(k, cs + 1); } write (ans * 2 + "\n"); } public static void main(String[] args) { Main m = new Main(); m.solve(); try { m.out.close(); } catch (IOException e) {} } BufferedReader in; BufferedWriter out; StringTokenizer tokenizer; public Main() { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); } public String n() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException e) {} } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(n()); } public long nl() { return Long.parseLong(n()); } public void write(String s) { try { out.write(s); } catch (IOException e) {} } }
linear
975_D. Ghosts
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); System.out.println(3 * (n / 2)); } }
constant
84_A. Toy Army
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; public class Main { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } long mod=1000000007; void solve() throws IOException { for (int tc=ni();tc>0;tc--) { long n=ni(); long q=1; long p=1; boolean f=false; while (true) { if (p*2==n || p*4==n) { f=true; break; } q++; p=q*q; if (p>n) break; } if (f) out.println("YES"); else out.println("NO"); } out.flush(); } int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); } long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); } long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; } public static void main(String[] args) throws IOException { new Main().solve(); } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; /** * Created by Egor on 24/10/14. */ public class TaskA { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); String[] input = reader.readLine().split(" "); long l = Long.parseLong(input[0]); long r = Long.parseLong(input[1]); if (l % 2 == 0) { if (r >= l + 2) { writer.println(l + " " + (l + 1) + " " + (l + 2)); } else { writer.println(-1); } } else { if (r >= l + 3) { writer.println((l + 1) + " " + (l + 2) + " " + (l + 3)); } else { writer.println(-1); } } writer.close(); } }
constant
483_A. Counterexample
CODEFORCES
//package round97; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = new int[n]; for(int i = 0;i < n;i++){ a[i] = ni(); } Arrays.sort(a); if(a[n-1] > 1){ a[n-1] = 1; Arrays.sort(a); }else{ a[n-1] = 2; } for(int i = 0;i < n;i++){ if(i > 0)out.print(" "); out.print(a[i]); } out.println(); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; /** * CodeForces 8C - Looking for Order * Created by Darren on 14-10-1. */ public class Main { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { new Main().run(); } int n; int[] x, y; int[][] time; int status; int[] dp; int[] pre; void run() throws IOException { int xs = in.nextInt(), ys = in.nextInt(); n = in.nextInt(); x = new int[n+1]; y = new int[n+1]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } x[n] = xs; y[n] = ys; computeTime(); status = (1<<n); dp = new int[1<<n]; pre = new int[1<<n]; Arrays.fill(dp, -1); dp[0] = 0; for (int i = 0; i < status; i++) { if (dp[i] == -1) continue; for (int j = 0; j < n; j++) { if (((1<<j) & i) == 0) { int t1 = ((1<<j) | i), temp1 = dp[i] + 2 * time[n][j]; if (dp[t1] == -1 || dp[t1] > temp1) { dp[t1] = temp1; pre[t1] = i; } for (int k = 0; k < n; k++) { if (((1<<k) & t1) == 0) { int t2 = ((1<<k) | t1), temp2 = dp[i] + time[n][j] + time[j][k] + time[k][n]; if (dp[t2] == -1 || dp[t2] > temp2) { dp[t2] = temp2; pre[t2] = i; } } } break; } } } int cur = (1 << n) - 1; out.println(dp[cur]); out.print(0); while (cur > 0) { int last = pre[cur], diff = cur ^ last; int obj1 = -1, obj2 = -1; for (int i = 0; i < n; i++) { if (((1<<i) & diff) > 0) { obj2 = obj1; obj1 = i; } } if (obj2 >= 0) out.printf(" %d %d %d", obj1+1, obj2+1, 0); else out.printf(" %d %d", obj1+1, 0); cur = last; } out.flush(); } void computeTime() { time = new int[n+1][n+1]; for (int i = 0; i <= n; i++) { for (int j = i+1; j <= n; j++) time[i][j] = time[j][i] = (x[i]- x[j])*(x[i]- x[j]) + (y[i]- y[j])*(y[i]- y[j]); } } static class Reader { BufferedReader reader; StringTokenizer tokenizer; public Reader(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** get next word */ String nextToken() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } String readLine() throws IOException { return reader.readLine(); } int nextInt() throws IOException { return Integer.parseInt( nextToken() ); } long nextLong() throws IOException { return Long.parseLong( nextToken() ); } double nextDouble() throws IOException { return Double.parseDouble( nextToken() ); } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; public class Main { static boolean visited[] ; static boolean ends[] ; static long mod = 1000000007 ; static int lens[] ; static int seeds[] ; static int a[] ; static double total ; public static ArrayList adj[] ; public static long x,y ; public static ArrayList<Long> xx ; public static void main(String[] args) throws IOException, InterruptedException { Scanner sc = new Scanner(System.in) ; long x = sc.nextLong() ; long k = sc.nextLong() ; if(x==0) {System.out.println(0); return ;} if(k==0) {System.out.println((2l*x)%mod);return ;} long m=pow(2,k); long a = 2l*(x%mod)*(m%mod); a = a-m+1 ; a=a%mod ; if(a<0)a=(a%mod + mod) % mod; System.out.println(a); } // method to print the divisors static ArrayList<Long> divisors(long n) { ArrayList<Long> arr = new ArrayList<Long>() ; // Note that this loop runs till square root for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) // If divisors are equal, print only one if (n/i == i) {arr.add(1l*i);arr.add(1l*i);} else // Otherwise print both {arr.add(1l*i); arr.add(1l*n/i);} } return arr ; } public static void generate(long current) { if(current>10000000000l) return ; xx.add(current) ; generate((10*current) +4); generate((10*current) +7); } public static int neededFromLeft(String x) { Stack<Character> st = new Stack<Character>() ; int c=0; for (int i = 0; i < x.length(); i++) { char cur = x.charAt(i); if(cur==')' && st.isEmpty()) c ++; else if(cur==')' && !st.isEmpty()) st.pop(); else if(cur=='(') st.push(cur); } return c; } public static int neededFromRight(String x) { Stack<Character> st = new Stack<Character>() ; int c=0; boolean f=true; for (int i = 0; i < x.length(); i++) { char cur = x.charAt(i); if(cur==')' && st.isEmpty()) f=false; else if(cur==')' && !st.isEmpty()) st.pop(); else if(cur=='(') st.push(cur); } return st.size(); } public static boolean fromBoth(String x) { Stack<Character> st = new Stack<Character>() ; boolean f1=true ,f2=true ; for (int i = 0; i < x.length(); i++) { char cur = x.charAt(i); if(cur==')' && st.isEmpty()) f1 =false ; else if(cur==')' && !st.isEmpty()) st.pop(); else if(cur=='(') st.push(cur); } if(st.size()>0)f2 = false ; if(f1==false && f2==false) return true ; else return false; } public static boolean isRegular(String x) { Stack<Character> st = new Stack<Character>() ; for (int i = 0; i < x.length(); i++) { char cur = x.charAt(i); if(cur==')' && st.isEmpty()) return false ; else if(cur==')' && !st.isEmpty()) st.pop(); else if(cur=='(') st.push(cur); } if(st.size()>0)return false ; else return true ; } public static int gcdExtended(int a, int b) { // Base Case if (a == 0) { x = 0; y = 1; return b; } //int x1=1, y1=1; // To store results of recursive call int gcd = gcdExtended(b%a, a); // Update x and y using results of recursive // call long x1 = y - (b/a) * x; long y1 = x; x = x1 ; y = y1 ; return gcd; } static int even(String x , int b ) { for (int j = b; j>=0; j--) { int current = x.charAt(j)-48 ; if(current%2==0) return current ; } return -1; } static int odd(String x , int b ) { for (int j = b; j>=0; j--) { int current = x.charAt(j)-48 ; if(current%2!=0) return current ; } return -1; } static long pow(long base, long k) { long res = 1; while(k > 0) { if(k % 2 == 1) { res = (res * base) % mod; } base = (base * base) % mod; k /= 2; } return res; } public static long solve(int k1, long k2) { long x = 1l*k2*(pow(2, k1)-1) ; return x%(1000000007) ; } public static long getN(long x) { long n = (long) Math.sqrt(x*2) ; long y = n*(n+1)/2; if(y==x) return n ; else if(y>x) return n ; else for (long i = n; ; i++) { y = i*(i+1)/2 ; if(y>=x) return i ; } } public static void dfss(int root , int len) { visited[root]=true ; if(ends[root] && root!=0) lens[root] = len ; for (int i = 0; i < adj[root].size(); i++) { int c= (int) adj[root].get(i) ; if(visited[c]==false) dfss(c, len+1); } } public static void pr(int root , int seed){ visited[root] = true ; int dv = adj[root].size()-1 ; if(root==0) dv++ ; for (int i = 0; i < adj[root].size(); i++) { int c = (int)adj[root].get(i) ; seeds[c]=dv*seed ; } for (int i = 0; i < adj[root].size() ; i++) { int c = (int)adj[root].get(i) ; if(visited[c]==false) pr(c , seeds[c]); } } public static String concatinate(String s ,int n) { if(s.length()==n) return s ; else return concatinate("0"+s, n) ; } 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(); } } public static long getGCD(long n1, long n2) { if (n2 == 0) { return n1; } return getGCD(n2, n1 % n2); } public static int cnt1(int mat[][]) //how many swaps to be a 1 matrix { int m = mat.length ; int c=0 ; for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat.length; j++) { int x = (i*m) +j ; if(x%2==0 && mat[i][j]==0) c++; if(x%2!=0 && mat[i][j]==1) c++; } } return c; } public static int cnt0(int mat[][]) { int m = mat.length ; int c=0 ; for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat.length; j++) { int x = (i*m) +j ; if(x%2!=0 && mat[i][j]==0) c++; if(x%2==0 && mat[i][j]==1) c++; } } return c; } public static boolean canFit2(int x1, int y1 , int x2 , int y2 , int x3 , int y3){ if(x1==x2) if(x1==x3) return true ; else return false ; else if(x1==x3) return false ; else { long a = 1l*(y2-y1)*(x3-x2) ; long b = 1l*(y3-y2)*(x2-x1) ; if(a==b) return true; else return false ; } } public static void shuffle(pair[] ss){ if(ss.length==1) return ; for (int i = 0; i < ss.length; i++) { Random rand = new Random(); int n = rand.nextInt(ss.length-1) + 0; pair temp = ss[i] ; ss[i] = ss[n] ; ss[n] = temp ; } } public static int binary(ArrayList<pair> arr, int l, int r, long x) /// begin by 0 and n-1 { if (r>=l) { int mid = l + (r - l)/2; if (arr.get(mid).x== x) return mid; if (arr.get(mid).x> x) return binary(arr, l, mid-1, x); return binary(arr, mid+1, r, x); } return -1; } /// searching for the index of first elment greater than x public static int binary1(int[]arr , int x) { int low = 0, high = arr.length; // numElems is the size of the array i.e arr.size() while (low != high) { int mid = (low + high) / 2; // Or a fancy way to avoid int overflow if (arr[mid] <= x) { /* This index, and everything below it, must not be the first element * greater than what we're looking for because this element is no greater * than the element. */ low = mid + 1; } else { /* This element is at least as large as the element, so anything after it can't * be the first element that's at least as large. */ high = mid; } } return low ; // return high ; } ////// searching for last element less than X public static int binary2(pair[]arr , int x) { int low = 0, high = arr.length; // numElems is the size of the array i.e arr.size() while (low != high) { int mid = (low + high) / 2; // Or a fancy way to avoid int overflow if (arr[mid].x >= x) { /* This index, and everything below it, must not be the first element * greater than what we're looking for because this element is no greater * than the element. */ high=mid; } else { /* This element is at least as large as the element, so anything after it can't * be the first element that's at least as large. */ low = mid+1 ; } } return low ; // return high ; } private static boolean triangle(int a, int b , int c){ if(a+b>c && a+c>b && b+c>a) return true ; else return false ; } private static boolean segment(int a, int b , int c){ if(a+b==c || a+c==b && b+c==a) return true ; else return false ; } private static int gcdThing(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static boolean is(int i){ if(Math.log(i)/ Math.log(2) ==(int) (Math.log(i)/ Math.log(2))) return true ; if(Math.log(i)/ Math.log(3) ==(int) (Math.log(i)/ Math.log(3)) ) return true ; if(Math.log(i)/ Math.log(6) ==(int) (Math.log(i)/ Math.log(6)) ) return true ; return false; } public static boolean contains(int b[] , int x) { for (int i = 0; i < b.length; i++) { if(b[i]==x) return true ; } return false ; } public static int binary(long []arr , long target , int low , long shift) { int high = arr.length; while (low != high) { int mid = (low + high) / 2; if (arr[mid]-shift <= target) { low = mid + 1; } else { high = mid; } } return low ; // return high ; } public static boolean isLetter(char x){ if(x+0 <=122 && x+0 >=97 ) return true ; else if (x+0 <=90 && x+0 >=65 ) return true ; else return false; } public static long getPrimes(long x ){ if(x==2 || x==3 || x==1) return 2 ; if(isPrime(x)) return 5 ; for (int i = 2; i*i<=x; i++) { if(x%i==0 && isPrime(i)) return getPrimes(x/i) ; } return -1; } public static String solve11(String x){ int n = x.length() ; String y = "" ; for (int i = 0; i < n-2; i+=2) { if(ifPalindrome(x.substring(i, i+2))) y+= x.substring(i, i+2) ; else break ; } return y+ solve11(x.substring(y.length(),x.length())) ; } public static String solve1(String x){ String y = x.substring(0 , x.length()/2) ; return "" ; } public static String reverse(String x){ String y ="" ; for (int i = 0; i < x.length(); i++) { y = x.charAt(i) + y ; } return y ; } public static boolean ifPalindrome(String x){ int numbers[] = new int[10] ; for (int i = 0; i < x.length(); i++) { int z = Integer.parseInt(x.charAt(i)+"") ; numbers[z] ++ ; } for (int i = 0; i < numbers.length; i++) { if(numbers[i]%2!=0) return false; } return true ; } public static int get(int n){ return n*(n+1)/2 ; } // public static long getSmallestDivisor( long y){ // if(isPrime(y)) // return -1; // // for (long i = 2; i*i <= y; i++) // { // if(y%i ==0) // { // return i; // } // } // return -1; // } public static int lis( int[]a , int n){ int lis[] = new int[n] ; Arrays.fill(lis,1) ; for(int i=1;i<n;i++) for(int j=0 ; j<i; j++) if (a[i]>a[j] && lis[i] < lis[j]+1) lis[i] = lis[j] + 1; int max = lis[0]; for(int i=1; i<n ; i++) if (max < lis[i]) max = lis[i] ; return (max); // ArrayList<Integer> s = new ArrayList<Integer>() ; // for (int i = n-1; i >=0; i--) // { // if(lis[i]==max) // { // s.add(a[i].z); // max --; // } // } // // for (int i = s.size()-1 ; i>=0 ; i--) // { // System.out.print(s.get(i)+" "); // } // } public static int calcDepth(Vertix node){ if(node.depth>0) return node.depth; // meaning it has been updated before; if(node.parent != null) return 1+ calcDepth(node.parent); else return -1; } public static boolean isPrime (long num){ if (num < 2) return false; if (num == 2) return true; if (num % 2 == 0) return false; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true; } public static ArrayList<Long> getDiv(Long n) { ArrayList<Long> f = new ArrayList<Long>() ; while (n%2==0) { if(!f.contains(2))f.add((long) 2) ; n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (long i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { if(!f.contains(i))f.add(i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) if(!f.contains(n))f.add(n); return f ; } // public static boolean dfs(Vertix v , int target){ // try{ // visited[v.i]= true ; // } catch (NullPointerException e) // { // System.out.println(v.i); // } // if(v.i == target) // // return true ; // for (int i =0 ; i< v.neighbours.size() ; i++) // { // // Vertix child = v.neighbours.get(i) ; // if(child.i == target){ // found = true ; // } // if(visited[child.i]==false){ // found |= dfs(child, target) ; // } // } // return found; // } public static class Vertix{ long i ; int depth ; ArrayList<Vertix> neighbours ; Vertix parent ; Vertix child ; public Vertix(long i){ this.i = i ; this.neighbours = new ArrayList<Vertix> () ; this.parent = null ; depth =-1; this.child = null ; } } public static class pair implements Comparable<pair> { int x ; int y ; int i; public pair(int x, int y, int i ){ this.x=x ; this.y =y ; this.i =i ; } @Override public int compareTo(pair p) { if(this.x > p.x) return 1 ; else if (this.x == p.x) return 0 ; else return -1 ; } } public static class pair2 implements Comparable<pair2>{ int i ; int j ; int plus ; public pair2(int i , int j , int plus){ this.i =i ; this.j = j ; this.plus = plus ; } @Override public int compareTo(pair2 p) { if(this.j > p.j) return 1 ; else if (this.j == p.j) return 0 ; else return -1 ; } } public static class point implements Comparable<point> { int x, y ; public point(int x,int y){ this.x=x ; this.y=y; } @Override public boolean equals(Object o) { // If the object is compared with itself then return true if (o == this) { return true; } /* Check if o is an instance of Complex or not "null instanceof [type]" also returns false */ if (!(o instanceof point)) { return false; } // typecast o to Complex so that we can compare data members point c = (point) o; // Compare the data members and return accordingly return Integer.compare(x, c.x) == 0 && Integer.compare(y, c.y) == 0; } @Override public int compareTo(point p) { if(this.x == p.x && this.y ==p.y) return 0 ; else return -1 ; } @Override public int hashCode() { return 15+x+(y%2) ; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ 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); TaskF2 solver = new TaskF2(); solver.solve(1, in, out); out.close(); } static class TaskF2 { 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(); } HashMap<Integer, ArrayList<Interval>> map = new HashMap<>(); for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { sum += a[j]; if (map.containsKey(sum) == false) { map.put(sum, new ArrayList<>()); } ArrayList<Interval> arr = map.get(sum); if (arr.isEmpty() || arr.get(arr.size() - 1).r < i) { arr.add(new Interval(i, j)); } else if (arr.get(arr.size() - 1).r >= j) { arr.set(arr.size() - 1, new Interval(i, j)); } } } ArrayList<Interval> best = new ArrayList<>(); for (ArrayList<Interval> arr : map.values()) { if (best.size() < arr.size()) { best = arr; } } out.println(best.size()); for (Interval i : best) { out.println((i.l + 1) + " " + (i.r + 1)); } } class Interval { int l; int r; Interval(int l, int r) { this.l = l; this.r = r; } } } static class InputReader { private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private 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 (isWhitespace(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 (!isWhitespace(c)); return res * sgn; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; public class A { public static void main(String[] args) { new A(new Scanner(System.in)); } public A(Scanner in) { TreeSet<String> ts = new TreeSet<String>(); ArrayList<String> sr = new ArrayList<String>(); String s = in.next(); for (int i=0; i<s.length(); i++) { for (int j=i+1; j<=s.length(); j++) { String ss = s.substring(i, j); if (ts.contains(ss)) { sr.add(ss); } ts.add(ss); } } int res = 0; for (String ss : sr) { if (ss.length() > res) res = ss.length(); } System.out.printf("%d%n", res); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L; static final int INf = 1_000_000_000; static FastReader reader; static PrintWriter writer; public static void main(String[] args) { Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000); t.start(); } static class O implements Runnable { public void run() { try { magic(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } static class FastReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static void magic() throws IOException { reader = new FastReader(); writer = new PrintWriter(System.out, true); Map<Integer, ArrayList<Pair>> map = new HashMap<>(); int n = reader.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;++i) { arr[i] = reader.nextInt(); } for(int i=0;i<n;++i) { int sum = 0; for(int j=i;j<n;++j) { sum+=arr[j]; ArrayList<Pair> list = map.get(sum); if(list==null) { list = new ArrayList<>(); } list.add(new Pair(i+1,j+1)); map.put(sum, list); } } int ans = 0,at = -1; for(int e : map.keySet()) { ArrayList<Pair> list = map.get(e); Collections.sort(list); // writer.println("Pairs having sum: "+e); // for(Pair p : list) { // writer.print(p); // writer.print(" "); // } // writer.println(); int ispe = 0; int len = list.size(); for(int i=0;i<len;++i) { ispe++; int r = list.get(i).y; while(i+1<len && list.get(i+1).x<=r) { i++; } } if(ans<ispe) { ans = ispe; at = e; } } writer.println(ans); ArrayList<Pair> list = map.get(at); Collections.sort(list); int len = list.size(); for(int i=0;i<len;++i) { writer.println(list.get(i).x+" "+list.get(i).y); int r = list.get(i).y; while(i+1<len && list.get(i+1).x<=r) { i++; } } } static class Pair implements Comparable<Pair> { int x,y; Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair other) { if(this.y!=other.y) { return this.y - other.y; } return this.x - other.x; } public String toString() { return "{" + x + "," + y + "}"; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import com.sun.org.apache.xalan.internal.xsltc.dom.BitArray; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.BitSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author abdelrahman */ public class p1 { /** * @param args the command line arguments */ public static void main(String[] args) { new p1().run(); } private void run() { try { // TODO code application logic here Scanner scanner = new Scanner(System.in); String in = scanner.next(); Hashtable<String, Boolean> tmp = new Hashtable<String, Boolean>(); int sol = 0; for (int i = 0; i < in.length(); i++) { for (int j = i + 1; j <= in.length(); j++) { String str = in.substring(i, j); if (tmp.containsKey(str)) { if (tmp.get(str)) { if(str.length() > sol) sol=str.length(); boolean tmp1 = tmp.remove(str); tmp.put(str, false); } } else { tmp.put(str, Boolean.TRUE); } } } System.out.println(sol); } catch (Exception ex) { } } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int[]dp1 = new int[n+1]; int[]dp2 = new int[n+1]; dp1[1] = 1; int mod = (int) (1e9+7); char[]instruction = new char[n+1]; instruction[0] = 's'; int[]sum = new int[n+1]; for (int i = 1; i <= n; i++) { instruction[i] = next().charAt(0); for (int j = 1; j <= i; j++) { sum[j] = sum[j-1] + dp1[j]; if (sum[j] >= mod) sum[j] -= mod; } for (int j = 1; j <= i; j++) { if (instruction[i-1]=='f') dp2[j] = dp1[j-1]; else { dp2[j] = sum[i] - sum[j-1]; if (dp2[j] < 0) dp2[j] += mod; } } for (int j = 1; j <= i; j++) { dp1[j] = dp2[j]; } } int ans = 0; for (int i = 1; i <= n; i++) { ans += dp1[i]; if (ans >= mod) ans -= mod; } System.out.println(ans); pw.close(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; TaskC.InputReader in = new TaskC.InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.Solve(in, out); out.close(); } static class TaskC { private long mod = 1_000_000_007; private int n; private boolean[] s; public void Solve(InputReader in, PrintWriter out) { n = in.NextInt(); s = new boolean[n]; for (int i = 0; i < n; i++) { String ss = in.Next(); s[i] = ss.charAt(0) == 'f'; } if (s[n - 1]) { out.println(0); return; } long[] dpSum = new long[n + 1], lastDpSum = new long[n + 1]; for (int i = 0; i <= n; i++) { lastDpSum[i] = i + 1; } for (int i = n - 2; i >= 0; i--) { for (int j = 0; j <= i; j++) { if (!s[i]) { dpSum[j] = lastDpSum[j]; } else { dpSum[j] = lastDpSum[j + 1] - lastDpSum[j]; } if (j != 0) { dpSum[j] += dpSum[j - 1]; } dpSum[j] %= mod; while (dpSum[j] < 0) dpSum[j] += mod; } long[] temp = dpSum; dpSum = lastDpSum; lastDpSum = temp; } out.println(lastDpSum[0]); } public static int GetMax(int[] ar) { int max = Integer.MIN_VALUE; for (int a : ar) { max = Math.max(max, a); } return max; } public static int GetMin(int[] ar) { int min = Integer.MAX_VALUE; for (int a : ar) { min = Math.min(min, a); } return min; } public static long GetSum(int[] ar) { long s = 0; for (int a : ar) s += a; return s; } public static int[] GetCount(int[] ar) { return GetCount(ar, GetMax(ar)); } public static int[] GetCount(int[] ar, int maxValue) { int[] dp = new int[maxValue + 1]; for (int a : ar) { dp[a]++; } return dp; } 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(), " \t\n\r\f,"); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int NextInt() { return Integer.parseInt(Next()); } public long NextLong() { return Long.parseLong(Next()); } public double NextDouble() { return Double.parseDouble(Next()); } public int[] NextIntArray(int n) { return NextIntArray(n, 0); } public int[] NextIntArray(int n, int offset) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = NextInt() - offset; } return a; } public int[][] NextIntMatrix(int n, int m) { return NextIntMatrix(n, m, 0); } public int[][] NextIntMatrix(int n, int m, int offset) { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = NextInt() - offset; } } return a; } } } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BankAccount { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); int n = Integer.parseInt(s); if (s.charAt(0) == '-') if (Integer.parseInt(s.substring(0, s.length()-1))>Integer.parseInt(s.substring(0, s.length()-2)+s.charAt(s.length()-1))) s=s.substring(0, s.length()-1); else s=s.substring(0, s.length()-2)+s.charAt(s.length()-1); System.out.println(Integer.parseInt(s)); in.close(); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.io.BufferedInputStream; import java.util.Scanner; /** * Created by jizhe on 2016/1/29. */ public class LCMChallenge { public static void main(String[] args) { Scanner in = new Scanner(new BufferedInputStream(System.in)); long N = in.nextLong(); if( N == 1 || N == 2 ) { System.out.printf("%d\n", N); return; } if( (N&1) == 1 ) { long lcm = N*(N-1)*(N-2); System.out.printf("%d\n", lcm); } else { long lcm; if( N%3 == 0 ) { lcm = (N-1)*(N-2)*(N-3); } else { lcm = N*(N-1)*(N-3); } System.out.printf("%d\n", lcm); } } }
constant
235_A. LCM Challenge
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Homyak implements Runnable { private void solve() throws IOException { int n = nextInt(); String seq = nextToken(); int nh = 0; int nt = 0; for (int i = 0; i < n; ++i) if (seq.charAt(i) == 'H') ++nh; else ++nt; int res = n; for (int delta = 0; delta < n; ++delta) { int changed = 0; int at = delta; for (int i = 0; i < nh; ++i) { if (seq.charAt(at) != 'H') ++changed; ++at; if (at >= n) at = 0; } for (int i = 0; i < nt; ++i) { if (seq.charAt(at) != 'T') ++changed; ++at; if (at >= n) at = 0; } res = Math.min(res, changed / 2); } writer.println(res); } public static void main(String[] args) { new Homyak().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(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.*; import java.util.*; import java.lang.reflect.Array; import java.math.*; public class Solution { private BufferedReader in; private PrintWriter out; private StringTokenizer st; private Random rnd; int[] levels; int[] loyal; int n, k; double A; int[] choices; int[] new_loyal; double[] koef; double ans = 0.0; int total; void rec(int step, int start) { if(step == k) { for(int i = 0; i < n; i++) { new_loyal[i] = loyal[i]; } for(int i = 0; i < k; i++) { new_loyal[choices[i]] = Math.min(100, new_loyal[choices[i]] + 10); } int full = 0; for(int i = 0; i < n; i++) { if(new_loyal[i] == 100) { ++full; } } if(full > (n / 2)) { ans = 1.0; return; } for(int i = 0; i < n; i++) { koef[i] = (double) new_loyal[i] / 100.0; } int bits_needed = (n / 2) + 1; double total_win = 0.0; double total_fights = 0.0; for(int mask = 0; mask < total; mask++) { int bits = 0; double win = 1.0; double loose = 1.0; double b = 0.0; for(int bit = 0; bit < n; bit++) { if((mask & (1 << bit)) != 0) { ++bits; win *= koef[bit]; } else { loose *= (1.0 - koef[bit]); b += levels[bit]; } } double prob = win * loose; if(bits >= bits_needed) { total_win += prob; } else { total_fights += prob * (A / (A + b)); } } ans = Math.max(ans, total_win + total_fights); } else { for(int i = start; i < n; i++) { choices[step] = i; rec(step + 1, i); } } } public void solve() throws IOException { n = nextInt(); k = nextInt(); A = nextInt(); levels = new int[n]; loyal = new int[n]; new_loyal = new int[n]; choices = new int[k]; koef = new double[n]; for(int i = 0; i < n; i++) { levels[i] = nextInt(); loyal[i] = nextInt(); } total = 1 << n; rec(0, 0); out.println(ans); } public static void main(String[] args) { new Solution().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); st = null; rnd = new Random(); solve(); out.close(); } catch(IOException e) { e.printStackTrace(); } } private String nextToken() throws IOException, NullPointerException { while(st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
np
105_B. Dark Assembly
CODEFORCES
import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class Main { static int n; static int a; static int b; static int g; static int ref; static int refg; static HashSet<Integer> cgroup; static HashMap<Integer,Integer> indexmap; static HashSet<Integer> nums; static HashSet<Integer> used; public static void main(String[] args) { Scanner scan = new Scanner(System.in); n = scan.nextInt(); a = scan.nextInt(); b = scan.nextInt(); boolean[] where = new boolean[n]; indexmap = new HashMap<Integer,Integer>(); used = new HashSet<Integer>(); nums = new HashSet<Integer>(); if (a==b) b = 0; for (int i = 0; i<n; i++) { int x = scan.nextInt(); nums.add(x); indexmap.put(x,i); } scan.close(); for (int x : nums) { if (used.contains(x)) continue; cgroup = new HashSet<Integer>(); cgroup.add(x); g = -1; refg = -1; ref = -1; used.add(x); if (!spawn(x,a,b) || !spawn(x,b,a)) { System.out.println("NO"); return; } if (cgroup.size()%2==1 && ref == -1) { System.out.println("NO"); return; } else { boolean w = true; if (g == a) w = false; for (int k : cgroup) { where[indexmap.get(k)] = w; } } } System.out.println("YES"); for (int i = 0; i<where.length; i++) if (where[i]) System.out.print("1 "); else System.out.print("0 "); } private static boolean spawn(int x, int ab, int abo) { int xab = ab-x; if (xab == x) { ref = x; refg = ab; } else { if (nums.contains(xab)) { cgroup.add(xab); used.add(xab); spawn(xab,abo,ab); } else { if (g == -1) g = abo; else if (g != abo) { return false; } } } return true; } }
linear
468_B. Two Sets
CODEFORCES
import java.util.*; public class vas2 { public static void main( String[] args ) { Scanner in = new Scanner( System.in ); int n = in.nextInt(); String st = in.next(); int[] a = new int[n]; for ( int i = 0; i < n; i++ ) a[i] = st.charAt( i ) - 48; boolean c = false; for ( int i = 1; !c && i < n; i++ ) { int s = 0; for ( int j = 0; j < i; j++ ) s += a[j]; int t = 0; for ( int j = i; j < n; j++ ) { t += a[j]; if ( t > s ) if ( t - a[j] != s ) break; else t = a[j]; } if ( t == s ) c = true; } System.out.println( c ? "YES" : "NO" ); } }
quadratic
1030_C. Vasya and Golden Ticket
CODEFORCES
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t-- >0){ String str = scn.next(); Pattern p = Pattern.compile("R[0-9]+C[0-9]+"); Matcher m = p.matcher(str); if (m.matches()){ String nums[] = str.split("[RC]"); String first = nums[1]; String second = nums[2]; String ans = ""; long num = Integer.parseInt(second); while(num >0){ if (num % 26 > 0){ ans += (char)(num%26+'A'-1); num/=26; } else { ans += 'Z'; num/=26; num--; } } for (int i = ans.length()-1; i>=0;--i){ System.out.print(ans.charAt(i)); } System.out.println(first); } else { String first = str.split("[0-9]+")[0]; String second = str.split("[A-Z]+")[1]; System.out.print("R"+second); long num = 0, pow = 1; for (int i = first.length()-1; i>=0; --i){ num += (long)(first.charAt(i)-'A'+1) * pow; pow*=26; } System.out.println("C"+num); } } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.*; import java.util.*; public class Main { static Scanner in = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int n = in.nextInt(); int m = in.nextInt(); long boyMax = 0; int NBoyMax = 0; long sweets = 0; TreeSet<Long> boyMember = new TreeSet<>(); for (int i = 0; i < n; i++) { long input = in.nextLong(); boyMember.add(input); if (boyMax < input) { boyMax = input; NBoyMax = 1; } else if (boyMax == input) NBoyMax++; sweets += (input * m); } long smallestGirl = (long) 1e8 + 1; long sum = 0; for (int i = 0; i < m; i++) { long input = in.nextLong(); sum += input; if (smallestGirl > input) smallestGirl = input; } if (smallestGirl < boyMember.last()) { out.println(-1); } else if (smallestGirl == boyMember.last()) { sweets += sum - boyMember.last() * m; out.println(sweets); } else { if (NBoyMax > 1) { sweets += sum - boyMember.last() * m; out.println(sweets); } else { Object[] boyList = boyMember.toArray(); if (boyList.length > 1) { long boy = 0; boy = (long)boyList[boyList.length - 2]; sweets += (sum - smallestGirl - boyMember.last() * (m - 1)); sweets += (smallestGirl - boy); out.println(sweets); } else { out.println(-1); } } } in.close(); out.close(); } }
linear
1159_C. The Party and Sweets
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskG2 solver = new TaskG2(); solver.solve(1, in, out); out.close(); } static class TaskG2 { static final int MOD = 1000000000 + 7; static final int MAXN = 51; int getWays(int i, int j, int k, int l, int[][][][] ways, boolean[][][][] cached) { if (i + j + k == 0) return l == -1 ? 1 : 0; if (l < 0) return 0; if (cached[i][j][k][l]) return ways[i][j][k][l]; int s = i + j + k; long value = 0; if (l == 0 && i != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i - 1, j, k, x, ways, cached); } } if (l == 1 && j != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i, j - 1, k, x, ways, cached); } } if (l == 2 && k != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i, j, k - 1, x, ways, cached); } } ways[i][j][k][l] = (int) (value % MOD); cached[i][j][k][l] = true; return ways[i][j][k][l]; } int totalWays(int i, int j, int k, int[][][][] ways, boolean[][][][] cached, int[] factorial) { long ret = 0; for (int l = 0; l < 3; l++) ret += getWays(i, j, k, l, ways, cached); ret *= factorial[i]; ret %= MOD; ret *= factorial[j]; ret %= MOD; ret *= factorial[k]; ret %= MOD; return (int) ret; } int add(int type, int value, int[] sizes, int sum, int[][][][] dp) { sizes[type]++; if (type == 0) { for (int s = sum + value; s >= value; s--) { for (int i = 1; i <= sizes[0]; i++) for (int j = 0; j <= sizes[1]; j++) for (int k = 0; k <= sizes[2]; k++) { dp[i][j][k][s] += dp[i - 1][j][k][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } if (type == 1) { for (int s = sum + value; s >= value; s--) { for (int i = 0; i <= sizes[0]; i++) for (int j = 1; j <= sizes[1]; j++) for (int k = 0; k <= sizes[2]; k++) { // System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length); dp[i][j][k][s] += dp[i][j - 1][k][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } if (type == 2) { for (int s = sum + value; s >= value; s--) { for (int i = 0; i <= sizes[0]; i++) for (int j = 0; j <= sizes[1]; j++) for (int k = 1; k <= sizes[2]; k++) { // System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length); dp[i][j][k][s] += dp[i][j][k - 1][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } return sum + value; } public void solve(int testNumber, InputReader in, OutputWriter out) { int[][][][] ways = new int[MAXN][MAXN][MAXN][3]; boolean[][][][] cached = new boolean[MAXN][MAXN][MAXN][3]; // Arrays.fill(ways, -1); int n = in.nextInt(), T = in.nextInt(); ArrayList<Integer>[] ar = new ArrayList[3]; for (int i = 0; i < 3; i++) ar[i] = new ArrayList<Integer>(); int total_sum = 0; for (int i = 0; i < n; i++) { int t = in.nextInt(), g = in.nextInt(); ar[g - 1].add(t); total_sum += t; } if (T > total_sum) { out.println(0); return; } int min_index = 0, mn = 100000000; for (int i = 0; i < 3; i++) { if (ar[i].size() < mn) { mn = ar[i].size(); min_index = i; } } int[][][][] dp = new int[ar[(1 + min_index) % 3].size() + 1][ar[(2 + min_index) % 3].size() + 1][mn + 1][total_sum + 1]; dp[0][0][0][0] = 1; int[] sizes = {0, 0, 0}; int sum = 0; int[] order = {(min_index + 1) % 3, (min_index + 2) % 3, min_index}; int type = 0; for (int i : order) { for (int v : ar[i]) sum = add(type, v, sizes, sum, dp); type++; } int[] factorial = new int[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; i++) factorial[i] = (int) ((factorial[i - 1] * 1L * i) % MOD); long answer = 0; for (int i = 0; i < dp.length; i++) for (int j = 0; j < dp[0].length; j++) for (int k = 0; k < dp[0][0].length; k++) { answer += dp[i][j][k][T] * 1L * totalWays(i, j, k, ways, cached, factorial); answer %= MOD; } out.println(answer); } } 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 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 println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.util.*; import java.io.*; public class main{ static int max = 5000+1; static FastReader in = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static int N = 18; static int[][] mn1 = new int[N][N]; static int[][] mn2 = new int[N][N]; static int[][] dp = new int[1<<N][N]; static int n,m; static void solve(){ n = in.nextInt(); m = in.nextInt(); int[][] a = new int[n][m]; for(int i=0;i<n;i++)for(int j=0;j<m;j++)a[i][j] = in.nextInt(); for(int i=0;i<n;i++){ Arrays.fill(mn1[i],Integer.MAX_VALUE); Arrays.fill(mn2[i],Integer.MAX_VALUE); } for(int i=0;i<n;i++) for(int j=0;j<n;j++) for(int k=0;k<m;k++){ mn1[i][j] = Math.min(mn1[i][j],Math.abs(a[i][k]-a[j][k])); if(k<=m-2) mn2[i][j] = Math.min(mn2[i][j],Math.abs(a[i][k]-a[j][k+1])); } int ans = 0; for(int i=0;i<n;i++){ for(int x=0;x<1<<n;x++)Arrays.fill(dp[x],-1); for(int j=0;j<n;j++)dp[1<<j][j] = 0; dp[1<<i][i] = Integer.MAX_VALUE; for(int j=0;j<n;j++) ans = Math.max(ans,Math.min(mn2[j][i],calc((1 << n) - 1, j))); } out.println(ans); } static int calc(int mask, int v){ if (dp[mask][v] != -1) return dp[mask][v]; dp[mask][v] = 0; for(int u=0;u<n;u++) if (v != u && (((mask >> u) & 1)>0)) dp[mask][v] = Math.max(dp[mask][v], Math.min(mn1[u][v], calc(mask ^ (1 << v), u))); return dp[mask][v]; } public static void main(String[] args){ solve(); out.flush(); out.close(); } static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } int nextInt(){return Integer.parseInt(in.next());} long nextLong(){return Long.parseLong(in.next());} double nextDouble(){return Double.parseDouble(in.next());} } } // |xvcxv|vcv[cvcvc|cxv||]vcvx:v|c|vxc|[|cvx:cxvx||||]
np
1102_F. Elongated Matrix
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, sc, out); out.close(); } static class Task { public void solve(int testNumber, InputReader sc, PrintWriter out) { double n=sc.nextInt(); double k=sc.nextInt(); double ans=n-(-1.5+Math.sqrt(9.0/4+2*(n+k))); out.printf("%.0f\n",ans); } } 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()); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.Scanner; public class f { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); Hashtable<Long, Boolean> d = new Hashtable<Long, Boolean>(); int n = in.nextInt(), k = in.nextInt(), size = 0, a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); Arrays.sort(a); for (int i = 0; i < n; i++) { long x = a[i]; if (!d.containsKey(x)) { d.put(x * k, true); size++; } } System.out.println(size); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n,t[],g[],MOD=(int)1e9+7; static int [][]memo; static int dp(int msk,int rem,int lastG) { if(rem==0) return 1; if(memo[lastG][msk]!=-1) return memo[lastG][msk]; int ans=0; for(int i=0;i<n;i++) { if((msk & (1<<i))==0 && rem>=t[i] && g[i]!=lastG) ans+=dp(msk|1<<i,rem-t[i],g[i]); if(ans>=MOD) ans-=MOD; } return memo[lastG][msk]=ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n=sc.nextInt(); int T=sc.nextInt(); t=new int [n]; g=new int [n]; for(int i=0;i<n;i++) { t[i]=sc.nextInt(); g[i]=sc.nextInt()-1; } memo=new int [4][1<<n]; for(int []x:memo) Arrays.fill(x, -1); out.println(dp(0, T, 3)); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.*; public class helloWorld { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int l = 1000, r = 0, u = 1000, b = 0; for(int i = 0; i < n; i++ ) { String str = in.next(); for(int j = 0; j < m; j++) if(str.charAt(j) == 'B') { l = Math.min(j+1, l); r = Math.max(j+1, r); u = Math.min(i+1, u); b = Math.max(i+1, b); } } System.out.println((u+b)/2 + " " + (l+r)/2); in.close(); } }
quadratic
1028_A. Find Square
CODEFORCES
import java.util.Scanner; public class prob1177b { public static void main(String[] args){ Scanner sc=new Scanner(System.in); long k,c,n,d; c=1; d=9; n=1; k= sc.nextLong(); while(k>(c*d)) { k-=(c*d); n*=10; d*=10; c++; } n+=(k-1)/c; char[] num = String.valueOf(n).toCharArray(); System.out.println(num[(int)((k-1)%c)]); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import static java.lang.Math.*; import static java.util.Arrays.*; import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { new Main().run(); } StreamTokenizer in; PrintWriter out; //deb//////////////////////////////////////////////// public static void deb(String n, Object n1) { System.out.println(n + " is : " + n1); } public static void deb(int[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(long[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(BigInteger[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(int[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } public static void deb(long[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } public static void deb(String[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } ///////////////////////////////////////////////////////////// int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } class Pair<X, Y> { public X x; public Y y; public Pair(X x, Y y) { this.x = x; this.y = y; } public void setX(X x) { this.x = x; } public void setY(Y y) { this.y = y; } } boolean inR(int x, int y) { return (x >= 0) && (x < nn) && (y >= 0) && (y < nn); } static int nn; void run() throws IOException { // in = new StreamTokenizer(new BufferedReader(new FileReader("circles.in"))); // out = new PrintWriter(new FileWriter("circles.out")); in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); } static long MOD=1000000009; static long modPow(long a, int pow) { long res = 1; while (pow > 0) { if ((pow & 1) != 0) { res = res * a % MOD; } pow >>= 1; a = a * a % MOD; } return res; } void solve() throws IOException { // BufferedReader re= new BufferedReader(new FileReader("C:\\Users\\ASELA\\Desktop\\A.in")); // BufferedReader re = new BufferedReader(new InputStreamReader(System.in)); int n=nextInt(),m=nextInt(),k=nextInt(); int an=(n/k)*(k-1)+n%k; long ans=0; if(an>=m){ System.out.println(m); return; } int rem=m-an; ans=modPow(2, rem+1)-2; ans*=k; ans+=m-rem*k; ans%=MOD; // System.out.println("sjkd"+rem); if(ans<0)ans+=MOD; System.out.println(ans); } }
logn
338_A. Quiz
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; /** * Created by timur on 28.03.15. */ public class TaskD { boolean eof; BufferedReader br; StringTokenizer st; PrintWriter out; public static void main(String[] args) throws IOException { new TaskD().run(); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "-1"; } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return br.readLine(); } void run() throws IOException { InputStream input = System.in; PrintStream output = System.out; try { File f = new File("a.in"); if (f.exists() && f.canRead()) { input = new FileInputStream(f); output = new PrintStream("a.out"); } } catch (Throwable e) { } br = new BufferedReader(new InputStreamReader(input)); out = new PrintWriter(output); solve(); br.close(); out.close(); } long md(long x, long y, long x1, long y1) { return Math.abs(x - x1) + Math.abs(y - y1); } double md(double x, double y, double x1, double y1) { return Math.abs(x - x1) + Math.abs(y - y1); } double ed(double x, double y, double x1, double y1) { return Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1)); } void solve() { int t = nextInt(); long n, k; int m = 34; long[] res = new long[m]; res[1] = 0; res[2] = 1; for (int i = 3; i < m; i++) { res[i] = res[i - 1] * 4L; } long[] l = new long[m]; long[] r = new long[m]; l[0] = 0; l[1] = 1; r[0] = 0; r[1] = 1; for (int i = 2; i < m; i++) { l[i] = l[i - 1] * 2 + 1; r[i] = r[i - 1] * 4; } long[] mi = new long[m]; long[] ma = new long[m]; for (int i = 1; i < m; i++) { mi[i] = mi[i - 1] + l[i]; ma[i] = ma[i - 1] + r[i]; } // for (int i = 0; i < m - 1; i++) { // for (int j = 0; j <= i; j++) { // out.println(i + " " + j + " " + mi[(int)i - j] + " " + (ma[(int)i] - l[(int)i - j + 1] * ma[j])); // } // } for (int i = 0; i < t; i++) { n = nextLong(); k = nextLong(); if (n >= 32) { out.println("YES " + (n - 1)); } else { if (k > ma[(int)n]) { out.println("NO"); } else { for (int j = 0; j <= n; j++) { if (mi[(int)n - j] <= k && ma[(int)n] - l[(int)n - j + 1] * ma[j] >= k) { out.println("YES " + j); break; } if (j == n - 1) { out.println("NO"); } } } } } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main { static int[] a; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); a = sc.nextIntArray(n); long inversions = divide(0, n - 1); // out.println(inversions); // System.err.println(Arrays.toString(a)); if (n == 5) out.println("Petr"); else { if (n % 2 == 0) out.println(inversions % 2 == 0 ? "Petr" : "Um_nik"); else out.println(inversions % 2 != 0 ? "Petr" : "Um_nik"); } out.flush(); out.close(); } static long divide(int b, int e) { if (b == e) return 0; long cnt = 0; int mid = b + e >> 1; cnt += divide(b, mid); cnt += divide(mid + 1, e); cnt += merge(b, mid, e); return cnt; } static long merge(int b, int mid, int e) { long cnt = 0; int len = e - b + 1; int[] tmp = new int[len]; int i = b, j = mid + 1; for (int k = 0; k < len; k++) { if (i == mid + 1 || (j != e + 1 && a[i] > a[j])) { tmp[k] = a[j++]; cnt += (mid + 1 - i); } else tmp[k] = a[i++]; } for (int k = 0; k < len; k++) a[b + k] = tmp[k]; return cnt; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
nlogn
986_B. Petr and Permutations
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayList; public class A { 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); ArrayList<Integer> p = new ArrayList<Integer>(); ArrayList<Integer> o = new ArrayList<Integer>(); int n = nextInt(); for (int i=0; i<n; i++) { int a = nextInt(); if (a % 2 == 0) p.add(i+1); else o.add(i+1); } if (p.size() < o.size()) out.println(p.get(0)); else out.println(o.get(0)); out.flush(); } }
linear
25_A. IQ test
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int inf = (int) 1e9; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); int n = nextInt(); int k = nextInt(); long l = -1; long r = 100000; while(l != r - 1) { long mid = (l + r) / 2; if (mid * (mid + 1) / 2 - (n - mid) > k) r = mid; else l = mid; } pw.println(n - l); pw.close(); } static BufferedReader br; static StringTokenizer st = new StringTokenizer(""); static PrintWriter pw; static String next() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } 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()); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Stack; import java.util.StringTokenizer; public class TwoSets { static int n, a, b; static HashSet<Integer> arr = new HashSet<Integer>(); static HashSet<Integer> visited = new HashSet<Integer>(); static HashMap<Integer, Integer> result = new HashMap<Integer, Integer>(); static void dfs(int x, int parent, int len) { stack.push(x); visited.add(x); int children = 0; if (a - x > 0) { if (a - x != parent && arr.contains(a - x)) { dfs(a - x, x, len + 1); children++; } } if (b - x > 0) { if (b - x != parent && arr.contains(b - x)) { dfs(b - x, x, len + 1); children++; } } if (children == 0) { if (len % 2 == 1) { System.out.println("NO"); System.exit(0); } else { while (!stack.isEmpty()) { int first = stack.pop(); int second = stack.pop(); if (first == a - second) { result.put(first, 0); result.put(second, 0); } else { result.put(first, 1); result.put(second, 1); } } } } } static Stack<Integer> stack = new Stack<Integer>(); public static void main(String[] args) { InputReader r = new InputReader(System.in); n = r.nextInt(); a = r.nextInt(); b = r.nextInt(); int[] list = new int[n]; for (int i = 0; i < n; i++) { list[i] = r.nextInt(); arr.add(list[i]); } for (int x : arr) { if (!visited.contains(x)) { if (arr.contains(a - x) && arr.contains(b - x)) continue; if (arr.contains(a - x) || arr.contains(b - x)) { dfs(x, -1, 1); } else { System.out.println("NO"); System.exit(0); } } } PrintWriter out = new PrintWriter(System.out); out.println("YES"); for (int i = 0; i < list.length; i++) { if (result.get(list[i]) == null) out.println(0); else out.println(result.get(list[i])); } out.close(); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public InputReader(FileReader stream) { reader = new BufferedReader(stream); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
linear
468_B. Two Sets
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class BetaRound8_C implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok; @Override public void run() { try { long startTime = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } tok = new StringTokenizer(""); Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long endTime = System.currentTimeMillis(); long totalMemory = Runtime.getRuntime().totalMemory(); long freeMemory = Runtime.getRuntime().freeMemory(); System.err.println("Time = " + (endTime - startTime) + " ms"); System.err.println("Memory = " + ((totalMemory - freeMemory) / 1024) + " KB"); } catch (Throwable e) { e.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()); } void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } public static void main(String[] args) { new Thread(null, new BetaRound8_C(), "", 256 * 1024 * 1024).start(); } // ------------------------------------------------------------------------------ final int INF = 1000 * 1000 * 1000; int x0, y0; int n; int[] x, y; int t(int i, int j) { int dx = x[i] - x[j]; int dy = y[i] - y[j]; return dx * dx + dy * dy; } int t0(int i) { int dx = x[i] - x0; int dy = y[i] - y0; return dx * dx + dy * dy; } int[] dp; int[] p; void solve() throws IOException { x0 = readInt(); y0 = readInt(); n = readInt(); x = new int[n]; y = new int[n]; for (int i = 0; i < n; i++) { x[i] = readInt(); y[i] = readInt(); } dp = new int[1 << n]; p = new int[1 << n]; Arrays.fill(dp, INF); dp[(1 << n) - 1] = 0; get(0); out.println(dp[0]); printPath(); } int get(int mask) { if (dp[mask] != INF) { return dp[mask]; } int res = INF; for (int i = 0; i < n; i++) { if (((1 << i) & mask) == 0) { // порядок неважен, т.к. в i все равно идти, пойдем туда сразу int test = get(mask ^ (1 << i)) + 2 * t0(i); if (res > test) { res = test; p[mask] = mask ^ (1 << i); } for (int j = i + 1; j < n; j++) { if (((1 << j) & mask) == 0) { test = get(mask ^ (1 << i) ^ (1 << j)) + t0(i) + t(i, j) + t0(j); if (res > test) { res = test; p[mask] = mask ^ (1 << i) ^ (1 << j); } } } break; } } return dp[mask] = res; } void printPath() { ArrayList<Integer> ans = new ArrayList<Integer>(); ans.add(0); int mask = 0; while (mask != (1 << n) - 1) { for (int i = 0; i < n; i++) { if (((mask ^ p[mask]) & (1 << i)) != 0) { ans.add(i + 1); } } mask = p[mask]; ans.add(0); } for (int x : ans) { out.print(x + " "); } } }
np
8_C. Looking for Order
CODEFORCES
import java.util.Scanner; public class CodeforcesC { public static void main(String[] args) { Scanner ob = new Scanner(System.in); long n = ob.nextLong(); long s = ob.nextLong(); long l = 1; long r = n; while(l<=r){ long mid = (l + r)/2; if(reallybignumber(mid,s)){ r = mid-1; }else{ l = mid +1; } } /******long l1 = l; ***while(l1<=n) { System.out.print(l1 + " "); l1++; }*///////// System.out.println(n-l+1); } private static boolean reallybignumber(long n,long s) { long m = n; long sum=0; int d=1; while(m>0){ long rem = m % 10; sum = rem * d + sum; m = m / 10; } if(n-sum >= s) return true; else return false; } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class AAA { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); String a=""; String b=""; for(int i=0;i<1129;i++) { a+="1"; b+="8"; } a+="9"; b+="1"; System.out.println(a); System.out.println(b); } }
constant
1028_B. Unnatural Conditions
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class d { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); long[] arr = new long[n];//in.nextLongArray(n); for (int i = 0; i < n; i++) { //if (i < n / 2) arr[i] = 1; //else arr[i] = 1000000000; arr[i] = in.nextLong(); } long sum = 0; long count = 0; TreeSet<Long> ts = new TreeSet<>(); ts.add(1L); long oo = 1000000000 + 100; ts.add(oo); for (long a : arr) { a += 10; ts.add(a); ts.add(a - 2); ts.add(a + 2); } long[] inds = new long[ts.size()]; int idx = 0; for (long a : ts) { inds[idx++] = a; } SuperBIT bit1 = new SuperBIT(inds); SuperBIT bit2 = new SuperBIT(inds); BigInteger ans = BigInteger.valueOf(0); for (long a : arr) { a += 10; long countLess = bit1.queryCompr(1, a - 2); long sumLess = bit2.queryCompr(1, a - 2); long countMore = bit1.queryCompr(a + 2, oo); long sumMore = bit2.queryCompr(a + 2, oo); //System.out.println(a + " " + countLess + " " + sumLess + " " + countMore + " " + sumMore); bit1.updateCompr(a, 1); bit2.updateCompr(a, a); long tmp = 0; tmp += countLess * a - sumLess; tmp -= sumMore - countMore * a; ans = ans.add(BigInteger.valueOf(tmp)); } out.println(ans); out.close(); } static class SuperBIT { long[] dataMul, dataAdd; SuperBIT(int n) { dataMul = new long[n]; dataAdd = new long[n]; } void update(int left, int right, long val) { internalUpdate(left, val, -val * (left-1)); internalUpdate(right, -val, val * right); } void internalUpdate(int at, long mul, long add) { while (at < dataMul.length) { dataMul[at] += mul; dataAdd[at] += add; at |= (at + 1); } } long query(int at) { long mul = 0; long add = 0; int start = at; while(at >= 0) { mul += dataMul[at]; add += dataAdd[at]; at = (at & (at + 1)) -1; } return mul * start + add; } long query(int left, int right) { if (left > right) { int temp = left; left = right; right = temp; } return query(right) - (left > 0 ? query(left-1) : 0); } long[] indices; // Used for compressed BIT // Compressed BIT constructor // A BIT that only stores the values that will be updated. // indices is a sorted array of all the unique indices // that would be used for this BIT. public SuperBIT(long[] indices) { this.indices = indices; dataMul = new long[indices.length]; dataAdd = new long[indices.length]; } // Search for the index in the array. If the index was not found, // return the first index lower than the search index. int binSearch(long ind) { int low = 0; int high = dataMul.length-1; while(low < high) { int mid = (low + high+1)/2; if(indices[mid] == ind) return mid; else if(indices[mid] < ind) low = mid; else if(indices[mid] > ind) high = mid-1; } if(indices[low] > ind) --low; return low; } // Read the largest index less than or equal to the given index. long queryCompr(long index) { return query(binSearch(index)); } long queryCompr(long left, long right) { return query(binSearch(left), binSearch(right)); } // Update a specific index by a value. If the index is not in this // compressed BIT, the index below will be updated. void updateCompr(long index, long val) { int ind = binSearch(index); update(ind, ind, val); } void updateCompr(long left, long right, long val) { update(binSearch(left), binSearch(right), val); } } static Random rand = new Random(); static void sort(int[] a) { int n = a.length; for (int i = a.length - 1; i > 0; i--) { int j = rand.nextInt(i + 1); int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } Arrays.sort(a); } static void sort(long[] a) { int n = a.length; for (int i = a.length - 1; i > 0; i--) { int j = rand.nextInt(i + 1); long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } Arrays.sort(a); } static void sort(double[] a) { int n = a.length; for (int i = a.length - 1; i > 0; i--) { int j = rand.nextInt(i + 1); double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } Arrays.sort(a); } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a / gcd(a, b) * b; } static long[] eEuclid(long a, long b) { if (b == 0) return new long[] { a, 1, 0 }; long[] ans = eEuclid(b, a % b); long temp = ans[1] - ans[2] * (a / b); ans[1] = ans[2]; ans[2] = temp; return ans; } static long modInverse(long a, long m) { return ((eEuclid(a, m)[1] % m) + m) % m; } static class IntList { static int[] EMPTY = {}; int[] a = EMPTY; int n = 0; void add(int v) { if (n >= a.length) a = Arrays.copyOf(a, (n << 2) + 8); a[n++] = v; } int get(int idx) { return a[idx]; } int size() { return n; } } static class DisjointSet { int[] s, r; public DisjointSet(int n) { s = new int[n]; r = new int[n]; for (int i = 0; i < n; i++) s[i] = i; } public int find(int i) { return s[i] == i ? i : (s[i] = find(s[i])); } public void union(int a, int b) { if(r[a = find(a)] == r[b = find(b)]) r[a]++; if(r[a] >= r[b]) s[b] = a; else s[a] = b; } } 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()); } public int[] nextOffsetIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt() - 1; return arr; } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public int[][] nextIntArray(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextInt(); return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public long[][] nextLongArray(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextLong(); return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) arr[i] = nextDouble(); return arr; } public double[][] nextDoubleArray(int n, int m) throws IOException { double[][] arr = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextDouble(); return arr; } public char[][] nextCharArray(int n, int m) throws IOException { char[][] arr = new char[n][]; for (int i = 0; i < n; i++) arr[i] = next().toCharArray(); return arr; } } }
nlogn
903_D. Almost Difference
CODEFORCES
import java.util.*; import java.io.*; import java.text.*; public class B1195 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); long x =sc.nextInt(); long y =sc.nextInt(); long m = (-3+Math.round(Math.sqrt(9+8*(x+y))))/2; long e = x-m; pw.println(e); pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } 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.util.*; import java.io.*; import java.math.BigInteger; public class Solution { 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 fang(int s, int x, int y) { if (x > y) { int t = x; x = y; y = t; } if (s + 1 <= x) { return (long)(s + 1) * (s + 2) / 2; } if (s + 1 <= y) { return (long)x * (x + 1) / 2 + (long)(s + 1 - x) * x; } if (s + 1 >= x + y - 1) { return (long)x * y; } long q = x + y - 1 - s - 1; return (long)x * y - q * (q + 1) / 2; } long f(int s, int n, int x, int y) { long ans = fang(s, n - x + 1, n - y + 1) + fang(s, n - x + 1, y) + fang(s, x, n - y + 1) + fang(s, x, y); ans -= Math.min(s + 1, n - x + 1) + Math.min(s + 1, x) + Math.min(s + 1, n - y + 1) + Math.min(s + 1, y); return ans + 1; } void solve() throws Exception { int n = nextInt(); int x = nextInt(), y = nextInt(); long c = nextInt(); if (c == 1) { out.println(0); return; } int bg = 0, ed = 2 * n; while (ed > bg + 1) { int mm = (bg + ed) / 2; if (f(mm, n, x, y) >= c) ed = mm; else bg = mm; } out.println(ed); } void run() { try { Locale.setDefault(Locale.US); // in = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { out.close(); } } public static void main(String[] args) { // TODO Auto-generated method stub new Solution().run(); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Main { public static int n,m; public static void main(String[] arg) { FastScanner scan = null; PrintWriter out = null; try{ scan = new FastScanner(new FileInputStream("input.txt")); out = new PrintWriter(new FileOutputStream("output.txt")); }catch(FileNotFoundException e){ scan = new FastScanner(System.in); out = new PrintWriter(System.out); } n = scan.nextInt(); m = scan.nextInt(); int k = scan.nextInt(); int[][] board = new int[n+1][m+1]; String[] ins = scan.nextLine().split(" ",-1); List<Integer> ps = new ArrayList<Integer>(); for(int i = 0; i < 2 * k; i += 2){ int a = Integer.parseInt(ins[i]); int b = Integer.parseInt(ins[i+1]); board[a][b] = 1; ps.add(a * 2001 + b); } int retx = 1, rety = 1; int[] dx = {0,1,0,-1}; int[] dy = {1,0,-1,0}; while(true){ boolean find = false; List<Integer> ps2 = new ArrayList<Integer>(); for(Integer p : ps){ int i = p / 2001; int j = p % 2001; for(int q = 0; q < 4; q++){ int nx = i + dx[q]; int ny = j + dy[q]; if(in(nx,ny) && board[nx][ny] == 0){ board[nx][ny] = 1; retx = nx; rety = ny; find = true; ps2.add(nx * 2001 + ny); } } board[i][j] = 2; } ps = ps2; if(!find) break; } out.println(retx + " " + rety); out.close(); } public static boolean in(int i, int j){ return (1 <= i && i <= n) && (1 <= j && j <= m); } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream is) { try { br = new BufferedReader(new InputStreamReader(is)); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { return null; } } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (Exception e) { return null; } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.valueOf(next()); } } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringTokenizer; public class Tt { public static void main(String[] args) throws IOException { FastScanner fs=new FastScanner(System.in); int j = fs.nextInt(); ArrayList<Integer> a =new ArrayList<Integer>(); for(int i=0;i<j;i++) { a.add(fs.nextInt()); } Collections.sort(a); Collections.reverse(a); int c=0; while(a.size()!=0) { int f=a.get(a.size()-1); c+=1; for(int q=a.size()-1;q>-1;q--) if(a.get(q)%f==0) { a.remove(q); } } System.out.println(c); } 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 long nextLong() throws IOException{ return Long.parseLong(next()); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { if(!st.hasMoreTokens()) return br.readLine(); String ret = st.nextToken(); while(st.hasMoreTokens()) ret += " " + st.nextToken(); return ret; } }}
quadratic
1209_A. Paint the Numbers
CODEFORCES
// discussed with rainboy import java.io.*; import java.util.*; public class CF911D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] aa = new int[n]; for (int i = 0; i < n; i++) aa[i] = Integer.parseInt(st.nextToken()); boolean odd = false; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (aa[i] > aa[j]) odd = !odd; int m = Integer.parseInt(br.readLine()); while (m-- > 0) { st = new StringTokenizer(br.readLine()); int l = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); int k = r - l + 1; if ((long) k * (k - 1) / 2 % 2 != 0) odd = !odd; pw.println(odd ? "odd" : "even"); } pw.close(); } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; public class P1141F { static BufferedReader br; static BufferedWriter bw; static StringTokenizer st; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(br.readLine()); int[] a = new int[n]; int[][] b = new int[n][n]; HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; ++i) { a[i] = Integer.parseInt(st.nextToken()); int r = i; b[r][r] = a[r]; if (!map.containsKey(b[r][r])) map.put(b[r][r], new ArrayList<Integer>()); for(int l = 0; l < r; ++l) { b[l][r] = b[l][r-1] + a[r]; if (!map.containsKey(b[l][r])) map.put(b[l][r], new ArrayList<Integer>()); } } for(int r = 0; r < n; ++r) { for(int l = 0; l <= r; ++l) { int sum = b[l][r]; ArrayList<Integer> intervals = map.get(sum); int last_r = -1; if(!intervals.isEmpty()) last_r = intervals.get(intervals.size()-1); if(l > last_r) { intervals.add(l); intervals.add(r); } } } //int best_sum = -1; ArrayList<Integer> best_intervals = new ArrayList<Integer>(); for(Map.Entry<Integer, ArrayList<Integer>> entry : map.entrySet()) { //int sum = entry.getKey(); ArrayList<Integer> intervals = entry.getValue(); if(intervals.size() > best_intervals.size()) { best_intervals = intervals; } } bw.write(best_intervals.size()/2 + "\n"); for(int i = 0; i < best_intervals.size(); i += 2) { bw.write((best_intervals.get(i)+1) + " " + (best_intervals.get(i+1)+1) + "\n"); } br.close(); bw.close(); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class B { public static void main(String[] args) { FastScanner fs=new FastScanner(); int T=fs.nextInt(); for (int tt=0; tt<T; tt++) { int n=fs.nextInt(); boolean isEven=n%2==0; while (n%2==0) n/=2; if (isSquare(n) && isEven) { System.out.println("YES"); } else { System.out.println("NO"); } } } static boolean isSquare(long n) { long sqrt=(long) Math.sqrt(n); for (int i=(int) Math.max(1, sqrt-5); i<=sqrt+5; i++) if (i*i==n) return true; return false; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.util.Scanner; public class MargariteBestPresent_1080B { private static int f(int x) { return (x%2==0)?x/2:(x-1)/2-x; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n,r,l; n = sc.nextInt(); while(n-->0) { l = sc.nextInt(); r = sc.nextInt(); System.out.println(f(r)-f(l-1)); } sc.close(); } }
constant
1080_B. Margarite and the best present
CODEFORCES
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter; import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Array;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;import java.security.AccessControlException;import java.util.Arrays; import java.util.Collection;import java.util.Comparator;import java.util.List;import java.util.Map; import java.util.Objects;import java.util.TreeMap;import java.util.function.Function; import java.util.stream.Collectors;import java.util.stream.IntStream;import java.util.stream.LongStream; import java.util.stream.Stream;public class _B {static public void main(final String[] args) throws IOException{B._main(args);} static class B extends Solver{public B(){}@Override public void solve()throws IOException {int n=sc.nextInt();sc.nextLine();boolean res=false;if(n%2==0){int n1=n/2;int sq =(int)Math.ceil(Math.sqrt(n1));if(sq*sq==n1){res=true;}else if(n%4==0){n1=n/4;sq =(int)Math.ceil(Math.sqrt(n1));if(sq*sq==n1){res=true;}}}pw.println(Datas.yesNo(res)); }static public void _main(String[]args)throws IOException{new B().run();}}static class Datas{static class Pair<K,V>{private K k;private V v;public Pair(final K t,final V u){this.k=t;this.v=u;}public K getKey(){return k;}public V getValue(){return v; }}final static String SPACE=" ";public static TreeMap<Integer,Integer>mapc(final int[]a){return IntStream.range(0,a.length).collect(()->new TreeMap<Integer,Integer>(), (res,i)->{res.put(a[i],res.getOrDefault(a[i],0)+1);},Map::putAll);}public static TreeMap<Long,Integer>mapc(final long[]a){return IntStream.range(0,a.length).collect( ()->new TreeMap<Long,Integer>(),(res,i)->{res.put(a[i],res.getOrDefault(a[i],0)+ 1);},Map::putAll);}public static<T>TreeMap<T,Integer>mapc(final T[]a,Comparator<T> cmp){return IntStream.range(0,a.length).collect(cmp!=null?()->new TreeMap<T,Integer>(cmp) :()->new TreeMap<T,Integer>(),(res,i)->{res.put(a[i],res.getOrDefault(a[i],0)+1); },Map::putAll);}public static<T>TreeMap<T,Integer>mapc(final T[]a){return mapc(a, null);}public static TreeMap<Integer,Integer>mapc(final IntStream a){return a.collect( ()->new TreeMap<Integer,Integer>(),(res,v)->{res.put(v,res.getOrDefault(v,0)+1); },Map::putAll);}public static TreeMap<Long,Integer>mapc(final LongStream a){return a.collect(()->new TreeMap<Long,Integer>(),(res,v)->{res.put(v,res.getOrDefault(v, 0)+1);},Map::putAll);}public static<T>TreeMap<T,Integer>mapc(final Stream<T>a,Comparator<T> cmp){return a.collect(cmp!=null?()->new TreeMap<T,Integer>(cmp):()->new TreeMap<T, Integer>(),(res,v)->{res.put(v,res.getOrDefault(v,0)+1);},Map::putAll);}public static <T>TreeMap<T,Integer>mapc(final Stream<T>a){return mapc(a,null);}public static<T> TreeMap<T,Integer>mapc(final Collection<T>a,Comparator<T>cmp){return mapc(a.stream(), cmp);}public static<T>TreeMap<T,Integer>mapc(final Collection<T>a){return mapc(a.stream()); }public static TreeMap<Integer,List<Integer>>mapi(final int[]a){return IntStream.range(0, a.length).collect(()->new TreeMap<Integer,List<Integer>>(),(res,i)->{if(!res.containsKey(a[i])) {res.put(a[i],Stream.of(i).collect(Collectors.toList()));}else{res.get(a[i]).add(i); }},Map::putAll);}public static TreeMap<Long,List<Integer>>mapi(final long[]a){return IntStream.range(0,a.length).collect(()->new TreeMap<Long,List<Integer>>(),(res,i) ->{if(!res.containsKey(a[i])){res.put(a[i],Stream.of(i).collect(Collectors.toList())); }else{res.get(a[i]).add(i);}},Map::putAll);}public static<T>TreeMap<T,List<Integer>> mapi(final T[]a,Comparator<T>cmp){return IntStream.range(0,a.length).collect(cmp !=null?()->new TreeMap<T,List<Integer>>(cmp):()->new TreeMap<T,List<Integer>>(), (res,i)->{if(!res.containsKey(a[i])){res.put(a[i],Stream.of(i).collect(Collectors.toList())); }else{res.get(a[i]).add(i);}},Map::putAll);}public static<T>TreeMap<T,List<Integer>> mapi(final T[]a){return mapi(a,null);}public static TreeMap<Integer,List<Integer>> mapi(final IntStream a){int[]i=new int[]{0};return a.collect(()->new TreeMap<Integer, List<Integer>>(),(res,v)->{if(!res.containsKey(v)){res.put(v,Stream.of(i[0]).collect(Collectors.toList())); }else{res.get(v).add(i[0]);}i[0]++;},Map::putAll);}public static TreeMap<Long,List<Integer>> mapi(final LongStream a){int[]i=new int[]{0};return a.collect(()->new TreeMap<Long, List<Integer>>(),(res,v)->{if(!res.containsKey(v)){res.put(v,Stream.of(i[0]).collect(Collectors.toList())); }else{res.get(v).add(i[0]);}i[0]++;},Map::putAll);}public static<T>TreeMap<T,List<Integer>> mapi(final Stream<T>a,Comparator<T>cmp){int[]i=new int[]{0};return a.collect(cmp !=null?()->new TreeMap<T,List<Integer>>(cmp):()->new TreeMap<T,List<Integer>>(), (res,v)->{if(!res.containsKey(v)){res.put(v,Stream.of(i[0]).collect(Collectors.toList())); }else{res.get(v).add(i[0]);}i[0]++;},Map::putAll);}public static<T>TreeMap<T,List<Integer>> mapi(final Stream<T>a){return mapi(a,null);}public static<T>TreeMap<T,List<Integer>> mapi(final Collection<T>a,Comparator<T>cmp){return mapi(a.stream(),cmp);}public static<T>TreeMap<T,List<Integer>>mapi(final Collection<T>a){return mapi(a.stream()); }public static List<int[]>listi(final int[]a){return IntStream.range(0,a.length).mapToObj(i ->new int[]{a[i],i}).collect(Collectors.toList());}public static List<long[]>listi(final long[]a){return IntStream.range(0,a.length).mapToObj(i->new long[]{a[i],i}).collect(Collectors.toList()); }public static<T>List<Pair<T,Integer>>listi(final T[]a){return IntStream.range(0, a.length).mapToObj(i->new Pair<T,Integer>(a[i],i)).collect(Collectors.toList()); }public static List<int[]>listi(final IntStream a){int[]i=new int[]{0};return a.mapToObj(v ->new int[]{v,i[0]++}).collect(Collectors.toList());}public static List<long[]>listi(final LongStream a){int[]i=new int[]{0};return a.mapToObj(v->new long[]{v,i[0]++}).collect(Collectors.toList()); }public static<T>List<Pair<T,Integer>>listi(final Stream<T>a){int[]i=new int[]{0}; return a.map(v->new Pair<T,Integer>(v,i[0]++)).collect(Collectors.toList());}public static<T>List<Pair<T,Integer>>listi(final Collection<T>a){int[]i=new int[]{0};return a.stream().map(v->new Pair<T,Integer>(v,i[0]++)).collect(Collectors.toList());}public static String join(final int[]a){return Arrays.stream(a).mapToObj(Integer::toString).collect(Collectors.joining(SPACE)); }public static String join(final long[]a){return Arrays.stream(a).mapToObj(Long::toString).collect(Collectors.joining(SPACE)); }public static<T>String join(final T[]a){return Arrays.stream(a).map(v->Objects.toString(v)).collect(Collectors.joining(SPACE)); }public static<T>String join(final T[]a,final Function<T,String>toString){return Arrays.stream(a).map(v->toString.apply(v)).collect(Collectors.joining(SPACE));}public static<T>String join(final Collection<T>a){return a.stream().map(v->Objects.toString(v)).collect(Collectors.joining(SPACE)); }public static<T>String join(final Collection<T>a,final Function<T,String>toString) {return a.stream().map(v->toString.apply(v)).collect(Collectors.joining(SPACE)); }public static<T>String join(final Stream<T>a){return a.map(v->Objects.toString(v)).collect(Collectors.joining(SPACE)); }public static<T>String join(final Stream<T>a,final Function<T,String>toString){ return a.map(v->toString.apply(v)).collect(Collectors.joining(SPACE));}public static <T>String join(final IntStream a){return a.mapToObj(Integer::toString).collect(Collectors.joining(SPACE)); }public static<T>String join(final LongStream a){return a.mapToObj(Long::toString).collect(Collectors.joining(SPACE)); }public static List<Integer>list(final int[]a){return Arrays.stream(a).mapToObj(Integer::valueOf).collect(Collectors.toList()); }public static List<Integer>list(final IntStream a){return a.mapToObj(Integer::valueOf).collect(Collectors.toList()); }public static List<Long>list(final long[]a){return Arrays.stream(a).mapToObj(Long::valueOf).collect(Collectors.toList()); }public static List<Long>list(final LongStream a){return a.mapToObj(Long::valueOf).collect(Collectors.toList()); }public static<T>List<T>list(final Stream<T>a){return a.collect(Collectors.toList()); }public static<T>List<T>list(final Collection<T>a){return a.stream().collect(Collectors.toList()); }public static<T>List<T>list(final T[]a){return Arrays.stream(a).collect(Collectors.toList()); }public static String yesNo(final boolean res){return res?"YES":"NO";}public static String dump(Object obj){String res="";if(obj!=null){Class cl=obj.getClass();String cls=cl.getName();if(cls.startsWith("[")){res+="[";for(int i=0;;i++){try{Object o =Array.get(obj,i);String s=dump(o);if(i>0){res+=", ";}res+=s;}catch(ArrayIndexOutOfBoundsException ex){break;}}res+="]";}else if(Collection.class.isAssignableFrom(cl)){@SuppressWarnings("unchecked")final Object s=((Collection)obj).stream().map(v->dump(v)).collect(Collectors.joining(", ", "[","]"));res+=s.toString();}else if(Map.class.isAssignableFrom(cl)){@SuppressWarnings("unchecked")final Object s=((Map)obj).entrySet().stream().map(v->dump(v)).collect(Collectors.joining(", ", "{","}"));res+=s.toString();}else if(Character.class.isInstance(obj)|| Integer.class.isInstance(obj) || Long.class.isInstance(obj)|| Float.class.isInstance(obj)|| Double.class.isInstance(obj)|| String.class.isInstance(obj) ){res+=Objects.toString(obj);}else if(Map.Entry.class.isInstance(obj)){res+=dump(((Map.Entry)obj).getKey()) +"="+dump(((Map.Entry)obj).getValue());}else if(Stream.class.isInstance(obj)){@SuppressWarnings("unchecked") final Object s=((Stream)obj).map(v->dump(v)).collect(Collectors.joining(", ","[", "]"));res+=s.toString();}else{res+=Stream.concat(Arrays.stream(obj.getClass().getFields()).map(v ->{String name=v.getName();String val;try{Object o=v.get(obj);if(o!=null && v.isAnnotationPresent(Dump.class)) {Dump an=v.getAnnotation(Dump.class);Class ocl=o.getClass();val="{";for(String fn:an.fields()) {try{Field f=ocl.getField(fn);val+=fn+"="+dump(f.get(o))+", ";}catch(NoSuchFieldException nsfex){try{@SuppressWarnings("unchecked")final Method m=ocl.getMethod(fn);val+=fn+"="+dump(m.invoke(o)) +", ";}catch(NoSuchMethodException | IllegalArgumentException | InvocationTargetException nsmex){}}}if(val.endsWith(", ")){val=val.substring(0,val.length()-2);}val+="}";} else{val=dump(o);}}catch(IllegalAccessException ex){val="N/A";}return name+"="+val; }),Arrays.stream(obj.getClass().getMethods()).filter(m->m.isAnnotationPresent(Getter.class)).map(m ->{String name=m.getName();String val;try{Object o=m.invoke(obj);if(o!=null && m.isAnnotationPresent(Dump.class)) {Dump an=m.getAnnotation(Dump.class);Class ocl=o.getClass();val="{";for(String fn:an.fields()) {try{Field f=ocl.getField(fn);val+=fn+"="+dump(f.get(o))+", ";}catch(NoSuchFieldException nsfex){try{@SuppressWarnings("unchecked")final Method m1=ocl.getMethod(fn);val+=fn+"="+dump(m1.invoke(o)) +", ";}catch(NoSuchMethodException | IllegalArgumentException | InvocationTargetException nsmex){}}}if(val.endsWith(", ")){val=val.substring(0,val.length()-2);}val+="}";}else {val=dump(o);}}catch(IllegalAccessException | InvocationTargetException ex){val= "N/A";}return name+"="+val;})).collect(Collectors.joining(", ","{"+obj.getClass().getName() +": ","}"));}}if(res.length()==0){res="<null>";}return res;}}@Retention(RetentionPolicy.RUNTIME) public @interface Dump{String[]fields();}@Retention(RetentionPolicy.RUNTIME)public @interface Getter{}static class MyScanner{private StringBuilder cache=new StringBuilder();int cache_pos=0;private int first_linebreak=-1;private int second_linebreak=-1;private StringBuilder sb= new StringBuilder();private InputStream is=null;public MyScanner(final InputStream is){this.is=is;}public String charToString(final int c){return String.format("'%s'", c=='\n'?"\\n":(c=='\r'?"\\r":String.valueOf((char)c)));}public int get(){int res =-1;if(cache_pos<cache.length()){res=cache.charAt(cache_pos);cache_pos++;if(cache_pos ==cache.length()){cache.delete(0,cache_pos);cache_pos=0;}}else{try{res=is.read(); }catch(IOException ex){throw new RuntimeException(ex);}}return res;}private void unget(final int c){if(cache_pos==0){cache.insert(0,(char)c);}else{cache_pos--;}} public String nextLine(){sb.delete(0,sb.length());int c;boolean done=false;boolean end=false;while((c=get())!=-1){if(check_linebreak(c)){done=true;if(c==first_linebreak) {if(!end){end=true;}else{cache.append((char)c);break;}}else if(second_linebreak!= -1 && c==second_linebreak){break;}}if(end && c!=first_linebreak && c!=second_linebreak) {cache.append((char)c);break;}if(!done){sb.append((char)c);}}return sb.toString(); }private boolean check_linebreak(int c){if(c=='\n'|| c=='\r'){if(first_linebreak ==-1){first_linebreak=c;}else if(c!=first_linebreak && second_linebreak==-1){second_linebreak =c;}return true;}return false;}public int nextInt(){return Integer.parseInt(next()); }public long nextLong(){return Long.parseLong(next());}public boolean hasNext(){ boolean res=false;int c;while((c=get())!=-1){if(!check_linebreak(c)&& c!=' '&& c !='\t'){res=true;unget(c);break;}}return res;}public String next(){sb.delete(0,sb.length()); boolean started=false;int c;while((c=get())!=-1){if(check_linebreak(c)|| c==' '|| c=='\t'){if(started){unget(c);break;}}else{started=true;sb.append((char)c);}}return sb.toString();}public int nextChar(){return get();}public boolean eof(){int c=get(); boolean res=false;if(c!=-1){unget(c);}else{res=true;}return res;}public double nextDouble() {return Double.parseDouble(next());}}static abstract class Solver{protected String nameIn=null;protected String nameOut=null;protected boolean singleTest=false;protected MyScanner sc=null;protected PrintWriter pw=null;private int current_test=0;private int count_tests=0;protected int currentTest(){return current_test;}protected int countTests(){return count_tests;}private void process()throws IOException{if(!singleTest) {count_tests=sc.nextInt();sc.nextLine();for(current_test=1;current_test<=count_tests; current_test++){solve();pw.flush();}}else{count_tests=1;current_test=1;solve();} }abstract protected void solve()throws IOException;public void run()throws IOException {boolean done=false;try{if(nameIn!=null){if(new File(nameIn).exists()){try(FileInputStream fis=new FileInputStream(nameIn);PrintWriter pw0=select_output();){select_output(); done=true;sc=new MyScanner(fis);pw=pw0;process();}}else{throw new RuntimeException("File " +new File(nameIn).getAbsolutePath()+" does not exist!");}}}catch(IOException | AccessControlException ex){}if(!done){try(PrintWriter pw0=select_output();){sc=new MyScanner(System.in); pw=pw0;process();}}}private PrintWriter select_output()throws FileNotFoundException {if(nameOut!=null){return new PrintWriter(nameOut);}return new PrintWriter(System.out); }}static abstract class Tester{static public int getRandomInt(final int min,final int max){return(min+(int)Math.floor(Math.random()*(max-min+1)));}static public long getRandomLong(final long min,final long max){return(min+(long)Math.floor(Math.random() *(max-min+1)));}static public double getRandomDouble(final double min,final double maxExclusive){return(min+Math.random()*(maxExclusive-min));}abstract protected void testOutput(final List<String>output_data);abstract protected void generateInput(); abstract protected String inputDataToString();private boolean break_tester=false; protected void beforeTesting(){}protected void breakTester(){break_tester=true;} public boolean broken(){return break_tester;}}}
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author EndUser */ public class E35PD { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int count = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (a[i] > a[j]) { count++; } } } boolean isEven = (count % 2 == 0); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int m = in.nextInt(); for (int i = 0; i < m; i++) { int l = in.nextInt(); int r = in.nextInt(); int size = (r - l) + 1; int numOfConn = (size - 1) * size / 2; if (numOfConn % 2 == 1) { isEven = !isEven; } if (isEven) { out.write("even"); out.newLine(); } else { out.write("odd"); out.newLine(); } } out.close(); } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static MyScanner scan; static PrintWriter pw; public static void main(String[] args) { new Thread(null,null,"_",1<<25) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { scan = new MyScanner(); pw = new PrintWriter(System.out, true); StringBuilder sb = new StringBuilder(); int n = ni(); int d = ni(); int arr[] = new int[n]; int cnt = 2; for(int i=0;i<n;++i) arr[i] = ni(); for(int i=0;i<n-1;++i) { if(arr[i+1]-d==arr[i]+d) { ++cnt; continue; } if(arr[i+1]-(arr[i]+d)>d) ++cnt; if((arr[i+1]-d)-arr[i]>d) ++cnt; } pl(cnt); pw.flush(); pw.close(); } static long MMI(long A,long MOD) { return modpow(A,MOD-2,MOD); } static long modpow(long x,long y,long MOD) { if(y==0) return 1; if((y&1)==0) return modpow((x*x)%MOD,y>>1,MOD); else return (x*modpow(x,y-1,MOD))%MOD; } static class Pair implements Comparable<Pair> { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(Pair other) { if(this.x!=other.x) return this.x-other.x; return this.y-other.y; } public String toString() { return "{"+x+","+y+"}"; } } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static String ne() throws IOException { return scan.next(); } static String nel() throws IOException { return scan.nextLine(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextLine()throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
/* * UMANG PANCHAL * DAIICT */ import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { static LinkedList<Integer> adj[]; static ArrayList<Integer> adj1[]; static int[] color,visited1; static boolean b[],visited[],possible; static int level[]; static Map<Integer,HashSet<Integer>> s; static int totalnodes,colored; static int count[]; static long sum[]; static int nodes; static double ans=0; static long[] as=new long[10001]; static long c1=0,c2=0; static int[] a,d,k; static int max=100000000; static long MOD = (long)1e9 + 7,sm=0,m=Long.MIN_VALUE; static boolean[] prime=new boolean[1000005]; static int[] levl; static int[] eat; static int price[]; static int size[],res[],par[]; static int result=0; // --------------------My Code Starts Here---------------------- public static void main(String[] args) throws IOException { in=new InputReader(System.in); w=new PrintWriter(System.out); int n=ni(); int[] a=na(n); int ans=0; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(a[j]<a[i]) ans++; } } int m=ni(); ans=ans%2; while(m-->0) { int l=ni(),r=ni(); int range=r-l+1; range=range*(range-1)/2; range=range%2; ans=(ans+range)%2; if(ans==1) w.println("odd"); else w.println("even"); } w.close(); } public static long nCrModp(long n, long r, long p) { long[] C=new long[(int)r+1]; C[0] = 1; for (long i = 1; i <= n; i++) { for (long j = Math.min(i, r); j > 0; j--) C[(int)j] = (C[(int)j] + C[(int)(j-1)])%p; } return C[(int)r]; } public static long nCr(long n, long r) { long x=1; for(long i=n;i>=n-r+1;i--) x=((x)*(i)); for(long i=r;i>=1;i--) x=((x)/(i)); return x%MOD; } public static long nCrModpDP(long n, long r, long p) { long[] C=new long[(int)r+1]; C[0] = 1; for (long i = 1; i <= n; i++) { for (int j = (int)Math.min(i, r); j > 0; j--) C[j] = (C[j] + C[j-1])%p; } return C[(int)r]; } public static long nCrModpLucas(long n,long r, long p) { if (r==0) return 1; long ni = n%p, ri = r%p; return (nCrModpLucas(n/p,r/p, p) * nCrModpDP(ni,ri, p)) % p; } public static void buildgraph(int n){ adj=new LinkedList[n+1]; visited=new boolean[n+1]; levl=new int[n+1]; par=new int[n+1]; for(int i=0;i<=n;i++){ adj[i]=new LinkedList<Integer>(); } } public static int getSum(long BITree[], int index) { int sum = 0; while (index > 0) { sum += BITree[index]; index -= index & (-index); } return sum; } public static long[] updateBIT(long BITree[], int n, int index, int val) { while (index <= n) { BITree[index] += val; index += index & (-index); } return BITree; } public static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true; } // --------------------My Code Ends Here------------------------ public static String ns() { return in.nextLine(); } public static int ni() { return in.nextInt(); } public static long nl() { return in.nextLong(); } public static int[] na(int n) { a=new int[n]; for(int i=0;i<n;i++) a[i]=ni(); return a; } public static void sieveOfEratosthenes() { int n=prime.length; for(int i=0;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*2; i <n; i += p) prime[i] = false; } } } public static boolean printDivisors(long n) { long ans=0; for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i) ans++; else { ans=ans+2; } } if(ans>3) break; } if(ans==3) return true; else return false; } public static void dfs(int i) { visited[i]=true; for(int j:adj[i]) { if(!visited[j]) { dfs(j); nodes++; } } } public static String rev(String s) { StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long gcd(long a, long b) { while (b > 0) { long temp = b; b = a % b; // % is remainder a = temp; } return a; } static InputReader in; static PrintWriter w; 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 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); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { static final long mod=(int)1e9+7; public static void main(String[] args) throws Exception { FastReader in=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int n=in.nextInt(); long ans=0; for(int i=2;2*i<=n;i++) { ans+=i*(n/i-1); } ans*=4; pw.print(ans); pw.flush(); } } class pair { int f,s; } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if(st==null || !st.hasMoreElements()) { 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()); } }
linear
1062_D. Fun with Integers
CODEFORCES
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.lang.reflect.Array; import java.math.*; import java.security.SecureRandom; public class WCS { public static class Vector implements Comparable <Vector> { long x, y; int position; Vector first, second; boolean toReverse; public Vector(long xx, long yy, int p) { x = xx; y = yy; position = p; first = null; second = null; toReverse = false; } public Vector negate() { Vector vv = new Vector(-x, -y, position); vv.first = first; vv.second = second; vv.toReverse = !toReverse; return vv; } public Vector add(Vector v) { Vector sum = new Vector(this.x + v.x, this.y + v.y, position); sum.first = this; sum.second = v; return sum; } public Vector subtract(Vector v) { return this.add(v.negate()); } public double euclideanNorm() { return Math.sqrt(x * x + y * y); } @Override public int compareTo(Vector v) { double thisa = Math.atan2(this.y, this.x); double va = Math.atan2(v.y, v.x); if(thisa < 0) thisa += 2 * Math.PI; if(va < 0) va += 2 * Math.PI; if(thisa < va) return -1; if(thisa > va) return 1; return Integer.compare(this.position, v.position); } @Override public String toString() { return x + " " + y; } } public static void dfs(Vector curr, int[] ans) { if(curr.first == null) { ans[curr.position] = curr.toReverse ? -1 : 1; return; } curr.first.toReverse ^= curr.toReverse; curr.second.toReverse ^= curr.toReverse; dfs(curr.first, ans); dfs(curr.second, ans); } public static boolean ok(Vector v1, Vector v2) { return v1.add(v2).euclideanNorm() <= Math.max(v1.euclideanNorm(), v2.euclideanNorm()); } public static void stop(long k) { long time = System.currentTimeMillis(); while(System.currentTimeMillis() - time < k); } public static void main(String[] args) throws IOException { int n = in.nextInt(); TreeSet <Vector> vectors = new TreeSet <> (); for(int i = 0; i < n; i ++) { Vector v = new Vector(in.nextLong(), in.nextLong(), i); vectors.add(v); } while(vectors.size() > 2) { //System.out.println(vectors); //stop(500); TreeSet <Vector> support = new TreeSet <> (); while(vectors.size() > 0) { Vector curr = vectors.pollFirst(); Vector next1 = vectors.higher(curr); Vector next2 = vectors.lower(curr.negate()); Vector next3 = vectors.higher(curr.negate()); Vector next4 = vectors.lower(curr); //System.out.println("CURR: " + curr + "\n" + next1 + "\n" + next2); if(next1 != null) { if(ok(curr, next1)) { support.add(curr.add(next1)); vectors.remove(next1); continue; } } if(next1 != null) { if(ok(curr, next1.negate())) { support.add(curr.subtract(next1)); vectors.remove(next1); continue; } } if(next2 != null) { if(ok(curr, next2)) { support.add(curr.add(next2)); vectors.remove(next2); continue; } } if(next2 != null) { if(ok(curr, next2.negate())) { support.add(curr.subtract(next2)); vectors.remove(next2); continue; } } if(next3 != null) { if(ok(curr, next3)) { support.add(curr.add(next3)); vectors.remove(next3); continue; } } if(next3 != null) { if(ok(curr, next3.negate())) { support.add(curr.subtract(next3)); vectors.remove(next3); continue; } } if(next4 != null) { if(ok(curr, next4)) { support.add(curr.add(next4)); vectors.remove(next4); continue; } } if(next4 != null) { if(ok(curr, next4.negate())) { support.add(curr.subtract(next4)); vectors.remove(next4); continue; } } support.add(curr); } vectors = support; } if(vectors.size() == 2) { Vector curr = vectors.pollFirst(); Vector next = vectors.pollFirst(); Vector add = curr.add(next); Vector sub = curr.subtract(next); if(sub.euclideanNorm() <= add.euclideanNorm()) vectors.add(sub); else vectors.add(add); } //System.out.println(vectors.first().euclideanNorm()); StringBuilder buffer = new StringBuilder(); int[] ans = new int[n]; dfs(vectors.pollFirst(), ans); for(int i = 0; i < n; i ++) buffer.append(ans[i] + " "); System.out.println(buffer); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } BigInteger nextBigInteger() { return new BigInteger(in.next()); } int nextInt() { return Integer.parseInt(next()); } char nextChar() { return in.next().charAt(0); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader in = new FastReader(); static OutputStream out = new BufferedOutputStream(System.out); public static byte[] toByte(Object o) { return String.valueOf(o).getBytes(); } public static void sop(Object o) { System.out.print(o); } }
nlogn
995_C. Leaving the Bar
CODEFORCES
import java.io.*; import java.lang.reflect.*; public class D { final int MOD = (int)1e9 + 7; final double eps = 1e-12; final int INF = (int)1e9; public D () { long L = sc.nextLong(); long R = sc.nextLong(); int Z = 64 - Long.numberOfLeadingZeros(L ^ R); long res = (1L << Z) - 1; exit(res); } //////////////////////////////////////////////////////////////////////////////////// /* Dear hacker, don't bother reading below this line, unless you want to help me debug my I/O routines :-) */ static MyScanner sc = new MyScanner(); static class MyScanner { public String next() { newLine(); return line[index++]; } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { line = null; return readLine().split(" "); } public char [] nextChars() { return next().toCharArray(); } public Integer [] nextInts() { String [] L = nextStrings(); Integer [] res = new Integer [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } public Long [] nextLongs() { String [] L = nextStrings(); Long [] res = new Long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } public Double [] nextDoubles() { String [] L = nextStrings(); Double [] res = new Double [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Double.parseDouble(L[i]); return res; } public String [] next (int N) { String [] res = new String [N]; for (int i = 0; i < N; ++i) res[i] = sc.next(); return res; } public Integer [] nextInt (int N) { Integer [] res = new Integer [N]; for (int i = 0; i < N; ++i) res[i] = sc.nextInt(); return res; } public Long [] nextLong (int N) { Long [] res = new Long [N]; for (int i = 0; i < N; ++i) res[i] = sc.nextLong(); return res; } public Double [] nextDouble (int N) { Double [] res = new Double [N]; for (int i = 0; i < N; ++i) res[i] = sc.nextDouble(); return res; } public String [][] nextStrings (int N) { String [][] res = new String [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextStrings(); return res; } public Integer [][] nextInts (int N) { Integer [][] res = new Integer [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextInts(); return res; } public Long [][] nextLongs (int N) { Long [][] res = new Long [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextLongs(); return res; } public Double [][] nextDoubles (int N) { Double [][] res = new Double [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextDoubles(); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error(e); } } private final BufferedReader r; MyScanner () { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = readLine().split(" "); index = 0; } } } static void print(Object o, Object... a) { printDelim(" ", o, a); } static void cprint(Object o, Object... a) { printDelim("", o, a); } static void printDelim (String delim, Object o, Object... a) { pw.println(build(delim, o, a)); } static void exit (Object o, Object... a) { print(o, a); exit(); } static void exit () { pw.close(); System.out.flush(); System.err.println("------------------"); System.err.println("Time: " + ((millis() - t) / 1000.0)); System.exit(0); } void NO() { throw new Error("NO!"); } //////////////////////////////////////////////////////////////////////////////////// static String build(String delim, Object o, Object... a) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : a) append(b, p, delim); return b.toString().trim(); } static void append(StringBuilder b, Object o, String delim) { if (o.getClass().isArray()) { int L = Array.getLength(o); for (int i = 0; i < L; ++i) append(b, Array.get(o, i), delim); } else if (o instanceof Iterable<?>) { for (Object p : (Iterable<?>)o) append(b, p, delim); } else b.append(delim).append(o); } //////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new D(); exit(); } static void start() { t = millis(); } static PrintWriter pw = new PrintWriter(System.out); static long t; static long millis() { return System.currentTimeMillis(); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.util.*; import java.io.*; import java.awt.Point; import java.math.BigInteger; import static java.lang.Math.*; // Solution is at the bottom of code public class _AAAA implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; OutputWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new _AAAA(), "", 128 * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeBegin = System.currentTimeMillis(); Locale.setDefault(Locale.US); init(); solve(); out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// String delim = " "; String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(delim); } String readLine() throws IOException{ return in.readLine(); } ///////////////////////////////////////////////////////////////// final char NOT_A_SYMBOL = '\0'; char readChar() throws IOException{ int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } char[] readCharArray() throws IOException{ return readLine().toCharArray(); } ///////////////////////////////////////////////////////////////// int readInt() throws IOException{ return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException{ int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } /////////////////////////////////////////////////////////////////// long readLong() throws IOException{ return Long.parseLong(readString()); } long[] readLongArray(int size) throws IOException{ long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// double readDouble() throws IOException{ return Double.parseDouble(readString()); } double[] readDoubleArray(int size) throws IOException{ double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } ///////////////////////////////////////////////////////////////////// Point readPoint() throws IOException{ return new Point(readInt(), readInt()); } Point[] readPointArray(int size) throws IOException{ Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// class OutputWriter extends PrintWriter{ final int DEFAULT_PRECISION = 12; int precision; String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } public OutputWriter(OutputStream out) { super(out); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public int getPrecision() { return precision; } public void setPrecision(int precision) { this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } private String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } public void printWithSpace(double d){ printf(formatWithSpace, d); } public void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } public void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; boolean check(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// void solve() throws IOException{ int n = readInt(); int k = readInt(); Map<Long, Integer> map = new TreeMap<Long, Integer>(); for (int i = 0; i < n; ++i){ map.put(readLong(), i); } int ans = 0; boolean[] used = new boolean[n]; for (Map.Entry<Long, Integer> e: map.entrySet()){ if (used[e.getValue()]) continue; long value = e.getKey() * k; Integer index = map.get(value); if (index != null){ used[index] = true; } ++ans; } out.println(ans); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class A { static BufferedReader in; static PrintWriter out; static StringTokenizer st; static Random rnd; void solve() throws IOException { int n = nextInt(); int[] arr = new int[n]; Integer[] arrCopy = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = arrCopy[i] = nextInt(); Arrays.sort(arrCopy); int bad = 0; for (int i = 0; i < n; i++) if (arr[i] != arrCopy[i]) ++bad; boolean fail = bad > 2; out.println(!fail ? "YES" : "NO"); } public static void main(String[] args) { new A().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); rnd = new Random(); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(42); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.Scanner; public class AlexAndARhombus { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); System.out.println(n*n+(n-1)*(n-1)); sc.close(); } }
constant
1180_A. Alex and a Rhombus
CODEFORCES
import java.util.Scanner; public class ToyArmy { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); System.out.println(n / 2 + n); } }
constant
84_A. Toy Army
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); E solver = new E(); solver.solve(1, in, out); out.close(); } static class E { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.ni(), K = in.ni(); long mod = 998244353; long[][] dp = new long[n + 1][n + 1]; for (int lim = 1; lim <= n; lim++) { long sum = 1; dp[0][lim] = 1; for (int i = 1; i <= n; i++) { dp[i][lim] = (dp[i][lim] + sum) % mod; sum = (sum + dp[i][lim]) % mod; if (i >= lim) sum = (sum - dp[i - lim][lim] + mod) % mod; } } long ans = 0; for (int k = 1; k < Math.min(K, n + 1); k++) { long h = dp[n][k] - dp[n][k - 1]; int lim = K / k; if (K % k == 0) lim--; if (lim > n) lim = n; ans += dp[n][lim] * h % mod; } out.println(2 * ans % mod); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int ni() { return Integer.parseInt(ns()); } } }
quadratic
1027_E. Inverse Coloring
CODEFORCES
/** * @author derrick20 */ import java.io.*; import java.util.*; public class PetyaSpiders implements Runnable { public static void main(String[] args) throws Exception { new Thread(null, new PetyaSpiders(), ": )", 1 << 28).start(); } public void run() { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); M = sc.nextInt(); if (N > M) { int temp = N; N = M; M = temp; } // if the max is 1, then 1x1. Else, one dimension is at least 2, so // our idea of sliding forward a 2xN window works if (M == 1) { out.println(0); } else { int[][][] dp = new int[M][1 << N][1 << N]; // N, M are at least 2. N <= 6 // base case: try all prev and curr masks, let next = 0 for (int prev = 0; prev < 1 << N; prev++) { // we cannot allow the previous to have anything except for 0's. // this matters for M = 2, since at the end of the dp we are // doing a special case for the final column where we need to // ensure both curr AND next are validly covered if (prev == 0) { for (int curr = 0; curr < 1 << N; curr++) { // all of these will satisfy the nonexistent columns, of course dp[0][prev][curr] = Integer.bitCount(curr); } } else { // not allowed to have nonzero previous spiders Arrays.fill(dp[0][prev], oo); } } for (int prev = 0; prev < 1 << N; prev++) { for (int curr = 0; curr < 1 << N; curr++) { if (isValid(0, prev, curr)) { dp[1][prev][curr] = Integer.bitCount(prev) + Integer.bitCount(curr); } else { dp[1][prev][curr] = oo; } } } for (int col = 2; col <= M - 2; col++) { for (int next = 0; next < 1 << N; next++) { for (int curr = 0; curr < 1 << N; curr++) { dp[col][curr][next] = oo; for (int prev = 0; prev < 1 << N; prev++) { if (dp[col - 1][prev][curr] != oo && isValid(prev, curr, next)) { dp[col][curr][next] = Math.min(dp[col][curr][next], dp[col - 1][prev][curr] + Integer.bitCount(next)); } } } } } // to get the answer, we need to act on the last column by trying to // ensure that both the prev row AND the current row are valid // basically, isValid(prev, curr, next) && isValid(curr, next, 0) int ans = oo; for (int next = 0; next < 1 << N; next++) { for (int curr = 0; curr < 1 << N; curr++) { dp[M - 1][curr][next] = oo; for (int prev = 0; prev < 1 << N; prev++) { if (dp[M - 2][prev][curr] != oo && isValid(prev, curr, next) && isValid(curr, next, 0)) { dp[M - 1][curr][next] = Math.min(dp[M - 1][curr][next], dp[M - 2][prev][curr] + Integer.bitCount(next)); ans = Math.min(ans, dp[M - 1][curr][next]); } } } } // for (int c = 1; c < M; c++) { // System.out.println("For col = " + c); // for (int prev = 0; prev < 1 << N; prev++) { // System.out.println("Prev = " + Integer.toBinaryString(prev)); // for (int curr = 0; curr < 1 << N; curr++) { // System.out.println("Curr = " + Integer.toBinaryString(curr) + " gives " + dp[c][prev][curr] + " "); // } // } // } out.println(N * M - ans); } out.close(); } static int N, M; static int oo = 999; static int[] dr = {1, 0, -1, 0}, dc = {0, 1, 0, -1}; static boolean isValid(int prev, int curr, int next) { boolean[][] grid = new boolean[N][3]; int[] subsets = {prev, curr, next}; for (int r = 0; r < N; r++) { for (int c = 0; c < 3; c++) { if ((subsets[c] & 1) > 0) { grid[r][c] = true; for (int k = 0; k < 4; k++) { int r2 = r + dr[k]; int c2 = c + dc[k]; if (0 <= r2 && r2 <= N - 1 && 0 <= c2 && c2 <= 2) { grid[r2][c2] = true; } } } subsets[c] >>= 1; } } for (int r = 0; r < N; r++) { if (!grid[r][1]) { // we only need to ensure the middle is safe return false; } } return true; } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { 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 int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Andy Phan */ public class p1096f { static long MOD = 998244353; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); BIT invert = new BIT(n+5); BIT neg = new BIT(n+5); long res = 0; int[] arr = new int[n]; boolean[] has = new boolean[n+1]; long num1 = 0; for(int i = 0; i < n; i++) { arr[i] = in.nextInt(); if(arr[i] != -1) { res += invert.read(n+5)-invert.read(arr[i]); res %= MOD; invert.update(arr[i], 1); has[arr[i]] = true; } else num1++; } if(num1 == 0) { System.out.println(res); return; } for(int i = 1; i <= n; i++) if(!has[i]) neg.update(i, 1); long invertNum1 = modInv(num1, MOD); res += ((num1*(num1-1))%MOD)*modInv(4, MOD); res %= MOD; long cnt = 0; for(int i = 0; i < n; i++) { if(arr[i] == -1) { cnt++; continue; } res += (((neg.read(n+5)-neg.read(arr[i]))*cnt)%MOD)*invertNum1; res %= MOD; } cnt = 0; for(int i = n-1; i >= 0; i--) { if(arr[i] == -1) { cnt++; continue; } res += (((neg.read(arr[i]))*cnt)%MOD)*invertNum1; res %= MOD; } System.out.println(res); } //@ static class BIT { int n; int[] tree; public BIT(int n) { this.n = n; tree = new int[n + 1]; } int read(int i) { int sum = 0; while (i > 0) { sum += tree[i]; i -= i & -i; } return sum; } void update(int i, int val) { while (i <= n) { tree[i] += val; i += i & -i; } } //$ } //@ // Computes the modular inverse of x // Returns 0 if the GCD of x and mod is not 1 // O(log n) : Can be converted to use BigIntegers static long modInv(long x, long mod) { return (BigInteger.valueOf(x).modInverse(BigInteger.valueOf(mod))).longValue(); } static long modInv(long a, long b, long y0, long y1, long q0, long q1) { long y2 = y0 - y1*q0; return b == 0 ? y2 : modInv(b, a % b, y1, y2, q1, a / b); } //@ static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a / gcd(a, b) * b; } }
nlogn
1096_F. Inversion Expectation
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class D { static byte[] buf = new byte[1<<26]; static int bp = -1; public static void main(String[] args) throws IOException { /**/ DataInputStream in = new DataInputStream(System.in); /*/ DataInputStream in = new DataInputStream(new FileInputStream("src/d.in")); /**/ in.read(buf, 0, 1<<26); int n = nni(); int m = nni(); int k = nni(); if (k%2==1) { for (int i = 0; i < n; ++i) { StringBuilder ans = new StringBuilder(); String sp = ""; for (int j = 0; j < m; ++j) { ans.append(sp+"-1"); sp = " "; } System.out.println(ans); } return; } int[][] lr = new int[n][m-1]; int[][] ud = new int[n-1][m]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m-1; ++j) { lr[i][j] = nni(); } } for (int i = 0; i < n-1; ++i) { for (int j = 0; j < m; ++j) { ud[i][j] = nni(); } } int[][][] ans = new int[k/2+1][n][m]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { for (int q = 1; q <= k/2; ++q) { ans[q][i][j] = 123456789; } } } for (int uq = 0; uq < k/2; ++uq) { for (int ui = 0; ui < n; ++ui) { for (int uj = 0; uj < m; ++uj) { int w = ans[uq][ui][uj]; if (ui>0 && w+ud[ui-1][uj]<ans[uq+1][ui-1][uj]) { ans[uq+1][ui-1][uj] = w+ud[ui-1][uj]; } if (ui<n-1 && w+ud[ui][uj]<ans[uq+1][ui+1][uj]) { ans[uq+1][ui+1][uj] = w+ud[ui][uj]; } if (uj>0 && w+lr[ui][uj-1]<ans[uq+1][ui][uj-1]) { ans[uq+1][ui][uj-1] = w+lr[ui][uj-1]; } if (uj<m-1 && w+lr[ui][uj]<ans[uq+1][ui][uj+1]) { ans[uq+1][ui][uj+1] = w+lr[ui][uj]; } } } } for (int i = 0; i < n; ++i) { StringBuilder as = new StringBuilder(); String sp = ""; for (int j = 0; j < m; ++j) { as.append(sp+ans[k/2][i][j]*2); sp = " "; } System.out.println(as); } } public static int nni() { int ret = 0; byte b = buf[++bp]; while (true) { ret = ret*10+b-'0'; b = buf[++bp]; if (b<'0'||b>'9') { while (buf[bp+1]=='\r'||buf[bp+1]=='\n'||buf[bp+1]==' ') {++bp;} break; } } return ret; } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; import java.io.IOException; import java.io.InputStream; public class Main { public static void main(String[] args) { File file = new File("in.txt"); File fileOut = new File("out.txt"); InputStream inputStream = null; OutputStream outputStream = null; // try {inputStream= new FileInputStream(file);} catch (FileNotFoundException ex){return;}; // try {outputStream= new FileOutputStream(fileOut);} catch (FileNotFoundException ex){return;}; inputStream = System.in; outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, in, out); out.close(); } } class Task { private final int mod = 1000000007; public void solve(int testNumber, InputReader in, PrintWriter out) { Integer n = in.nextInt(); List<Character> comm = new ArrayList<>(n); for(int i=0; i<n; i++){ comm.add(in.next().charAt(0)); } long[][] dp = new long[n][n]; dp[0][0] = 1; for(int i=1; i<n; i++){ Character lastComm = comm.get(i-1); if(lastComm.equals('f')){ dp[i][0] = 0; for(int j=1; j<n; j++){ dp[i][j] = dp[i-1][j-1]; } } else{ Long suffixSum = dp[i-1][n-1]; for(int j=n-1; j>=0; j--){ dp[i][j] = suffixSum; if(j>0) { suffixSum += dp[i - 1][j - 1] % mod; } } } } Long finalSum = 0L; for(int i=0; i<n; i++){ finalSum += dp[n-1][i] % mod; } out.println(finalSum % mod); } } 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 String nextLine(){ try { return reader.readLine(); } catch (IOException e){ throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } class Pair<F, S> { public final F first; public final S second; public Pair(F first, S second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.first, first) && Objects.equals(p.second, second); } @Override public int hashCode() { return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); } @Override public String toString() { return "(" + first + ", " + second + ')'; } } class IntPair extends Pair<Integer, Integer>{ public IntPair(Integer first, Integer second){ super(first, second); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.*; import java.util.*; public class ProblemA { InputReader in; PrintWriter out; void solve() { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); Arrays.sort(a); int d = k; int cur = n - 1; int ans = 0; while (d < m && cur >= 0) { d += a[cur] - 1; cur--; ans++; } if (d >= m) out.println(ans); else out.println("-1"); } ProblemA(){ boolean oj = System.getProperty("ONLINE_JUDGE") != null; try { if (oj) { in = new InputReader(System.in); out = new PrintWriter(System.out); } else { Writer w = new FileWriter("output.txt"); in = new InputReader(new FileReader("input.txt")); out = new PrintWriter(w); } } catch(Exception e) { throw new RuntimeException(e); } solve(); out.close(); } public static void main(String[] args){ new ProblemA(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public InputReader(FileReader fr) { reader = new BufferedReader(fr); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
nlogn
257_A. Sockets
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; public class C186D2A { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); if (n >= 0) { out.println(Math.abs(n)); } else { out.println(Math.max(n/10, (n/100)*10 + n%10)); } out.flush(); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static long factorial[],invFactorial[]; static ArrayList<Pair> graph[]; static boolean oj = System.getProperty("ONLINE_JUDGE") != null; /****************************************Solutions Begins***************************************/ static int n,m; static long cost[][],dp[]; public static void main(String[] args) throws Exception{ String st[]=nl(); n=pi(st[0]); m=pi(st[1]); st=nl(); String str=st[0]; int mn=10000; for(int i=0;i<n;i++){ mn=Math.min(mn,str.charAt(i)); } cost=new long[m][m]; for(int i=1;i<n;i++){ int a1=str.charAt(i-1)-mn; int a2=str.charAt(i)-mn; if(a1==a2)continue; cost[a1][a2]++; cost[a2][a1]++; } int mm=1<<m; dp=new long[mm]; Arrays.fill(dp,Long.MAX_VALUE/2); dp[0]=0; //debug(cost); long cntbit[]=new long[mm]; int minbit[]=new int[mm]; for(int mask=1;mask<mm;mask++){ cntbit[mask]=1+cntbit[(mask&(mask-1))]; for(int i=0;i<m;i++){ if(((mask>>i)&1)!=0){ minbit[mask]=i; break; } } } long cntcost[][]=new long[mm][m]; for(int mask=0;mask<mm;mask++){ for(int i=0;i<m;i++){ int b=minbit[mask]; cntcost[mask][i]=cntcost[mask^(1<<b)][i]+cost[i][b]; } } int yy=mm-1; for(int mask=0;mask<mm;mask++){ long cnt=cntbit[mask]; for(int i=0;i<m;i++){ if(((mask>>i)&1)!=0){ long ans=cnt*(cntcost[mask][i]-cntcost[yy^mask][i]); dp[mask]=Math.min(dp[mask],dp[mask^(1<<i)]+ans); } } } out.println(dp[mm-1]); /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ static String[] nl() throws Exception{ return br.readLine().split(" "); } static String[] nls() throws Exception{ return br.readLine().split(""); } static int pi(String str) { return Integer.parseInt(str); } static long pl(String str){ return Long.parseLong(str); } static double pd(String str){ return Double.parseDouble(str); } /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.000000000000000000000"); out.println(ft.format(d)); } /**************************************Bit Manipulation**************************************************/ static void printMask(long mask){ System.out.println(Long.toBinaryString(mask)); } static int countBit(long mask){ int ans=0; while(mask!=0){ if(mask%2==1){ ans++; } mask/=2; } return ans; } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new ArrayList[n]; for(int i=0;i<n;i++){ graph[i]=new ArrayList<>(); } } static void addEdge(int a,int b){ graph[a].add(new Pair(b,1)); } static void addEdge(int a,int b,int c){ graph[a].add(new Pair(b,c)); } /*********************************************PAIR********************************************************/ static class PairComp implements Comparator<Pair>{ public int compare(Pair p1,Pair p2){ return p1.u-p2.u; } } static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /******************************************Long Pair*******************************************************/ static class PairCompL implements Comparator<Pairl>{ public int compare(Pairl p1,Pairl p2){ long a=p1.u*p2.v; long b=p2.u*p1.v; if(a>b){ return -1; } else if(a<b){ return 1; } else{ return 0; } } } static class Pairl implements Comparable<Pairl> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pairl other = (Pairl) o; return u == other.u && v == other.v; } public int compareTo(Pairl other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o) { if(!oj) System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c) { long x=1; long y=a%c; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y) { if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /********************************************End***********************************************************/ }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.util.*; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Comp c1 = getComp(scanner); Comp c2 = getComp(scanner); c1.sortByPrice(); c2.sortByPrice(); int i = 0; int j = 0; while(i < c1.num || j < c2.num) { Elem xi = (i < c1.num) ? c1.elems.get(i) : null; Elem yj = (j < c2.num) ? c2.elems.get(j) : null; if(xi != null && yj != null) { if(xi.price >= yj.price) { if(!c2.resultSet.contains(xi)) { c1.resultSet.add(xi); } i++; } else { if(!c1.resultSet.contains(yj)) { c2.resultSet.add(yj); } j++; } } else if(xi != null) { if(!c2.resultSet.contains(xi)) { c1.resultSet.add(xi); } i++; } else { if(!c1.resultSet.contains(yj)) { c2.resultSet.add(yj); } j++; } } long result = c1.getResultPrice() + c2.getResultPrice(); System.out.println(result); } private static Comp getComp(Scanner scanner) { Comp c = new Comp(); c.num = scanner.nextInt(); for(int i = 0; i < c.num; i++) { c.addElem(scanner.nextLong(), scanner.nextLong()); } return c; } } class Comp { int num; List<Elem> elems = new ArrayList<>(); Set<Elem> resultSet = new HashSet<>(); void addElem(long el, long pr) { Elem elem = new Elem(el, pr); elems.add(elem); } void sortByPrice() { Collections.sort(elems); } long getResultPrice() { long sumPrice = 0; for(Elem elem : resultSet) { sumPrice += elem.price; } return sumPrice; } } class Elem implements Comparable<Elem> { long elem; long price; public Elem(long el, long pr) { this.elem = el; this.price = pr; } public int compareTo(Elem other) { return (int) (other.price - price); } public boolean equals(Object o) { if(!(o instanceof Elem)) { return false; } Elem other = (Elem) o; return (other.elem == elem); } public int hashCode() { return (int) elem; } public String toString() { return "(" + elem + ", " + price + ")"; } }
nlogn
981_B. Businessmen Problems
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); //inputs long n = in.nextLong(); if(n == 1) System.out.println(1); else if(n == 2) System.out.println(2); else if(n % 2 == 0){ int cnt = nPrime(n); if(cnt == 1) System.out.println((n) * (n-1) * (n-3)); else if(cnt > 1) System.out.println((n-1) * (n-2) * (n-3)); } else System.out.println((n) * (n-1) * (n-2)); } public static int nPrime(long n){ int cnt=1; if(n % 3 == 0) cnt++; return cnt; } }
constant
235_A. LCM Challenge
CODEFORCES
import java.util.*; import java.io.*; public class _1517_D { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer line = new StringTokenizer(in.readLine()); int n = Integer.parseInt(line.nextToken()); int m = Integer.parseInt(line.nextToken()); int k = Integer.parseInt(line.nextToken()); int[][] edges1 = new int[n][m - 1]; int[][] edges2 = new int[n - 1][m]; for(int i = 0; i < n; i++) { line = new StringTokenizer(in.readLine()); for(int j = 0; j < m - 1; j++) { edges1[i][j] = Integer.parseInt(line.nextToken()); } } for(int i = 0; i < n - 1; i++) { line = new StringTokenizer(in.readLine()); for(int j = 0; j < m; j++) { edges2[i][j] = Integer.parseInt(line.nextToken()); } } if(k % 2 == 1) { for(int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < m; j++) { sb.append(-1); if(j < m - 1) sb.append(' '); } out.println(sb.toString()); } }else { int[][][] dp = new int[n][m][k + 1]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { Arrays.fill(dp[i][j], Integer.MAX_VALUE); dp[i][j][0] = 0; } } for(int a = 2; a <= k; a += 2) { for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(i > 0) { dp[i][j][a] = Math.min(dp[i][j][a], dp[i - 1][j][a - 2] + 2 * edges2[i - 1][j]); } if(i < n - 1) { dp[i][j][a] = Math.min(dp[i][j][a], dp[i + 1][j][a - 2] + 2 * edges2[i][j]); } if(j > 0) { dp[i][j][a] = Math.min(dp[i][j][a], dp[i][j - 1][a - 2] + 2 * edges1[i][j - 1]); } if(j < m - 1) { dp[i][j][a] = Math.min(dp[i][j][a], dp[i][j + 1][a - 2] + 2 * edges1[i][j]); } } } } for(int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); for(int j = 0; j < m; j++) { sb.append(dp[i][j][k]); if(j < m - 1) sb.append(' '); } out.println(sb.toString()); } } in.close(); out.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; @SuppressWarnings("Duplicates") public class C817 { private FastScanner in; private PrintWriter out; private long calcSum(long x) { int ans = 0; while (x > 0) { ans += x % 10; x /= 10; } return ans; } private long calcDiff(long x) { return x - calcSum(x); } private long binSearch(long n, long s) { long l = 0; long r = n + 1; while (r - l > 1) { long m = (r + l) >> 1; if (calcDiff(m) >= s) { r = m; } else { l = m; } } return l; } private void solve() throws IOException { long n = in.nextLong(); long s = in.nextLong(); long ans = binSearch(n, s); out.println(n - ans); } private void run() { try { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } 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()); } } public static void main(String[] arg) { new C817().run(); } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Array; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.*; public class CFContest { public static void main(String[] args) throws Exception { boolean local = System.getProperty("ONLINE_JUDGE") == null; boolean async = true; Charset charset = Charset.forName("ascii"); FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset); Task task = new Task(io, new Debug(local)); if (async) { Thread t = new Thread(null, task, "dalt", 1 << 27); t.setPriority(Thread.MAX_PRIORITY); t.start(); t.join(); } else { task.run(); } if (local) { io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M"); } io.flush(); } public static class Task implements Runnable { final FastIO io; final Debug debug; int inf = (int) 1e8; long lInf = (long) 1e18; public Task(FastIO io, Debug debug) { this.io = io; this.debug = debug; } @Override public void run() { int t = io.readInt(); while (t-- > 0) solve1(); } public void solve1() { cache.clear(); int n = io.readInt(); int m = io.readInt(); Col[] mat = new Col[m]; for (int i = 0; i < m; i++) { mat[i] = new Col(); mat[i].data = new int[n]; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int v = io.readInt(); mat[j].data[i] = v; mat[j].max = Math.max(mat[j].max, v); } } Arrays.sort(mat, (a, b) -> -(a.max - b.max)); mat = Arrays.copyOf(mat, Math.min(n, m)); io.cache.append(bf(mat, getCol(n), n, 0)).append('\n'); } public void enhance(Col mask, Col c, Col ans, int n) { for (int i = 0; i < n; i++) { ans.data[i] = Math.max(mask.get(i), c.get(i)); } } Deque<Col> cache = new ArrayDeque<>(); public Col getCol(int n) { if (cache.isEmpty()) { Col col = new Col(); col.data = new int[n]; return col; } return cache.removeFirst(); } public void destroy(Col c) { c.offset = 0; c.max = 0; cache.addLast(c); } public int bf(Col[] cols, Col mask, int n, int k) { if (k >= cols.length) { int sum = 0; for (int i = 0; i < n; i++) { sum += mask.data[i]; } return sum; } int max = 0; cols[k].offset = 0; for (int i = 0; i < n; i++) { Col c = getCol(n); enhance(mask, cols[k], c, n); max = Math.max(max, bf(cols, c, n, k + 1)); destroy(c); cols[k].turn(); } return max; } } public static class Col { int[] data; int offset; public int get(int i) { return data[(i + offset) % data.length]; } public void turn() { offset++; } int max; } public static class FastIO { public final StringBuilder cache = new StringBuilder(20 << 20); private final InputStream is; private final OutputStream os; private final Charset charset; private StringBuilder defaultStringBuf = new StringBuilder(1 << 8); private byte[] buf = new byte[1 << 20]; private int bufLen; private int bufOffset; private int next; public FastIO(InputStream is, OutputStream os, Charset charset) { this.is = is; this.os = os; this.charset = charset; } public FastIO(InputStream is, OutputStream os) { this(is, os, Charset.forName("ascii")); } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public long readLong() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } long val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public double readDouble() { boolean sign = true; skipBlank(); if (next == '+' || next == '-') { sign = next == '+'; next = read(); } long val = 0; while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } if (next != '.') { return sign ? val : -val; } next = read(); long radix = 1; long point = 0; while (next >= '0' && next <= '9') { point = point * 10 + next - '0'; radix = radix * 10; next = read(); } double result = val + (double) point / radix; return sign ? result : -result; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } public int readLine(char[] data, int offset) { int originalOffset = offset; while (next != -1 && next != '\n') { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(byte[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (byte) next; next = read(); } return offset - originalOffset; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } public void flush() { try { os.write(cache.toString().getBytes(charset)); os.flush(); cache.setLength(0); } catch (IOException e) { throw new RuntimeException(e); } } public boolean hasMore() { skipBlank(); return next != -1; } } public static class Debug { private boolean allowDebug; public Debug(boolean allowDebug) { this.allowDebug = allowDebug; } public void assertTrue(boolean flag) { if (!allowDebug) { return; } if (!flag) { fail(); } } public void fail() { throw new RuntimeException(); } public void assertFalse(boolean flag) { if (!allowDebug) { return; } if (flag) { fail(); } } private void outputName(String name) { System.out.print(name + " = "); } public void debug(String name, int x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, long x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, double x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, int[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, long[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, double[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, Object x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, Object... x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.deepToString(x)); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Solution23A { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ 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()); } public static void main(String[] args){ new Solution23A().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); } } void solve() throws IOException{ char[] t = readString().toCharArray(); int max = 0; for(int i = 0; i < t.length; i++){ for(int j = i + 1; j < t.length; j++){ for(int k = 0; k < t.length - j; k++){ if(t[i+k] == t[j+k]) max = max(max, k+1); else break; } } } out.println(max); } int ModExp(int a, int n, int mod){ int res = 1; while (n!=0) if ((n & 1) != 0) { res = (res*a)%mod; --n; } else { a = (a*a)%mod; n >>= 1; } return res; } static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int leftIndex, int rightIndex) { final int MAGIC_VALUE = 50; 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; } } } boolean isPrime(int a){ for(int i = 2; i <= sqrt(a); i++) if(a % i == 0) return false; return true; } static double distance(long x1, long y1, long x2, long y2){ return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long gcd(long a, long b){ if(min(a,b) == 0) return max(a,b); return gcd(max(a, b) % min(a,b), min(a,b)); } static long lcm(long a, long b){ return a * b /gcd(a, b); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; public class R495A { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(), k=scan.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=scan.nextInt(); int res=2; for(int i=0;i<n-1;i++) { if(a[i+1]-a[i]>2*k) res+=2; else if(a[i+1]-a[i]==2*k) res++; } System.out.println(res); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int digitsum(long n) { int ans = 0; while (n > 0) { ans += n % 10; n /= 10; } return ans; } public void solve(int testNumber, InputReader in, PrintWriter out) { long n = in.nextLong(); long s = in.nextLong(); if (s >= n) { out.println(0); return; } long ans = s; while (ans < s + digitsum(ans)) { ans++; } if (n >= ans) { out.println(n - ans + 1); } else { out.println(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 long nextLong() { return Long.parseLong(next()); } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } class GraphBuilder { int n, m; int[] x, y; int index; int[] size; GraphBuilder(int n, int m) { this.n = n; this.m = m; x = new int[m]; y = new int[m]; size = new int[n]; } void add(int u, int v) { x[index] = u; y[index] = v; size[u]++; size[v]++; index++; } int[][] build() { int[][] graph = new int[n][]; for (int i = 0; i < n; i++) { graph[i] = new int[size[i]]; } for (int i = index - 1; i >= 0; i--) { int u = x[i]; int v = y[i]; graph[u][--size[u]] = v; graph[v][--size[v]] = u; } return graph; } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long[] readLongArray(int size) throws IOException { long[] res = new long[size]; for (int i = 0; i < size; i++) { res[i] = readLong(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Template().run(); // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } void solve() throws IOException { int n = readInt(); int m = readInt(); int max = 1 << n; long[][] dp = new long[n][max]; for (int i = 0; i < n; i++) { dp[i][1 << i] = 1; } GraphBuilder gb = new GraphBuilder(n, m); for (int i = 0; i < m; i++) { gb.add(readInt() - 1, readInt() - 1); } int[][] graph = gb.build(); for (int mask = 1; mask < max; mask++) { int firstBit = -1; for (int i = 0; i < n; i++) { if (hasBit(mask, i)) { firstBit = i; break; } } for (int last = 0; last < n; last++) { if (dp[last][mask] == 0) continue; for (int y : graph[last]) { if (!hasBit(mask, y) && y > firstBit) { dp[y][mask | (1 << y)] += dp[last][mask]; } } } } long answer = 0; for (int i = 1; i < max; i++) { if (Integer.bitCount(i) < 3) continue; int firstBit = -1; for (int j = 0; j < n; j++) { if (hasBit(i, j)) { firstBit = j; break; } } for (int y : graph[firstBit]) { answer += dp[y][i]; } } out.println(answer / 2); } boolean hasBit(int mask, int bit) { return (mask & (1 << bit)) != 0; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class CF387D { static class A { ArrayList<Integer> list = new ArrayList<>(); int u, v, d; } static int INF = Integer.MAX_VALUE; static boolean bfs(A[] aa, int n) { LinkedList<Integer> queue = new LinkedList<>(); for (int u = 1; u <= n; u++) if (aa[u].v > 0) aa[u].d = INF; else { aa[u].d = 0; queue.addLast(u); } aa[0].d = INF; while (!queue.isEmpty()) { int u = queue.removeFirst(); if (aa[u].d + 1 == aa[0].d) break; for (int v : aa[u].list) { int w = aa[v].u; if (aa[w].d == INF) { aa[w].d = aa[u].d + 1; queue.addLast(w); } } } return aa[0].d != INF; } static boolean dfs(A[] aa, int n, int u) { if (u == 0) return true; for (int v : aa[u].list) { int w = aa[v].u; if (aa[w].d == aa[u].d + 1 && dfs(aa, n, w)) { aa[u].v = v; aa[v].u = u; return true; } } aa[u].d = INF; return false; } static int matchings(A[] aa, int n) { int cnt = 0; while (bfs(aa, n)) for (int u = 1; u <= n; u++) if (aa[u].v == 0 && dfs(aa, n, u)) cnt++; return cnt; } 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[] eu = new int[m]; int[] ev = new int[m]; for (int j = 0; j < m; j++) { st = new StringTokenizer(br.readLine()); eu[j] = Integer.parseInt(st.nextToken()); ev[j] = Integer.parseInt(st.nextToken()); } A[] aa = new A[n + 1]; int min = m + n * 3; for (int ctr = 1; ctr <= n; ctr++) { boolean loop = false; boolean[] ci = new boolean[n + 1]; boolean[] co = new boolean[n + 1]; for (int i = 0; i <= n; i++) aa[i] = new A(); int m_ = 0; for (int j = 0; j < m; j++) { int u = eu[j]; int v = ev[j]; if (u == ctr && v == ctr) loop = true; else if (u == ctr && v != ctr) ci[v] = true; else if (u != ctr && v == ctr) co[u] = true; else { aa[u].list.add(v); m_++; } } int cnt = loop ? 0 : 1; for (int i = 1; i <= n; i++) if (i != ctr) { if (!ci[i]) cnt++; if (!co[i]) cnt++; } int m2 = matchings(aa, n); cnt += (m_ - m2) + (n - 1 - m2); if (min > cnt) min = cnt; } System.out.println(min); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
// practice with rainboy import java.io.*; import java.util.*; public class CF111C extends PrintWriter { CF111C() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF111C o = new CF111C(); o.main(); o.flush(); } int encode(int[] aa, int m) { int a = 0; for (int j = 0; j < m; j++) a = a * 3 + aa[j]; return a; } void decode(int[] aa, int m, int a, int base) { for (int j = m - 1; j >= 0; j--) { aa[j] = a % base; a /= base; } } void main() { int n = sc.nextInt(); int m = sc.nextInt(); if (n < m) { int tmp = n; n = m; m = tmp; } int p = 1; for (int j = 0; j < m; j++) p *= 3; int[] dp = new int[p]; int[] dq = new int[p]; int[] aa = new int[m]; int[] bb = new int[m]; for (int j = 0; j < m; j++) aa[j] = 1; Arrays.fill(dp, -1); dp[encode(aa, m)] = 0; while (n-- > 0) { Arrays.fill(dq, -1); for (int a = 0; a < p; a++) { if (dp[a] < 0) continue; decode(aa, m, a, 3); for (int b = 0; b < 1 << m; b++) { decode(bb, m, b, 2); boolean bad = false; for (int j = 0; j < m; j++) if (aa[j] == 0 && bb[j] == 0) { bad = true; break; } if (bad) continue; int cnt = 0; for (int j = 0; j < m; j++) if (bb[j] == 1) { bb[j] = 2; cnt++; } for (int j = 0; j < m; j++) if (bb[j] == 0 && (aa[j] == 2 || j > 0 && bb[j - 1] == 2 || j + 1 < m && bb[j + 1] == 2)) bb[j] = 1; int a_ = encode(bb, m); dq[a_] = Math.max(dq[a_], dp[a] + m - cnt); } } int[] tmp = dp; dp = dq; dq = tmp; } int ans = 0; for (int a = 0; a < p; a++) { if (dp[a] <= ans) continue; decode(aa, m, a, 3); boolean bad = false; for (int j = 0; j < m; j++) if (aa[j] == 0) { bad = true; break; } if (!bad) ans = dp[a]; } println(ans); } }
np
111_C. Petya and Spiders
CODEFORCES
//بسم الله الرحمن الرحيم import java.util.*; import java.lang.*; import java.nio.*; import java.io.*; public class as { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[100000000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } ///////////////////////////////////////////////////////////// public static void main(String[] args) throws Exception { Reader sc=new Reader(); StringBuilder finalAnswer=new StringBuilder(); //finalAnswer.append(1).append('\n'); int t=sc.nextInt(); while(t-->0) { int count=0; int n=sc.nextInt(); if(n==2 || n==4) { finalAnswer.append("YES").append('\n'); count++; } if(n%2==0 && count==0){ n/=2; if((int)Math.sqrt(n)*(int)Math.sqrt(n)==n) { finalAnswer.append("YES").append('\n'); count++; } else { n*=2; } } if(n%4==0 && count==0) { n/=4; if((int)Math.sqrt(n)*(int)Math.sqrt(n)==n) { finalAnswer.append("YES").append('\n'); count++; } } if(count==0){ finalAnswer.append("NO").append('\n'); } } System.out.println(finalAnswer); } ///////////////////////////////////////////////////////// public static long gcd(long a, long b) { while (b > 0) { long temp = b; b = a % b; // % is remainder a = temp; } return a; } public static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static boolean containsDigit(int number, int digit) { while (number > 0) { int curr_digit = number % 10; if (curr_digit == digit) return true; number /= 10; } return false; } static boolean isPalindrome(String s) { int n = s.length(); for (int i = 0; i < (n/2); ++i) { if (s.charAt(i) != s.charAt(n - i - 1)) { return false; } } return true; } void sieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) System.out.print(i + " "); } } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.*; public class C { static long x, k; static long mod = 1000000007; public static void main(String[] args) { JS in = new JS(); x = in.nextLong(); k = in.nextLong(); if(x==0) { System.out.println(0); return; } long c = pow(2,k); if(c==0) c = mod; long sub = c-1; long low = ((c*(x%mod))%mod - sub); while(low < 0) low += mod; long res = ((low*2)%mod + sub)%mod; System.out.println(res); } static long pow(long a, long p) { if(p==0) return 1; if(p==1) return a; if(p%2==0) { long res = pow(a,p/2)%mod; return (res*res)%mod; } else { return (pow(a,p-1)*a)%mod; } } static class JS{ 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 JS() { in = new BufferedInputStream(System.in, BS); } public JS(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; } } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.*; import java.io.*; public class givenstring { public static void main(String[] args){ Scanner reader = new Scanner(System.in); String in = reader.next(); int max = 0; for(int i = 0; i < in.length(); i++){ for(int j = i+1; j < in.length(); j++){ //take this substring String consider = in.substring(i, j); for(int k = i+1; k < in.length(); k++){ if(k + consider.length() > in.length()) break; else if(in.substring(k, k+consider.length()).equals(consider)) max = Math.max(max, consider.length()); } } } System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES