src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
public class D { public Object solve() { long N = sc.nextLong(), K = sc.nextLong() - 1; if (N >= 32) return print("YES", N-1); long A = 1L << (N-1), C = 4, T = (A*A - 1) / 3; while (A > 1 && K > T) { A /= 2; K -= (C-1); C *= 2; T += (C-3) * (A*A - 1) / 3; } if (K >= 0 && K <= T) return print("YES", Long.numberOfTrailingZeros(A)); else return print("NO"); } private static final boolean ONE_TEST_CASE = false; private static void init() { } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; } private static class IOUtils { public static class MyScanner { public String next() { newLine(); return line[index++]; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim(String delim, Object o, Object ... A) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : A) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static final java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start() { if (t == 0) t = millis(); } private static void append(java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append(final StringBuilder b, Object o, final String delim) { append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static Object print(Object o, Object ... A) { pw.println(build(o, A)); if (DEBUG) System.err.println(build(o, A)); return null; } private static void err(Object o, Object ... A) { System.err.println(build(o, A)); } private static boolean PRINT, DEBUG; private static void write(Object o) { err(o, '(', time(), ')'); if (PRINT) pw.println(o); } private static void exit() { IOUtils.pw.close(); System.out.flush(); err("------------------"); err(time()); System.exit(0); } private static long t; private static long millis() { return System.currentTimeMillis(); } private static String time() { return "Time: " + (millis() - t) / 1000.0; } private static void run(int N) { try { DEBUG = System.getProperties().containsKey("DEBUG"); PRINT = System.getProperties().containsKey("PRINT"); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new D().solve(); if (res != null) write("Case #" + n + ": " + build(res)); } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { init(); int N = ONE_TEST_CASE ? 1 : sc.nextInt(); IOUtils.run(N); } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class C35 { public static int mod = 1000000007; public static long INF = (1L << 60); static int n,m; static class Pair { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } static boolean[][] burned; static int[] dx={-1,0,1,0}; static int[] dy={0,-1,0,1}; static boolean isvalid(int x,int y) { return x>=0&&x<n&&y>=0&&y<m; } public static void main(String[] args) throws IOException { Scanner in = new Scanner("input.txt"); PrintWriter out = new PrintWriter(new FileWriter("output.txt")); n=in.nextInt(); m=in.nextInt(); burned=new boolean[n][m]; int k=in.nextInt(); Set<Pair> set=new HashSet<Pair>(); Pair prev=null; for(int i=0;i<k;i++) { int x=in.nextInt(); int y=in.nextInt(); burned[x-1][y-1]=true; set.add(prev=new Pair(x-1, y-1)); } while(!set.isEmpty()) { Set<Pair> tempset=new HashSet<>(); for(Pair p : set) { int x=p.x; int y=p.y; prev=p; for(int i=0;i<4;i++) { if(isvalid(x+dx[i], y+dy[i])&&!burned[x+dx[i]][y+dy[i]]) { tempset.add(new Pair(x+dx[i], y+dy[i])); burned[x+dx[i]][y+dy[i]]=true; } } } set=tempset; } out.printf("%d %d\n",(prev.x+1),(prev.y+1)); out.close(); } public static long pow(long x, long n) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p)) { if ((n & 1) != 0) { res = (res * p); } } return res; } public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException{ br = new BufferedReader(new FileReader(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();} } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); TaskD.Pair[] p = new TaskD.Pair[n]; for (int i = 0; i < n; ++i) { p[i] = new TaskD.Pair(in.nextLong(), in.nextLong()); } Arrays.sort(p); int last = 0; int ans = 1; for (int i = 1; i < n; ++i) { if (p[i].x - p[i].w >= p[last].x + p[last].w) { last = i; ++ans; } } out.println(ans); } static class Pair implements Comparable<TaskD.Pair> { long x; long w; public Pair(long x, long w) { this.x = x; this.w = w; } public int compareTo(TaskD.Pair o) { return Long.compare(x + w, o.x + o.w); } public String toString() { return x + " " + w; } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
nlogn
528_B. Clique Problem
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import java.text.*; public class Main { static PrintWriter out; static Reader in; public static void main(String[] args) throws IOException { input_output(); Main solver = new Main(); solver.solve(); out.close(); out.flush(); } static long INF = (long)1e18; static int MAXN = (int)1e7+5; static int mod = 998_244_353; static int n, m, q, t; static double pi = Math.PI; void solve() throws IOException{ t = in.nextInt(); int[] div = new int[MAXN]; Arrays.fill(div, 1); for (int i = 2; i < MAXN; i++) { if (div[i] == 1) { for (int j = i; j < MAXN; j+=i) { div[j] = i; } } } while (t --> 0) { n = in.nextInt(); int k = in.nextInt(); int[] arr = new int[n+1]; for (int i = 1; i <= n; i++) { arr[i] = in.nextInt(); int tmp = arr[i], newn = 1; while (div[arr[i]] != 1) { int elm = div[arr[i]], cnt = 0; while (div[arr[i]] == elm) { cnt++; arr[i] /= elm; } if (cnt%2 == 1) newn *= elm; } newn *= arr[i]; arr[i] = newn; } int[] close = new int[n+1]; List<Node> list = new ArrayList<>(); for (int i = 1; i <= n; i++) list.add(new Node(arr[i], i)); Collections.sort(list); for (int i = 0; i < n; i++) { if (i == n-1 || list.get(i+1).val != list.get(i).val) { close[list.get(i).idx] = -1; } else { close[list.get(i).idx] = list.get(i+1).idx; } } int[][] next = new int[n+1][k+1]; List<Integer> upd = new ArrayList<>(); List<Integer> nupd = new ArrayList<>(); for (int i = 0; i <= k; i++) next[n][i] = n; for (int i = n-1; i >= 1; i--) { nupd.clear(); if (close[i] == -1) { for (int j = 0; j <= k; j++) next[i][j] = next[i+1][j]; } else { int tmp = close[i]-1, cnt = 0; if (upd.size() == 0 || tmp < upd.get(0)) { nupd.add(tmp); tmp = -1; } for (int j = 0; j < upd.size(); j++) { if (nupd.size() < k+1 && tmp != -1 && tmp < upd.get(j)) { nupd.add(tmp); tmp = -1; } if (nupd.size() < k+1) nupd.add(upd.get(j)); } if (tmp != -1 && nupd.size() < k+1) nupd.add(tmp); for (int j = 0; j < nupd.size(); j++) next[i][j] = nupd.get(j); for (int j = nupd.size(); j <= k; j++) next[i][j] = n; upd.clear(); for (int j = 0; j < nupd.size(); j++) upd.add(nupd.get(j)); } } int[][] dp = new int[n+1][k+1]; for (int i = 1; i <= n; i++) for (int j = 0; j <= k; j++) dp[i][j] = n; for (int i = 0; i < n; i++) { for (int cur = 0; cur <= k; cur++) { for (int ncur = cur; ncur <= k; ncur++) { dp[next[i+1][ncur-cur]][ncur] = Math.min(dp[next[i+1][ncur-cur]][ncur], dp[i][cur]+1); } } } int ans = n; for (int i = 0; i <= k; i++) ans = Math.min(ans, dp[n][i]); out.println(ans); } } //<> static class Node implements Comparable<Node> { int val, idx; Node (int val, int idx) { this.val = val; this.idx = idx; } public int compareTo(Node o) { if (this.val != o.val) return this.val - o.val; return this.idx - o.idx; } } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String 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(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static void input_output() throws IOException { File f = new File("in.txt"); if(f.exists() && !f.isDirectory()) { in = new Reader(new FileInputStream("in.txt")); } else in = new Reader(); f = new File("out.txt"); if(f.exists() && !f.isDirectory()) { out = new PrintWriter(new File("out.txt")); } else out = new PrintWriter(System.out); } }
cubic
1497E2
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class A { public static void main(String[] args) { long fib[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073L, 4807526976L, 7778742049L, 12586269025L, 20365011074L, 32951280099L, 53316291173L, 86267571272L, 139583862445L, 225851433717L, 365435296162L, 591286729879L, 956722026041L, 1548008755920L, 2504730781961L, 4052739537881L, 6557470319842L, 10610209857723L }; int i = Arrays.binarySearch(fib, new Scanner(System.in).nextLong()); if (i < 4) if (i == 3) System.out.println("0 1 1"); else if (fib[i] == 1) System.out.println("0 0 1"); else System.out.println("0 0 0"); else System.out.println(fib[i - 4] + " " + fib[i - 3] + " " + fib[i - 1]); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/14/11 * Time: 9:53 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.FileReader; import java.util.StringTokenizer; import java.io.IOException; import java.util.Arrays; public class Fish extends Thread { public Fish() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } static int getOnes(int mask) { int result = 0; while (mask != 0) { mask &= mask - 1; ++result; } return result; } private void solve() throws Throwable { int n = nextInt(); double[][] a = new double[n][n]; double[] dp = new double[(1 << n)]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { a[i][j] = nextDouble(); } } int limit = (1 << n) - 1; //dp[mask] = probability of current subset (mask) to remain in the end dp[limit] = 1.0; for (int mask = limit; mask > 0; --mask) { int cardinality = getOnes(mask); int probability = cardinality * (cardinality - 1) / 2; for (int first = 0; first < n; ++first) { if ((mask & powers[first]) != 0) { for (int second = first + 1; second < n; ++second) { if ((mask & powers[second]) != 0) { dp[mask - powers[first]] += dp[mask] * a[second][first] / probability; dp[mask - powers[second]] += dp[mask] * a[first][second] / probability; } } } } } for (int i = 0; i < n; ++i) { output.printf("%.10f ", dp[powers[i]]); } } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new Fish().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } static int powers[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144}; private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
16_E. Fish
CODEFORCES
import java.awt.Point; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class Contest35_3 { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("input.txt")); String[] s = in.readLine().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); int k = Integer.parseInt(in.readLine()); s = in.readLine().split(" "); Point[] inp = new Point[k]; int p = 0; for (int i = 0; i < k; i++) { inp[i] = new Point(Integer.parseInt(s[p++]), Integer.parseInt(s[p++])); } int max = -1; int maxx = -1; int maxy = -1; int i; int j, dist; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { dist = 1000000; for (int l = 0; l < inp.length; l++) { dist = Math.min( Math.abs(inp[l].x - i) + Math.abs(inp[l].y - j), dist); } if (dist > max) { max = dist; maxx = i; maxy = j; } } } String res = maxx + " " + maxy + "\n"; FileWriter out = new FileWriter(new File("output.txt")); out.append(res); out.flush(); out.close(); } }
cubic
35_C. Fire Again
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Solution { private static int[] a; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); a = new int[101]; for (int i = 0; i < m; i++) { int type = sc.nextInt(); a[type] = a[type] + 1; } int lo=1, hi=100, max=0; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (check(n, mid)) { max = mid; lo = mid+1; } else { hi = mid -1; } } System.out.println(max); } public static boolean check(int n, int target) { int result = 0; for (int i=0; i <a.length; i++) { result = result + (a[i] / target); } if (result >= n) {return true;} return false; } }
nlogn
1011_B. Planning The Expedition
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; import java.util.TreeSet; public class TheyAreEverywhere { static StringTokenizer st; static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in), 325678); static int[] id = new int[100000]; public static void main(String[] args) throws IOException { int n = in(); String s = next(); int total = 0; int[] seq = new int[n]; boolean[] c = new boolean[100000]; for (int i = 0; i < n; i++) { seq[i] = s.charAt(i); if (!c[seq[i]]) { total++; c[seq[i]] = true; } } Arrays.fill(id, -1); int best = Integer.MAX_VALUE; TreeSet<Integer> q = new TreeSet<Integer>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return id[o1] - id[o2]; } }); for (int i = 0; i < n; i++) { q.remove(seq[i]); id[seq[i]] = i; q.add(seq[i]); if (q.size() == total) { //System.out.println("best: i=" + i + " id=" + id[q.first()]); best = Math.min(best, i - id[q.first()] + 1); } //System.out.println("i="+i+" " +q.toString()); } System.out.println(best); } public static int in() throws IOException { return Integer.parseInt(next()); } public static long inl() throws IOException { return Long.parseLong(next()); } public static String next() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.HashMap; import java.util.StringTokenizer; public class D { public static void main(String[] args){ FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(); long[] a = scan.nextLongArray(n); BigInteger res = BigInteger.ZERO; for (int i = n-1; i >= 0; i--) res = res.add(BigInteger.valueOf(i*a[i] - (n-1-i)*a[i])); HashMap<Long, Long> map = new HashMap<>(); for(int i = 0; i < n; i++) { res = res.subtract(BigInteger.valueOf(map.getOrDefault(a[i]-1, 0L))); res = res.add(BigInteger.valueOf(map.getOrDefault(a[i]+1, 0L))); map.put(a[i], map.getOrDefault(a[i], 0L)+1); } out.println(res); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n){ long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextDoubleArray(int n){ double[] a = new double[n]; for(int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char[][] nextGrid(int n, int m){ char[][] grid = new char[n][m]; for(int i = 0; i < n; i++) grid[i] = next().toCharArray(); return grid; } } }
nlogn
903_D. Almost Difference
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; public class Task235A { public static void main(String... args) throws NumberFormatException, IOException { Solution.main(System.in, System.out); } static class Scanner { private final BufferedReader br; private String[] cache; private int cacheIndex; Scanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); cache = new String[0]; cacheIndex = 0; } int nextInt() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return Integer.parseInt(cache[cacheIndex++]); } long nextLong() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return Long.parseLong(cache[cacheIndex++]); } String next() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return cache[cacheIndex++]; } void close() throws IOException { br.close(); } } static class Solution { public static void main(InputStream is, OutputStream os) throws NumberFormatException, IOException { PrintWriter pw = new PrintWriter(os); Scanner sc = new Scanner(is); long n = sc.nextInt(); if (n < 3) { pw.println(n); } else { if (n % 2 != 0) { pw.println(n * (n - 1) * (n - 2)); } else { if (n % 3 != 0) { pw.println(n * (n - 1) * (n - 3)); } else { long cand1 = n * (n - 1) * (n - 2) / 2; long cand2 = (n - 1) * (n - 2) * (n - 3); pw.println(Math.max(cand1, cand2)); } } } pw.flush(); sc.close(); } } }
constant
235_A. LCM Challenge
CODEFORCES
import java.util.*; import java.io.*; import static java.util.Arrays.*; import static java.lang.Math.*; import java.math.*; public class Main { void run() throws IOException { int n = in.nextInt(); char[] c = in.next().toCharArray(); int[][] t = new int[n][n]; int[][] h = new int[n][n]; int allt = 0, allh = 0; for (int i = 0; i < n; i++) { if (c[i] == 'T') { allt++; } else { allh++; } } for (int i = 0; i < n; i++) { if (c[i] == 'T') { t[i][i] = 1; h[i][i] = 0; } else { t[i][i] = 0; h[i][i] = 1; } for (int j = i + 1; j < n; j++) { if (c[j] == 'T') { t[i][j] = t[i][j - 1] + 1; h[i][j] = h[i][j - 1]; } else { h[i][j] = h[i][j - 1] + 1; t[i][j] = t[i][j - 1]; } } } for (int i = 1; i < n; i++) { t[i][i - 1] = allt; h[i][i - 1] = allh; for (int j = 0; j < i - 1; j++) { t[i][j] = allt - t[j + 1][i - 1]; h[i][j] = allh - h[j + 1][i - 1]; } } int r = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (h[i][j] == t[(j + 1) % n][(i - 1 + n) % n]) { r = min(r, h[i][j]); } if (t[i][j] == h[(j + 1) % n][(i - 1 + n) % n]) { r = min(r, t[i][j]); } } } out.println(r); /* for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { out.print(t[i][j] + " "); } out.println(); } out.println(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { out.print(h[i][j] + " "); } out.println(); }*/ } class pair implements Comparable <pair> { int x, y; pair(int x, int y) { this.x = x; this.y = y; } public int compareTo (pair p) { if (x != p.x) { return x - p.x; } else { return y - p.y; } } } static PrintWriter out; static Scanner in; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); //final String FILENAME = "jury"; in = new Scanner (new File (FILENAME + ".in")); out = new PrintWriter (new File(FILENAME + ".out")); in = new Scanner (System.in); out = new PrintWriter (System.out); new Main().run(); /*out = new PrintWriter (System.out); final int NUMBER_OF_TESTS = 35; for (int i = 1; i <= NUMBER_OF_TESTS; i++) { Scanner test = new Scanner (new File ("tests/" + i + ".in")); Scanner right = new Scanner (new File ("tests/" + i + ".out")); String get_right = right.nextLine(); String get_test = new Main().run(test); if (get_right.equals(get_test)) { out.println("Test #" + i + ": " + "OK!"); } else { out.println("Test #" + i + ": " + "ERROR!"); out.println("Expected: " + get_right); out.println("Received: " + get_test); break; } }*/ out.close(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; 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; } static{ in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); } public static void main(String[] args)throws Exception{ int n = nextInt(); out.println(n*3/2); out.flush(); } }
constant
84_A. Toy Army
CODEFORCES
import java.util.Scanner; public class Flatwile { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt(); int[] c = new int[n]; int[] a = new int[n]; for (int i=0; i<n; i++){ c[i] = sc.nextInt(); a[i] = sc.nextInt(); } sort(c, a); int res = 1; double prev = Integer.MIN_VALUE; for(int i=0; i<c.length; i++){ if (c[i]-a[i]/2d - prev >=t){ res++; } if (i!=c.length-1 && c[i+1]-a[i+1]/2d-(c[i]+a[i]/2d)>t ){ res++; } prev = c[i] +a[i]/2d; } System.out.println(res); } private static void sort(int[] a, int[] b){ for(int i=0; i<a.length; i++){ for(int j=i+1; j<a.length; j++){ if (a[i]>a[j]){ swap(a, i, j); swap(b, i, j); } } } } private static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nova */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { class Team implements Comparable<Team> { int solved = 0; int penalty = 0; Team(int solved, int penalty) { this.solved = solved; this.penalty = penalty; } public int compareTo(Team o) { return this.solved == o.solved ? this.penalty - o.penalty : -(this.solved - o.solved); } public boolean equals(Object obj) { if (obj instanceof Team) { Team o = (Team) obj; return ((this.solved == o.solved) && (this.penalty == o.penalty)); } return false; } } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int k = in.nextInt(); Team[] teams = new Team[n]; for (int i = 0; i < n; i++) teams[i] = new Team(in.nextInt(), in.nextInt()); Arrays.sort(teams); int[] top = new int[n]; int[] map = new int[n]; int cur = -1; for (int i = 0; i < n; i++) { if (i == 0 || !teams[i].equals(teams[i - 1])) cur = i; top[cur]++; map[i] = cur; } out.println(top[map[k - 1]]); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
nlogn
166_A. Rank List
CODEFORCES
import java.util.Scanner; public class SimpleTask { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); boolean[][] graph = new boolean[n][n]; for (int i = 0; i < m; i++) { int u = scan.nextInt() - 1; int v = scan.nextInt() - 1; graph[u][v] = true; graph[v][u] = true; } long[][] dp = new long[1 << n][n]; long sum = 0; for (int i = 0; i < n; i++) dp[1 << i][i] = 1; for (int mask = 1; mask < (1 << n); mask++) { int first = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) == 0 || first == i) continue; for (int j = 0; j < n; j++) { if (graph[i][j] && (mask & (1 << j)) != 0) dp[mask][i] += dp[mask ^ 1 << i][j]; } if (Integer.bitCount(mask) >= 3 && graph[i][first]) sum += dp[mask][i]; } } System.out.println(sum / 2); scan.close(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class CFTest6 { static BufferedReader br; public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); try { int[] a1 = readIntArr(); int[] a2 = readIntArr(); br.close(); int f = a1[0]; int d = a1[1]; int s = a1[2]; Arrays.sort(a2); if (d <= s) System.out.println(0); else { int cur = d - s + 1; int num=0; for(int i=0;i<f;i++){ num++; cur-=a2[f-i-1]; if(cur<=0)break; cur++; } if (cur > 0) System.out.println(-1); else{ System.out.println(num); } } } catch (IOException e) { e.printStackTrace(); } } static public String readLine() throws IOException { return br.readLine(); } static public String readString() throws IOException { return br.readLine(); } static public long readlong() throws IOException { return Long.parseLong(br.readLine()); } static public int readInt() throws IOException { return Integer.parseInt(br.readLine()); } static public int[] readIntArr() throws IOException { String[] str = br.readLine().split(" "); int arr[] = new int[str.length]; for (int i = 0; i < arr.length; i++) arr[i] = Integer.parseInt(str[i]); return arr; } static public double[] readDoubleArr() throws IOException { String[] str = br.readLine().split(" "); double arr[] = new double[str.length]; for (int i = 0; i < arr.length; i++) arr[i] = Double.parseDouble(str[i]); return arr; } static public long[] readLongArr() throws IOException { String[] str = br.readLine().split(" "); long arr[] = new long[str.length]; for (int i = 0; i < arr.length; i++) arr[i] = Long.parseLong(str[i]); return arr; } static public double readDouble() throws IOException { return Double.parseDouble(br.readLine()); } }
nlogn
257_A. Sockets
CODEFORCES
import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Random; import java.util.TreeSet; /** * Actual solution is at the top, in class Solver */ public class Main implements Runnable { private static String[] args; public static void main(String[] args) { Main.args = args; new Thread(null, new Main(), "MyRunThread", 1 << 26).start(); } @Override public void run() { long time_beg = -1; InputStream inputStream = System.in; OutputStream outputStream = System.out; if (args.length > 0 && args[0].equals("outside")) { time_beg = System.currentTimeMillis(); try { inputStream = new FileInputStream("IO/in.txt"); // outputStream = new FileOutputStream("IO/out.txt"); } catch (Exception e) { System.err.println(e); System.exit(1); } } else { try { // inputStream = new FileInputStream("file_name"); // outputStream = new FileOutputStream("file_name"); } catch (Exception e) { System.err.println(e); System.exit(1); } } Solver s = new Solver(); s.in = new InputReader(inputStream); s.out = new OutputWriter(outputStream); if (args.length > 0 && args[0].equals("outside")) { s.debug = new DebugWriter(s.out); } s.solve(); s.out.close(); if (args.length > 0 && args[0].equals("outside")) { s.debug.close(); System.err.printf("*** Total time: %.3f ***\n", (System.currentTimeMillis() - time_beg) / 1000.0); } } } final class Solver { InputReader in; OutputWriter out; DebugWriter debug; public void solve() { int n = in.readInt(); int[] mas = new int[n]; int[] sorted = new int[n]; for (int i = 0; i < n; ++i) sorted[i] = mas[i] = in.readInt(); Random rnd = new Random(System.nanoTime()); for (int i = 1; i < n; ++i) { int j = rnd.nextInt(i); int tmp = sorted[j]; sorted[j] = sorted[i]; sorted[i] = tmp; } Arrays.sort(sorted); int id1 = -1; for (int i = 0; i < n; ++i) if (mas[i] != sorted[i]) { id1 = i; break; } int id2 = -1; for (int i = n - 1; i >= 0; --i) if (mas[i] != sorted[i]) { id2 = i; break; } if (id1 != -1 && id2 != -1 && id1 != id2) { int tmp = mas[id1]; mas[id1] = mas[id2]; mas[id2] = tmp; } for (int i = 0; i < n; ++i) if (mas[i] != sorted[i]) { out.printLine("NO"); return; } out.printLine("YES"); } } class InputReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } 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 peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void printFormat(String format, Object... objects) { writer.printf(format, objects); } public void print(char[] objects) { writer.print(objects); } public void printLine(char[] objects) { writer.println(objects); } public void printLine(char[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void print(int[] objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(int[] objects) { print(objects); writer.println(); } public void printLine(int[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void print(long[] objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(long[] objects) { print(objects); writer.println(); } public void printLine(long[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void print(double[] objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(double[] objects) { print(objects); writer.println(); } public void printLine(double[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void print(byte[] objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(byte[] objects) { print(objects); writer.println(); } public void printLine(byte[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void print(boolean[] objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(boolean[] objects) { print(objects); writer.println(); } public void printLine(boolean[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class DebugWriter { private final OutputWriter writer; public DebugWriter(OutputWriter writer) { this.writer = writer; } private void printDebugMessage() { writer.print("debug:\t"); } public void printLine(Object... objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printFormat(String format, Object... objects) { flush(); printDebugMessage(); writer.printFormat(format, objects); flush(); } public void printLine(char[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(char[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void printLine(double[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(double[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void printLine(int[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(int[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void printLine(long[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(long[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void printLine(byte[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(byte[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void printLine(boolean[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(boolean[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void flush() { writer.flush(); } public void close() { writer.close(); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class A { static class Entity implements Comparable { public Entity(int x, int a) { this.x = x; this.a = a; } public int x, a; public int compareTo(Object t) { Entity o = (Entity) t; return x == o.x ? 0 : x < o.x ? -1 : 1; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(), t = 2 * scanner.nextInt(); if (1 == n) { System.out.println(2); } else { int rez = 2; ArrayList<Entity> list = new ArrayList<Entity>(); for (int i = 0; i < n; i++) { list.add(new Entity(scanner.nextInt(), scanner.nextInt())); } Collections.sort(list); for (int i = 1; i < n; i++) { int num = 2 * (list.get(i).x - list.get(i - 1).x) - list.get(i).a - list.get(i - 1).a; if (t < num) { rez += 2; } else if (t == num) { rez++; } } System.out.println(rez); } } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { static int N; static char[] a; static int[][] memo; static int[] ind; static final int MOD = (int) 1e9 + 7; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); a = new char[N]; for(int i = 0; i < N; i++) a[i] = sc.nextChar(); if(N == 1){out.println(1); out.flush(); return;} memo = new int[N][N + 5]; for(int[] a : memo) Arrays.fill(a, -1); out.println(dp(0, 1)); out.flush(); out.close(); } static int dp(int i, int ind) { if(i == N - 1) return a[i - 1] == 'f'? 1 : ind; if(i == 0) return dp(i + 1, a[i] == 's'? 1 : 2); if(memo[i][ind] != -1) return memo[i][ind]; int ans = 0; if(a[i - 1] == 'f') ans = dp(i + 1, a[i] == 's'? ind : ind + 1); else { if(ind > 1) ans = (ans + dp(i, ind -1)) % MOD; ans = (ans + dp(i + 1, a[i] == 's'? ind : ind + 1)) % MOD; } return memo[i][ind] = ans; } static class Scanner { StringTokenizer st; BufferedReader br; Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));} Scanner(String file) throws FileNotFoundException {br = new BufferedReader(new FileReader(file));} 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());} double nextDouble() throws IOException {return Double.parseDouble(next());} char nextChar()throws IOException{return next().charAt(0);} Long nextLong()throws IOException{return Long.parseLong(next());} boolean ready() throws IOException{return br.ready();} void waitForInput(){for(long i = 0; i < 3e9; i++);} } }
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.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { FastReader in; PrintWriter out; int n; public void solve(int testNumber, FastReader in, PrintWriter out) { this.in = in; this.out = out; n = in.nextInt(); if (n % 4 != 0) { out.println("! -1"); return; } int low = 0; int high = n >> 1; if (BValue(low) == 0) { out.println("! " + (low + 1)); return; } boolean value = BValue(low) > 0; while (high - low > 1) { int mid = (high + low) >> 1; int BVal = BValue(mid); if (BVal == 0) { out.println("! " + (mid + 1)); return; } if (value) { if (BVal < 0) { high = mid; } else { low = mid; } } else { if (BVal > 0) { high = mid; } else { low = mid; } } } out.println("! -1"); } public int BValue(int index) { out.println("? " + (index + 1)); out.flush(); int f = in.nextInt(); out.println("? " + (index + 1 + (n >> 1))); out.flush(); int s = in.nextInt(); return f - s; } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
logn
1019_B. The hat
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); long n = Long.parseLong(st.nextToken()), s = Long.parseLong(st.nextToken()); long m = s; while (m-f(m)<s && m<=n) m++; System.out.println(Math.max(n-m+1, 0)); } public static int f(long n) { int sum = 0; for (long i=0, j=1L ; i<(int)Math.log10(n)+1 ; i++, j*=10) { sum += (n/j)%10; } return sum; } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.util.*; import java.io.*; public class E { public static void main(String[] args) throws IOException {new E();} FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n, m, oo = 1 << 28; int[] dp, cost; int[][] to; char[] w; E() throws IOException { n = in.nextInt(); m = in.nextInt(); w = in.next().toCharArray(); to = new int[m+1][m+1]; for (int i = 0; i < n-1; i++) if (w[i] != w[i+1]) { to[w[i]-'a'][w[i+1]-'a']++; to[w[i+1]-'a'][w[i]-'a']++; } cost = new int[1 << m]; for (int i = 0; i < (1 << m); i++) for (int j = 0; j < m; j++) { if (((1 << j) & i) > 0) continue; for (int k = 0; k < m; k++) { if (((1 << k) & i) == 0) continue; cost[i] += to[j][k]; } } dp = new int[1 << m]; Arrays.fill(dp, oo); dp[0] = 0; for (int i = 1; i < (1 << m); i++) { for (int j = 0; j < m; j++) if (((i >> j) & 1) > 0) dp[i] = Math.min(dp[i], dp[i ^ (1 << j)]); dp[i] += cost[i]; } out.println(dp[(1 << m)-1]); out.close(); } void sort(int[] x) { int sz = x.length; Random r = new Random(); for (int i = 0; i < sz; i++) { int j = r.nextInt(sz); x[i] = x[j]-(x[i]-(x[j] = x[i])); } Arrays.sort(x); } 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 int[] intarr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Main{ public static boolean check(BigInteger a, BigInteger b){ long n = 0; String aStr = a.toString(); for (int i=0; i < aStr.length() ;i++ ) { n += Long.valueOf(aStr.charAt(i)-'0'); } return a.subtract(BigInteger.valueOf(n)).compareTo(b) >= 0; } public static void main(String[] args) { try(BufferedReader in = new BufferedReader(new InputStreamReader(System.in))){ String[] str = in.readLine().split(" "); BigInteger n = new BigInteger(str[0]); BigInteger s = new BigInteger(str[1]); BigInteger left = BigInteger.ONE; BigInteger right = new BigInteger(n.toString()).add(BigInteger.TEN); BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE); BigInteger t; while(right.subtract(left).compareTo(BigInteger.ONE)>0){ t = left.add(right.subtract(left).divide(TWO)); if(check(t, s)){ right = t; }else{ left = t; } } BigInteger result = n.subtract(right).add(BigInteger.ONE); if (result.compareTo(BigInteger.ZERO)<=0) { System.out.println(0); }else{ System.out.println(result); } }catch (IOException e) { e.printStackTrace(); } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.util.*; public class q1 { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int[] arr1=new int[9]; int[] arr2=new int[9]; String ss; s.nextLine(); for(int i=0;i<n;i++) { ss=s.nextLine(); if(ss.equals("M")) arr1[0]++; else if(ss.equals("S")) arr1[1]++; else if(ss.equals("L")) arr1[2]++; else if(ss.equals("XS")) arr1[3]++; else if(ss.equals("XL")) arr1[4]++; else if(ss.equals("XXS")) arr1[5]++; else if(ss.equals("XXL")) arr1[6]++; else if(ss.equals("XXXS")) arr1[7]++; else if(ss.equals("XXXL")) arr1[8]++; } for(int i=0;i<n;i++) { ss=s.nextLine(); if(ss.equals("M")) arr2[0]++; else if(ss.equals("S")) arr2[1]++; else if(ss.equals("L")) arr2[2]++; else if(ss.equals("XS")) arr2[3]++; else if(ss.equals("XL")) arr2[4]++; else if(ss.equals("XXS")) arr2[5]++; else if(ss.equals("XXL")) arr2[6]++; else if(ss.equals("XXXS")) arr2[7]++; else if(ss.equals("XXXL")) arr2[8]++; } int min; for(int i=0;i<9;i++) { if(arr1[i]<arr2[i]) min=arr1[i]; else min=arr2[i]; arr1[i]-=min; arr2[i]-=min; } int sum=0; for(int i=0;i<9;i++) { sum+=arr1[i]; } System.out.println(sum); //System.out.println(Arrays.toString(arr2)); } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; import java.util.StringTokenizer; public class D { public static class BIT { int[] dat; public BIT(int n){ dat = new int[n + 1]; } public void add(int k, int a){ // k : 0-indexed for(int i = k + 1; i < dat.length; i += i & -i){ dat[i] += a; } } public int sum(int s, int t){ // [s, t) if(s > 0) return sum(0, t) - sum(0, s); int ret = 0; for(int i = t; i > 0; i -= i & -i) { ret += dat[i]; } return ret; } } public static void main(String[] args) { try (final Scanner sc = new Scanner(System.in)) { final int N = sc.nextInt(); int[] array = new int[N]; for(int i = 0; i < N; i++){ array[i] = sc.nextInt() - 1; } long inv = 0; BIT bit = new BIT(N); for(int i = 0; i < N; i++){ inv += bit.sum(array[i], N); bit.add(array[i], 1); } //System.out.println(inv); int mod2 = (int)(inv % 2); final int M = sc.nextInt(); for(int i = 0; i < M; i++){ final int l = sc.nextInt() - 1; final int r = sc.nextInt() - 1; final long size = (r - l) + 1; if(size > 1){ //System.out.println(size + " " + ((size * (size - 1) / 2))); if((size * (size - 1) / 2) % 2 == 1){ mod2 = 1 - mod2; } } System.out.println((mod2 == 0) ? "even" : "odd"); } } } public static class Scanner implements Closeable { private BufferedReader br; private StringTokenizer tok; public Scanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } private void getLine() { try { while (!hasNext()) { tok = new StringTokenizer(br.readLine()); } } catch (IOException e) { /* ignore */ } } private boolean hasNext() { return tok != null && tok.hasMoreTokens(); } public String next() { getLine(); return tok.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public void close() { try { br.close(); } catch (IOException e) { /* ignore */ } } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Main { public static InputStream IN; public static OutputStream OUT; public static PrintWriter out; public static BufferedReader in; public static StringTokenizer st = null; public static int ni() throws Exception { for (;st == null || !st.hasMoreTokens();){ st = new StringTokenizer(in.readLine()); } return Integer.parseInt(st.nextToken()); } public static void main(String[] args) throws Exception { IN = new FileInputStream("input.txt"); OUT = new FileOutputStream("output.txt"); out = new PrintWriter(OUT); in = new BufferedReader(new InputStreamReader(IN)); int n = ni(); int m = ni(); int k = ni(); int[] x = new int[k]; int[] y = new int[k]; for (int i = 0 ; i < k; i++){ x[i] = ni() - 1; y[i] = ni() - 1; } int w = Integer.MIN_VALUE; int aa = -1; int ab = -1; for (int i = 0 ; i < n ; i++){ for (int j = 0; j < m; j++){ int min = Integer.MAX_VALUE; for (int q = 0; q < k; q++){ int cur = Math.abs(i - x[q]) + Math.abs(j - y[q]); min = Math.min(cur, min); } if (min > w){ w = min; aa = i; ab = j; } } } out.println((aa + 1) + " " + (ab + 1)); out.flush(); } }
cubic
35_C. Fire Again
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]); dp[i][cn+me]+=(((dp[j][cn]*binom[cn+me][cn])%mod)*pow2[me-1])%mod; dp[i][cn+me]%=mod; } } } long ans=0; for (int i=0;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.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; public class CodeForces { public static void main(String[] args) { Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in))); System.out.println(input.nextInt() / 2 + 1); } }
constant
964_A. Splits
CODEFORCES
import java.util.*; public class ehab4 { public static void main( String[] args ) { Scanner in = new Scanner( System.in ); int a = 0, b = 0; System.out.println( "? 0 0 " ); System.out.flush(); int c = in.nextInt(); for ( int i = 29; i >= 0; i-- ) { System.out.println( "? " + ( a + ( 1 << i ) ) + " " + b ); System.out.flush(); int q1 = in.nextInt(); System.out.println( "? " + a + " " + ( b + ( 1 << i ) ) ); System.out.flush(); int q2 = in.nextInt(); if ( q1 == q2 ) { if ( c == 1 ) a += ( 1 << i ); else if ( c == -1 ) b += ( 1 << i ); c = q1; } else if ( q1 == -1 ) { a += ( 1 << i ); b += ( 1 << i ); } else if ( q1 == -2 ) return; } System.out.println( "! " + a + " " + b ); System.out.flush(); } }
logn
1088_D. Ehab and another another xor problem
CODEFORCES
//package codeforces; import java.util.Scanner; public class ex5 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String S [] = new String[3]; int m=0,s=0,p=0; int temp=0; for (int i = 0; i < S.length; i++) { S[i]=scan.next(); if(S[i].indexOf('m')!=-1) m++; if(S[i].indexOf('s')!=-1) s++; if(S[i].indexOf('p')!=-1) p++; } int n1 = Integer.parseInt(S[0].substring(0,1)); int n2 = Integer.parseInt(S[1].substring(0,1)); int n3 = Integer.parseInt(S[2].substring(0,1)); int d3 = Math.abs(n1-n2); int d4 = Math.abs(n1-n3); int d5 = Math.abs(n2-n3); if(m==3||s==3||p==3) { if(d3==1&d5==1&d4==2||d3==1&d4==1&d5==2||d5==1&d4==1&d3==2) System.out.println(0); else if(d3==0&d4==0) System.out.println(0); else if(d3<d5&d3<d4) { if(d3==1||d3==2||d3==0) System.out.println(1); else System.out.println(2); } else if (d5<d4&d5<d3){ if(d5==1||d5==2||d5==0) System.out.println(1); else System.out.println(2); } else if(d4<d5&d4<d3) { if(d4==1||d4==2||d4==0) System.out.println(1); else System.out.println(2); } else if(d3==2&d5==2||d4==2&d5==2||d3==2&d4==2||d3==1&d5==1||d4==1&d5==1||d3==2&d4==1) System.out.println(1); else System.out.println(2); } if(m==2||s==2||p==2) { char c1 = S[0].charAt(1); char c2 = S[1].charAt(1); char c3 = S[2].charAt(1); if(c1==c2) { if(n1==n2) System.out.println(1); else if(d3==1||d3==2) System.out.println(1); else System.out.println(2); } if(c1==c3) { if(n1==n3) System.out.println(1); else if(d4==1||d4==2) System.out.println(1); else System.out.println(2); } if(c2==c3) { if(n2==n3) System.out.println(1); else if(d5==1||d5==2) System.out.println(1); else System.out.println(2); } } if(m==1&s==1&p==1) System.out.println(2); } }
constant
1191_B. Tokitsukaze and Mahjong
CODEFORCES
import java.util.*; import java.io.*; public class SolutionC{ public static void main(String[] args) throws Exception{ Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=sc.nextInt(); int[] arr=new int[10000002]; for(int i=0;i<arr.length;i++){ arr[i]=i; } for(int i=2;i*i<arr.length;i++){ int b=i*i; for(int j=b;j<arr.length;j+=b){ arr[j]=j/b; } } int[] pp = new int[10000001]; Arrays.fill(pp, -1); while(t-->0){ int n=sc.nextInt(); int k=sc.nextInt(); int[] aa=new int[n]; for(int i=0;i<n;i++){ int a=sc.nextInt(); aa[i]=arr[a]; } int[] mp = new int[k + 1]; int[] ip = new int[k + 1]; for (int i = 0; i < n; i++) { int a = aa[i]; for (int h = k; h >= 0; h--) { if (pp[a] >= ip[h]) { mp[h]++; ip[h] = i; } if (h > 0 && (mp[h - 1] < mp[h] || mp[h - 1] == mp[h] && ip[h - 1] > ip[h])) { mp[h] = mp[h - 1]; ip[h] = ip[h - 1]; } } pp[a] = i; } out.println(mp[k]+1); for (int i = 0; i < n; i++) { pp[aa[i]] = -1; } } out.close(); } }
cubic
1497E2
CODEFORCES
import java.lang.*; import java.io.*; import java.util.*; import java.math.*; public class Solution implements Runnable{ private static BufferedReader br = null; private static PrintWriter out = null; private static StringTokenizer stk = null; public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); (new Thread(new Solution())).start(); } private void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } private String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } private Integer nextInt() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Integer.parseInt(stk.nextToken()); } private Long nextLong() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Long.parseLong(stk.nextToken()); } private String nextWord() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return (stk.nextToken()); } private Double nextDouble() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Double.parseDouble(stk.nextToken()); } public void run() { int n = nextInt(); int t = nextInt(); double[] d = new double[2*n]; for (int i = 0; i < n; ++i) { double x = nextDouble(); double a = nextDouble(); d[2*i] = x-a/2; d[2*i+1] = x+a/2; } Arrays.sort(d); int res = 2; for (int i = 1; i < 2*n-1; i+=2) { if (d[i+1] - d[i] >= t) { ++res; } if (d[i+1] - d[i] > t) { ++res; } } out.println(res); out.flush(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class Solver { StringTokenizer st; BufferedReader in; PrintWriter out; public long result = 0; public int k = 0; public static void main(String[] args) throws NumberFormatException, IOException { Solver solver = new Solver(); solver.open(); solver.solve(); solver.close(); } public void open() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } public String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } public void solve() throws NumberFormatException, IOException { int n = nextInt(); int a = nextInt(); int b = nextInt(); int[] ar = new int[n]; for(int i=0;i<n;i++){ ar[i] = nextInt(); } Arrays.sort(ar); out.println(ar[b]-ar[b-1]); } public void close() { out.flush(); out.close(); } }
nlogn
169_A. Chores
CODEFORCES
//package arbuz; import java.util.Scanner; public class Arbuz { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if (n % 4 == 0 || n % 7 == 0 || n % 47 == 0 || n % 74 == 0 || n % 444 == 0 || n % 447 == 0 || n % 474 == 0 || n % 477 == 0) { System.out.println("YES"); } else { System.out.println("NO"); } } }
constant
122_A. Lucky Division
CODEFORCES
//2021 global14 // jzzhao import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int tc = sc.ni(); for (int rep = 0; rep < tc; rep++) { pw.println(solve(sc,pw)); //solve(sc,pw); } pw.close(); } /* FS Methods: - next(): next element in string - nextLine(): nextline in string - ni(): next Integer - nd(): next Double - nl(): next Long - intArray(n): - longArray(n): - to2di(m,n): - to2dl(m,n): */ public static String solve(FastScanner sc, PrintWriter pw) { int n = sc.ni(); long cur1 = 2; long cur2 = 4; long block = 2; long block2 = 4; int tmp = 3; while(cur1<=n||cur2<=n){ if(cur1==n||cur2==n){ return "YES"; } if(cur1<n){ cur1+=block*tmp; } if(cur2<n){ cur2+=block2*tmp; } tmp+=2; } return "NO"; //return "NO"; } /* - The following are helping method so pls do not do anything to them. */ // public static int[][] to2d(Scanner scanner, int m, int n){ // int[][] ans = new int[m][n]; // for(int i = 0;i<m;i++){ // String[] r = scanner.nextLine().split("[ ]"); // for(int j = 0;j<n;j++){ // ans[i][j] = stoi(r[j]); // } // } // return ans; // } // public static int[] toArray(Scanner scanner, int m){ // int[] ans = new int[m]; // String[] r = scanner.nextLine().split("[ ]"); // for(int i = 0;i<m;i++){ // ans[i] = stoi(r[i]); // } // return ans; // } public static void printArr(PrintWriter pw,int[] a){ for(int i = 0;i<a.length;i++){ pw.print(a[i]); if(i!=a.length-1){ pw.print(" "); } } pw.println(); } public static void print2d(PrintWriter pw,int[][] a){ for(int j=0;j<a.length;j++){ for(int i = 0;i<a[j].length;i++){ pw.print(a[j][i]); if(i!=a[j].length-1){ pw.print(" "); } } pw.println(" "); } pw.println(); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static int stoi(String s){ return Integer.parseInt(s); } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[] intArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = ni(); return ret; } int[][] to2di(int m, int n){ int[][] ans = new int[m][n]; for(int i = 0;i<m;i++){ String[] r = nextLine().split("[ ]"); for(int j = 0;j<n;j++){ ans[i][j] = Integer.parseInt(r[j]); } } return ans; } long[][] to2dl(int m, int n){ long[][] ans = new long[m][n]; for(int i = 0;i<m;i++){ String[] r = nextLine().split("[ ]"); for(int j = 0;j<n;j++){ ans[i][j] = Long.parseLong(r[j]); } } return ans; } long nl() { return Long.parseLong(next()); } long[] longArray(int N) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = nl(); return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * Date 22.11.2011 * Time 17:49:45 * Author Woodey * $ */ public class A15 { final double eps = 10e-9; class Pair implements Comparable<Pair>{ int x; int length; Pair(int x, int length) { this.x = x; this.length = length; } public int compareTo(Pair p) { return x - p.x; } } private void Solution() throws IOException { int n = nextInt(), t = nextInt(), ans = 2; Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i ++) { int x = nextInt(), length = nextInt(); pairs[i] = new Pair(x, length); } Arrays.sort(pairs); for (int i = 0; i < n-1; i ++) { double place = pairs[i+1].x - pairs[i].x - (double) pairs[i+1].length/2 - (double) pairs[i].length/2; if (place > t) ans += 2; else if ((int) (place+eps) == t) ans ++; } System.out.println(ans); } public static void main(String[] args) { new A15().run(); } BufferedReader in; StringTokenizer tokenizer; public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; Solution(); in.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(in.readLine()); return tokenizer.nextToken(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class C_138B { private static BufferedReader in; private static StringTokenizer st; private static PrintWriter out; static String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } public static void main(String[] args) throws NumberFormatException, IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); out = new PrintWriter(new OutputStreamWriter(System.out)); int n = nextInt(); int k = nextInt(); int [] a = new int [n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < a.length; i++) { set.add(a[i]); if(set.size()==k){ Set<Integer> set2 = new HashSet<Integer>(); for (int j = i; j >= 0; j--) { set2.add(a[j]); if(set2.size()==k){ out.print((j+1)+" "+(i+1)); out.close(); return; } } } } out.print("-1 -1"); out.close(); } }
linear
224_B. Array
CODEFORCES
import java.util.*; public class Main { public static void main(String[]args) { Scanner input=new Scanner (System.in); while(input.hasNext()) { long n=input.nextLong(); if(n==1||n==2) System.out.println(n); else if(n%2==1) System.out.println(n*(n-1)*(n-2)); else if(n%3!=0) System.out.println(Math.max(n*(n-1)*(n-3),n*(n-1)*(n-2)/2)); else System.out.println(Math.max( Math.max(n*(n-1)*(n-3)/3,n*(n-1)*(n-2)/2) , Math.max((n-2)*(n-1)*(n-3),n*(n-2)*(n-3)/6) )); } } }
constant
235_A. LCM Challenge
CODEFORCES
import java.util.*; public class A { int n; int[] arr; void run(){ Scanner s = new Scanner(System.in); n = s.nextInt(); arr = new int[n]; int even, odd; even = 0; odd = 0; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); if(arr[i]%2==0)even++; else odd++; } if(even>odd){ for (int i = 0; i < n; i++) { if(arr[i]%2==1){ System.out.println(i+1); System.exit(0); } } } else{ for (int i = 0; i < n; i++) { if(arr[i]%2==0){ System.out.println(i+1); System.exit(0); } } } } public static void main(String[] args) { new A().run(); } }
linear
25_A. IQ test
CODEFORCES
import java.io.*; import java.util.*; public class Main { static class FastScanner { private BufferedReader bufferedReader; private StringTokenizer stringTokenizer; public FastScanner(InputStream inputStream) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException ignored) { } } return stringTokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static class Node implements Comparable { Node left; Node right; private int value; Node(Node left, Node right, int value) { this.left = left; this.right = right; this.value = value; } @Override public int compareTo(Object o) { return Integer.compare(this.value, ((Node) o).value); } } private static int fib(int n, int m) { if (n < 2) return n; int a = 0; int b = 1; for (int i = 0; i < n - 2; i++) { int c = (a + b) % m; a = b; b = c; } return (a + b) % m; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a, long b) { return Math.abs(a * b) / gcd(a, b); } static class DSU { private int[] p; private int[] r; DSU(int n) { p = new int[n]; r = new int[n]; Arrays.fill(p, -1); Arrays.fill(r, 0); } int find(int x) { if (p[x] < 0) { return x; } return p[x] = find(p[x]); } void union(int a, int b) { a = find(a); b = find(b); if (a == b) return; if (r[a] < r[b]) { p[a] = b; } else { p[b] = a; } if (r[a] == r[b]) { r[a]++; } } } private static boolean isPrime(long n) { for (int i = 2; i < n; i++) { if (n % i == 0) return false; } return true; } private static double med(Integer[] a) { Arrays.sort(a); if (a.length % 2 == 0) { int r = a.length / 2; int l = r - 1; double s = a[l] + a[r]; return s / 2.0; } int m = a.length / 2; return a[m]; } static Map<Integer, ArrayList<Integer>> g; static Map<Integer, Integer> color; static void dfs(int v, int c) { color.put(v, c); for (int i = 0; i < g.get(v).size(); i++) { int u = g.get(v).get(i); if (!color.containsKey(u)) { dfs(u, c); } } } static void reverse(Integer[] a) { Collections.reverse(Arrays.asList(a)); } static boolean next(Integer[] a) { int i = a.length - 1; while (a[i] == 0) i--; int c = 0; while (i >= 0 && a[i] == 1) { c++; i--; } if (i < 0) return false; a[i] = 1; for (int j = i + 1; j < a.length; j++) { a[j] = 0; } c--; for (int j = 0; j < c; j++) { a[a.length - 1 - j] = 1; } return true; } private static int bin(Integer[] a, int l, int r, int x) { if (l >= r) return l; int m = (l + r) / 2; if (a[m] > x) { return bin(a, l, m, x); } else if (a[m] < x || (m < a.length - 1 && a[m + 1] == x)) { return bin(a, m + 1, r, x); } return m + 1; } private static class SegmentTree { private long[] d; private long[] a; SegmentTree(int n) { a = new long[n]; d = new long[5 * n]; } void update(int v, int l, int r, int pos, long val) { if (l == r) { d[v] += val; a[l] += val; } else { int mid = (l + r) / 2; if (pos <= mid) { update(v * 2, l, mid, pos, val); } else { update(v * 2 + 1, mid + 1, r, pos, val); } d[v] = d[v * 2] + d[v * 2 + 1]; } } int find(int v, int l, int r, long w) { if (v >= d.length) return -1; int mid = (l + r) / 2; if (d[v] <= w) return r; long o = w - d[v * 2]; if (mid + 1 < a.length && o >= a[mid + 1]) { return find(v * 2 + 1, mid + 1, r, o); } if (w >= a[l]) return find(v * 2, l, mid, w); return -1; } int iterFind(long w) { if (a[0] > w) return -1; int l = 0, r = a.length - 1; int v = 1; while (d[v] > w) { int mid = (l + r) / 2; long o = w - d[v * 2]; if (mid + 1 < a.length && o >= a[mid + 1]) { l = mid + 1; v = v * 2 + 1; w = o; } else { v = v * 2; r = mid; } } return r; } int get(int v, int vl, int vr, long w) { // cout << t[v] << " "<< v << " " << vl << " " << vr<<" " << w << endl; if (d[v] < w) return -1; if (vl > vr) return -1; if (vl == vr) { if (d[v] > w) return vl - 1; else return -1; } if (d[v * 2] > w) return get(v * 2, vl, (vl + vr) / 2, w); else return get(v * 2 + 1, (vl + vr + 2) / 2, vr, w - d[v * 2]); } } private static class FenwickTree { long[] t; FenwickTree(int n) { t = new long[n]; } long sum(int r) { long result = 0; for (; r >= 0; r = (r & (r + 1)) - 1) result += t[r]; return result; } void inc(int i, long delta) { int n = t.length; for (; i < n; i = (i | (i + 1))) t[i] += delta; } } void insert(List<Long> list, Long element) { int index = Collections.binarySearch(list, element); if (index < 0) { index = -index - 1; } list.add(index, element); } public static void main(String[] args) { FastScanner scanner = new FastScanner(System.in); PrintWriter printer = new PrintWriter(System.out); long n = scanner.nextLong(); long k = scanner.nextLong(); long l = 1; long r = n; while(true){ long m = (l + r) / 2; long x = (m * (m + 1)) / 2; x -= n - m; if (x == k) { printer.println(n - m); break; } else if (x < k) { l = m + 1; } else { r = m - 1; } } printer.flush(); printer.close(); } } /* 4 2 1 1 4 0 2 3 5 3 1 2 4 0 4 5 0 3 5 4 3 1 2 3 1 1 2 0 1 3 NO */
logn
1195_B. Sport Mafia
CODEFORCES
/** * Created by IntelliJ IDEA. * User: piyushd * Date: 3/26/11 * Time: 10:53 PM * To change this template use File | Settings | File Templates. */ public class TaskB { int[] levels; int[] loyalty; int n, k, A; double ans = Double.NEGATIVE_INFINITY; void rec(int ix, int sweets, int[] loyalty) { if (ix == n) { double nres = 0.0; for(int mask = 0; mask < (1<<n); mask++) { double res = 1.0, totalStrength = 0; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) > 0) { res *= loyalty[i] / 100.0; } else { res *= 1.0 - (loyalty[i]/ 100.0); totalStrength += levels[i]; } } int bitCount = Integer.bitCount(mask); if(bitCount > n / 2) { nres += res; } else { nres += res * (A) / (A + totalStrength); } } ans = Math.max(ans, nres); return; } for (int j = 0; j <= sweets; j++) { if (loyalty[ix] + 10 * j > 100) break; int[] nloyalty = loyalty.clone(); nloyalty[ix] += 10 * j; rec(ix + 1, sweets - j, nloyalty); } } void run() { n = nextInt(); k = nextInt(); A = nextInt(); levels = new int[n]; loyalty = new int[n]; for (int i = 0; i < n; i++) { levels[i] = nextInt(); loyalty[i] = nextInt(); } rec(0, k, loyalty); System.out.println(ans); } int nextInt() { try { int c = System.in.read(); if (c == -1) return c; while (c != '-' && (c < '0' || '9' < c)) { c = System.in.read(); if (c == -1) return c; } if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } long nextLong() { try { int c = System.in.read(); if (c == -1) return -1; while (c != '-' && (c < '0' || '9' < c)) { c = System.in.read(); if (c == -1) return -1; } if (c == '-') return -nextLong(); long res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } String nextLine() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (c == '\r' || c == '\n') c = System.in.read(); do { res.append((char) c); c = System.in.read(); } while (c != '\r' && c != '\n'); return res.toString(); } catch (Exception e) { return null; } } public static void main(String[] args) { new TaskB().run(); } }
np
105_B. Dark Assembly
CODEFORCES
/* * Created on 17.05.2019 */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Wolfgang Weck */ public class C01Easy { public static void main(String[] args) { try (BufferedReader r = new BufferedReader(new InputStreamReader(System.in))) { final String[] line = r.readLine().split(" "); final int N = Integer.parseInt(line[0]), P = Integer.parseInt(line[1]); final String[] numS = r.readLine().split(" "); if (numS.length != N) throw new IllegalArgumentException(); final int[] n = new int[N]; int sum1 = 0, sum2 = 0; for (int i = 0; i < N; i++) { n[i] = Integer.parseInt(numS[i]) % P; sum2 += n[i]; if (sum2 >= P) sum2 -= P; } int max = sum2; for (int i = 0; i < N; i++) { sum1 += n[i]; if (sum1 >= P) sum1 -= P; sum2 -= n[i]; if (sum2 < 0) sum2 += P; final int s = sum1 + sum2; if (s > max) max = s; } System.out.println(max); } catch (IOException e) { e.printStackTrace(); } } }
linear
958_C1. Encryption (easy)
CODEFORCES
import java.util.Scanner; public class Iq { static void metod() throws Exception { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] m = new int[n]; for (int i = 0; i < n; i++) m[i] = in.nextInt(); byte k = 0; if (m[0] % 2 == 0) { if (m[1] % 2 == 0) { k = 0; } else { if (m[2] % 2 == 0) { System.out.println(2); return; } else { System.out.println(1); return; } } } else { if (m[1] % 2 == 1) { k = 1; } else { if (m[2] % 2 == 0) { System.out.println(1); return; } else { System.out.println(2); return; } } } if (k == 0) { for (int i = 0; i < m.length; i++) { if (m[i] % 2 == 1) { System.out.println(i + 1); break; } } } else { for (int i = 0; i < m.length; i++) { if (m[i] % 2 == 0) { System.out.println(i + 1); break; } } } } public static void main(String args[]) throws Exception { Iq.metod(); } }
linear
25_A. IQ test
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Allen Li */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Nas solver = new Nas(); solver.solve(1, in, out); out.close(); } static class Nas { public void solve(int testNumber, FastReader in, PrintWriter out) { long x = in.nextLong(); if (x == 0) { out.println(0); return; } BigInteger n1 = BigInteger.valueOf(x); BigInteger n2 = BigInteger.valueOf(in.nextLong()); BigInteger mod = BigInteger.valueOf(1000000007); BigInteger a = BigInteger.valueOf(2).modPow(n2.add(BigInteger.ONE), mod); a = a.multiply(n1); a = a.mod(mod); BigInteger b = BigInteger.valueOf(2).modPow(n2, mod).subtract(BigInteger.ONE); a = a.subtract(b); a = a.add(mod); a = a.mod(mod); out.println(a); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(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() { 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 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); } } }
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.Arrays; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.util.Random; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion(); int testCount = in.scanInt(); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class E2RotateColumnsHardVersion { int[][] dp; int[] cur; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int m = in.scanInt(); int[][] ar = new int[n][m]; int[][] max = new int[m][2]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) ar[i][j] = in.scanInt(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) max[i][0] = Math.max(max[i][0], ar[j][i]); max[i][1] = i; } CodeHash.shuffle(max); Arrays.sort(max, (o1, o2) -> -o1[0] + o2[0]); dp = new int[2][1 << n]; cur = new int[1 << n]; for (int i = 0; i < Math.min(m, n); i++) { Arrays.fill(cur, 0); Arrays.fill(dp[i & 1], 0); for (int j = 0; j < 1 << n; j++) { for (int k = 0; k < n; k++) { int sum = 0; for (int l = 0; l < n; l++) { if ((j & (1 << l)) != 0) { sum += (ar[(k + l) % n][max[i][1]]); } } cur[j] = Math.max(cur[j], sum); } } for (int j = 0; j < (1 << n); j++) { for (int k = j; ; k = (k - 1) & j) { dp[i & 1][j] = Math.max(dp[i & 1][j], dp[(i - 1) & 1][k] + cur[j ^ k]); if (k == 0) break; } } } out.println(dp[Math.min(n, m) & 1 ^ 1][(1 << n) - 1]); } } static class CodeHash { public static void shuffle(int[][] ar) { Random rd = new Random(new Random().nextInt()); for (int i = 0; i < ar.length; i++) { int index = rd.nextInt(ar.length); int[] temp = ar[i]; ar[i] = ar[index]; ar[index] = temp; } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.util.Scanner; public class Main { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); while (n-- > 0) { int a = in.nextInt(); int b = in.nextInt(); int k = 0; while (a != 0 && b != 0) { if (a > b) { int t = a / b; k += t; a = a - b * t; } else { int t = b / a; k += t; b = b - a * t; } } System.out.println(k); } } }
constant
267_A. Subtractions
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Main implements Runnable { int n; boolean inBound (int x, int y) { return x >= 1 && y >= 1 && x <= n && y <= n; } void solve() throws Exception { n = sc.nextInt(); int y = sc.nextInt(); int x = sc.nextInt(); int c = sc.nextInt(); int yu = y; int yd = y; int xl = x; int xr = x; int current = 1; int time = 0; while (current < c) { time++; yu--; yd++; xl--; xr++; // left - up { int cur = time - 1; if (yu < 1) { cur -= (-yu); } if (xl < 1) { cur -= (-xl); } if (cur > 0) { current += cur; } } // right - up { int cur = time - 1; if (yu < 1) { cur -= (-yu); } if (xr > n) { cur -= (xr - n - 1); } if (cur > 0) { current += cur; } } // left - down { int cur = time - 1; if (yd > n) { cur -= (yd - n - 1); } if (xl < 1) { cur -= (-xl); } if (cur > 0) { current += cur; } } // right - down { int cur = time - 1; if (yd > n) { cur -= (yd - n - 1); } if (xr > n) { cur -= (xr - n - 1); } if (cur > 0) { current += cur; } } if (inBound(x, yd)) current++; if (inBound(x, yu)) current++; if (inBound(xl, y)) current++; if (inBound(xr, y)) current++; } out.println(time); } BufferedReader in; PrintWriter out; FastScanner sc; static Throwable uncaught; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable t) { Main.uncaught = t; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread t = new Thread(null, new Main(), "", (1 << 26)); t.start(); t.join(); if (uncaught != null) { throw uncaught; } } } class FastScanner { BufferedReader reader; StringTokenizer strTok; public FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws IOException { while (strTok == null || !strTok.hasMoreTokens()) { strTok = new StringTokenizer(reader.readLine()); } return strTok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; public class Main implements Runnable { // //////////////////////////////////////////////////////////////////// // Solution private int n; private int nn; private double[][] a; private double[] dp; private void solve() throws Throwable { n = nextInt(); nn = 1 << n; a = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = nextDouble(); } } dp = new double[nn]; Arrays.fill(dp, -1.0); dp[nn - 1] = 1.0; for (int j = 0; j < n; j++) { pw.format(Locale.US, "%.7f ", Dp(1 << j)); } } private double Dp(int i) { if (dp[i] >= 0.0) return dp[i]; double ans = 0; int count = Integer.bitCount(i); for (int j = 0; j < n; j++) { int jj = 1 << j; if ((jj & i) == 0) { double p = Dp(jj | i); double pPair = 2.0 / (double)((count + 1) * count); double s = 0; for (int l = 0; l < n; l++) { int ll = 1 << l; if ((ll & i) != 0) { s += a[l][j]; } } ans += p * pPair * s; } } dp[i] = ans; return dp[i]; } // //////////////////////////////////////////////////////////////////// // Utility functions PrintWriter pw; BufferedReader in; StringTokenizer st; void initStreams() throws FileNotFoundException { //System.setIn(new FileInputStream("1")); in = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); } String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextString()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextString()); } static Throwable sError; public static void main(String[] args) throws Throwable { Thread t = new Thread(new Main()); t.start(); t.join(); if (sError != null) { throw sError; } } public void run() { try { initStreams(); solve(); } catch (Throwable e) { sError = e; } finally { if (pw != null) pw.close(); } } }
np
16_E. Fish
CODEFORCES
import java.util.*; import java.io.*; public class Songs { 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[1000000]; // 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(); } } static int findPos(int x, int ar[]){ for(int i=0;i<ar.length;i++){ if(ar[i]==x) return (i+1); } return -20; } public static void main(String args[])throws IOException{ Reader sc=new Reader(); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int i,j; int n=sc.nextInt(); int tt=sc.nextInt(); int t[]=new int[n]; int g[]=new int[n]; int last=0; int M=1000000007; long sum=0; for(i=0;i<n;i++){ t[i]=sc.nextInt(); g[i]=sc.nextInt()-1; } int d[][]=new int[1<<n][4]; d[0][3]=1; for(i=0;i<(1<<n);i++){ for(last=0;last<4;last++){ for(j=0;j<n;j++){ if(g[j]!=last&&((i&(1<<j)))==0){ d[i^(1<<j)][g[j]]=(d[i^(1<<j)][g[j]]+d[i][last])%M; // System.out.println((i|(1<<j))+" "+(g[j])+" "+d[i|(1<<j)][g[j]]); } } } int dur=0; for(j=0;j<n;j++){ if((i&(1<<j))>0){ dur+=t[j]; } } if(dur==tt){ // System.out.println(i); sum=(sum+d[i][0]+d[i][1]+d[i][2])%M; } } pw.println(sum); pw.close(); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class CF1141F { static class V { int l, r, a; V(int l, int r, int a) { this.l = l; this.r = r; this.a = a; } } 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 + 1]; for (int i = 1; i <= n; i++) aa[i] = Integer.parseInt(st.nextToken()); for (int i = 1; i <= n; i++) aa[i] += aa[i - 1]; int m = n * (n + 1) / 2; V[] vv = new V[m]; m = 0; for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) vv[m++] = new V(i, j, aa[j] - aa[i - 1]); Arrays.sort(vv, (u, v) -> u.a != v.a ? u.a - v.a : u.r - v.r); int[] ii_ = new int[m]; int[] ii = new int[m]; int k_ = 0; for (int i = 0, j; i < m; i = j) { j = i + 1; while (j < m && vv[j].a == vv[i].a) j++; int k = 0, r = 0; for (int h = i; h < j; h++) if (vv[h].l > r) { ii[k++] = h; r = vv[h].r; } if (k_ < k) { k_ = k; int[] tmp = ii_; ii_ = ii; ii = tmp; } } pw.println(k_); for (int h = 0; h < k_; h++) { int i = ii_[h]; pw.println(vv[i].l + " " + vv[i].r); } pw.close(); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class B { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; public void solve() throws IOException { int N = nextInt(); int A = nextInt(); int B = nextInt(); int[] nsA = new int[N]; int[] nsB = new int[N]; char[] ans = new char[N]; Arrays.fill(nsA, -1); Arrays.fill(nsB, -1); Arrays.fill(ans, 'C'); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] P = new int[N]; for (int i = 0; i < N; i++) { P[i] = nextInt(); map.put(P[i], i); } // if A == B if (A == B) { for (int i = 0; i < N; i++) { if (!map.containsKey(A - P[i])) { out.println("NO"); return; } } out.println("YES"); for (int i = 0; i < N; i++) { out.print(0 + " "); } out.println(); return; } for (int i = 0; i < N; i++) { int oppA = A - P[i]; int oppB = B - P[i]; if (map.containsKey(oppA)) { nsA[i] = map.get(oppA); } if (map.containsKey(oppB)) { nsB[i] = map.get(oppB); } } for (int i = 0; i < N; i++) { if (nsA[i] == -1 && nsB[i] == -1) { out.println("NO"); return; } } for (int i = 0; i < N; i++) { if (ans[i] != 'C') continue; if (nsA[i] == -1) { if (!go(i, 'B', ans, nsA, nsB) ){ out.println("NO"); return; } } else if (nsB[i] == -1) { if (!go(i, 'A', ans, nsA, nsB) ){ out.println("NO"); return; } } } for (int i = 0; i < N; i++) { if (ans[i] != 'C') continue; if (nsA[i] == i || nsB[i] == i) { if (nsA[i] == i) { if (!go(i, 'B', ans, nsA, nsB) ){ out.println("NO"); return; } } else { if (!go(i, 'A', ans, nsA, nsB) ){ out.println("NO"); return; } } } } for (int i = 0; i < N; i++) { if (ans[i] != 'C') continue; if (!go(i, 'A', ans, nsA, nsB) ){ out.println("NO"); return; } } for (int i = 0; i < N; i++) { if (ans[i] == 'C') { out.println("NO"); return; } } out.println("YES"); for (int i = 0; i < N; i++) { out.print(ans[i] == 'A'? 0: 1); out.print(" "); } out.println(); } public boolean go(int cur, char link, char[] ans, int[] nsA, int[] nsB) { while (ans[cur] == 'C') { int next = link == 'A'? nsA[cur]: nsB[cur]; if (next == -1) return false; if (ans[next] != 'C') return false; ans[cur] = link; ans[next] = link; int nextNext = link == 'A'? nsB[next]: nsA[next]; cur = nextNext; if (cur == -1) return true; } return true; } /** * @param args */ public static void main(String[] args) { new B().run(); } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(System.out); solve(); reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
linear
468_B. Two Sets
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastScanner sc=new FastScanner(); PrintWriter pw=new PrintWriter(System.out); double eps=1e-12; while(sc.hasNext()){ int n=sc.nextInt(); int r=sc.nextInt(); double[]shu=new double[n]; for(int i=0;i<n;i++)shu[i]=sc.nextDouble(); double[]res=new double[n]; for(int i=0;i<n;i++){ for(int j=0;j<i;j++){ double temp=Math.abs(shu[i]-shu[j]); if(temp<2*r||Math.abs(temp-2*r)<eps){ res[i]=Math.max(res[i],res[j]+Math.sqrt(4*r*r-temp*temp)); } } res[i]=Math.max(res[i],r); } for(int i=0;i<n;i++){ pw.print(res[i]+" "); } pw.flush(); } } } class FastScanner{ BufferedReader br; StringTokenizer st; FastScanner(){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } String nextLine(){ String s=""; try { s=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } boolean hasNext(){ String s=""; while(!st.hasMoreTokens()){ s=nextLine(); if(s==null)return false; st=new StringTokenizer(s); } return true; } String next(){ String s=""; while(!st.hasMoreTokens()){ s=nextLine(); st=new StringTokenizer(s); } return st.nextToken(); } int nextInt(){ return Integer.valueOf(next()); } long nextLong(){ return Long.valueOf(next()); } double nextDouble(){ return Double.valueOf(next()); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import static java.lang.Math.*; import java.lang.reflect.Array; import java.util.*; 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 { PrintWriter writer = new PrintWriter(System.out); new Task(new InputReader(System.in), writer).solve(); writer.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()); } } class Task { public void solve() { out.println(25); } private InputReader in; private PrintWriter out; Task(InputReader in, PrintWriter out) { this.in = in; this.out = out; } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.awt.geom.Point2D; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class C { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] line = in.readLine().split(" "); int n = Integer.parseInt(line[0]); int r= Integer.parseInt(line[1]); line = in.readLine().split(" "); double[] x = new double[n]; double[] y= new double[n]; for(int i = 0; i<n; i++) { y[i] = r; x[i] = Integer.parseInt(line[i]); } for(int i = 1; i<n; i++) { for(int j = 0; j<i; j++) { if(Math.abs(x[i]-x[j])>r*2) { continue; } double low = y[j]; double high = y[j]+(double)r*2.0; for(int k = 0; k<85 && low<high; k++) { double mid = (low+high)/2.0; if(Point2D.distance(x[j], y[j], x[i], mid)<(double)r*2.0) { low = mid; } else { high = mid; } } y[i] = Math.max(y[i], low); } } System.out.printf("%.15f",y[0]); for(int i = 1; i<n; i++) { System.out.printf(" %.15f",y[i]); } System.out.print("\n"); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; public class B { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; long f(int x, int y, int sz) { if (x > y) { int tmp = x; x = y; y = tmp; } if (sz <= x) return (long) sz * (sz + 1) / 2; if (sz >= x + y - 1) return (long) x * y; long val = x * (x + 1) / 2; if (sz <= y) return val + (long) (sz - x) * x; long rest = x + y - 1 - sz; return (long) x * y - (long) rest * (rest + 1) / 2; } long count(int x, int y, int n, int time) { long DL = f(x + 1, y + 1, time + 1); long DR = f(n - x, y + 1, time + 1); long UL = f(x + 1, n - y, time + 1); long UR = f(n - x, n - y, time + 1); // if (time == 1) // System.err.println(DL + " " + DR + " " + UL + " " + UR); long L = Math.min(x + 1, time + 1); long R = Math.min(n - x, time + 1); long U = Math.min(n - y, time + 1); long D = Math.min(y + 1, time + 1); // if (time == 1) // System.err.println(L + " " + R + " " + U + " " + D); return DL + DR + UL + UR - L - R - U - D + 1; } void solve() throws IOException { int n = nextInt(); int x = nextInt() - 1; int y = nextInt() - 1; long need = nextLong(); if (need == 1) { out.println(0); return; } int low = 0; int high = Math.max(x, n - 1 - x) + Math.max(y, n - 1 - y); // for (int i = 0; i <= 100; i++) // System.err.println(count(x, y, n, i)); while (low < high - 1) { int mid = (int) (((long) low + high) / 2); if (count(x, y, n, mid) >= need) high = mid; else low = mid; } out.println(high); } B() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new B(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long k = sc.nextLong(); System.out.println(solve(n, k)); sc.close(); } static long solve(long n, long k) { return Math.max(0, Math.min(n, k - 1) - ((k + 2) / 2) + 1); } }
constant
1023_B. Pair of Toys
CODEFORCES
import java.util.Scanner; /** * @author Alexander Grigoryev * Created on 01.08.11 */ public class Main { static Scanner in = new Scanner(System.in); public static void main(String[] args) { String s = in.nextLine(); int k, ans = 0; for(int i = 0; i < s.length(); i++) for(int j = i + 1; j < s.length(); j++) { for(k = 0; j + k < s.length(); k++) { if(s.charAt(i + k) != s.charAt(j + k)) break; } if(ans < k) ans = k; } System.out.println(ans); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args)throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); //idea 1 : K/2번까지만 실행해서, 그 최솟값 *2를 하면 된다 //bfs로 i,j칸에 크거나 같은 값을 가지고 진입하면, 즉시 cut StringTokenizer st = new StringTokenizer(br.readLine(), " "); n = pint(st.nextToken()); m = pint(st.nextToken()); k = pint(st.nextToken()); //up down left right //0 is wall map = new int[n][m][4]; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine(), " "); for (int j = 0; j < m-1; j++) { int temp = pint(st.nextToken()); map[i][j][3]=temp; map[i][j+1][2]=temp; } } for (int i = 0; i < n-1; i++) { st = new StringTokenizer(br.readLine(), " "); for (int j = 0; j < m; j++) { int temp = pint(st.nextToken()); map[i][j][1]=temp; map[i+1][j][0]=temp; } } ans = new int[n][m][k/2+1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if(k%2==1) { sb.append("-1 "); continue; } int min=rec(i,j,0,k/2); sb.append(min*2).append(" "); }sb.append("\n"); } System.out.println(sb); } static int n,m,k; //up down left right static int[]dx = {-1,1, 0, 0}; static int[]dy = {0, 0, -1,1}; static int[][][]map; static int[][][]ans; static int rec(int x, int y, int cost, int cnt) { if(cnt==0) { return 0; } if(ans[x][y][cnt]!=0)return ans[x][y][cnt]; int temp=Integer.MAX_VALUE; for (int i = 0; i < 4; i++) { int tx=x+dx[i], ty=y+dy[i]; if(tx<0||tx>=n||ty<0||ty>=m)continue; if(map[x][y][i]!=0) { temp=Math.min(temp, rec(tx, ty, cost, cnt-1)+map[x][y][i]); } } ans[x][y][cnt]=temp; return ans[x][y][cnt]; } static int pint(String s) { return Integer.parseInt(s); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; public class A { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { String s = sc.next(); for (int l = s.length(); l > 0; --l) { HashSet<String> set = new HashSet<String>(); for (int i = 0; i < s.length() - l + 1; ++i) if (set.contains(s.substring(i, i + l))) { System.out.println(l); return; } else { set.add(s.substring(i, i + l)); } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class CFEdu23C { static long sum(long n) { long ans=0; while(n>0) { ans+=(n%10); n/=10; } return ans; } static long BS(long l,long h,long s) { if(l<=h) { long m=(l+h)/2l; if(m-sum(m)>=s && (m==1 || (m-1)-sum(m-1)<s)) return m; else if(m-sum(m)>=s) return BS(l, m-1, s); else return BS(m+1, h, s); } return (h+1); } public static void main(String args[]) { InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); /*------------------------------My Code starts here------------------------------*/ long n=in.nextLong(),s=in.nextLong(); long x=BS(0,n,s); out.print(n-x+1); out.close(); /*------------------------------The End------------------------------------------*/ } public static final long l = (int) (1e9 + 7); private static int[] nextIntArray(InputReader in, int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); return a; } private static long[] nextLongArray(InputReader in, int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = in.nextLong(); return a; } private static int[][] nextIntMatrix(InputReader in, int n, int m) { 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(); } return a; } private static void show(int[] a) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } private static void show2DArray(char[][] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) System.out.print(a[i][j]); System.out.println(); } } static class Pair { private int first; private int second; public Pair(int i, int j) { this.first = i; this.second = j; } public int getFirst() { return first; } public int getSecond() { return second; } public void setFirst(int k) { this.first = k; } public void setSecond(int k) { this.second = k; } } static int modPow(int a, int b, int p) { int result = 1; a %= p; while (b > 0) { if ((b & 1) != 0) result = (result * a) % p; b = b >> 1; a = (a * a) % p; } return result; } public static void SieveOfEratosthenes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); prime[1] = false; int i, j; for (i = 2; i * i <= n; i++) { if (prime[i]) { for (j = i; j <= n; j += i) { if (j != i) prime[j] = false; } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine = null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.util.*; import java.io.*; public class EdF { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; public static void main(String[] havish) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); Stack<Integer> st = new Stack<>(); Stack<Integer> temporary = new Stack<>(); for(int j = 0;j<n;j++){ int val = sc.nextInt(); boolean found = false; while(!st.isEmpty()){ int temp = st.peek(); if (val == temp+1){ found = true; st.pop(); break; } else{ temporary.add(st.pop()); } } if (!found){ while(!temporary.isEmpty()){ st.add(temporary.pop()); } } st.add(val); ArrayList<Integer> arr = new ArrayList<>(); for(int s : st){ arr.add(s); } for (int s =0 ;s<arr.size()-1;s++){ out.print(arr.get(s)); out.print("."); } out.println(arr.get(arr.size()-1)); temporary.clear(); } } out.close(); } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<>(); for (int i : array) copy.add(i); Collections.sort(copy); for(int i = 0;i<array.length;i++) array[i] = copy.get(i); } static String[] readArrayString(int n){ String[] array = new String[n]; for(int j =0 ;j<n;j++) array[j] = sc.next(); return array; } static int[] readArrayInt(int n){ int[] array = new int[n]; for(int j = 0;j<n;j++) array[j] = sc.nextInt(); return array; } static int[] readArrayInt1(int n){ int[] array = new int[n+1]; for(int j = 1;j<=n;j++){ array[j] = sc.nextInt(); } return array; } static long[] readArrayLong(int n){ long[] array = new long[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextLong(); return array; } static double[] readArrayDouble(int n){ double[] array = new double[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextDouble(); return array; } static int minIndex(int[] array){ int minValue = Integer.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(long[] array){ long minValue = Long.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(double[] array){ double minValue = Double.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static long power(long x, long y){ if (y == 0) return 1; if (y%2 == 1) return (x*power(x, y-1))%mod; return power((x*x)%mod, y/2)%mod; } static void verdict(boolean a){ out.println(a ? "YES" : "NO"); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } //StringJoiner sj = new StringJoiner(" "); //sj.add(strings) //sj.toString() gives string of those stuff w spaces or whatever that sequence is
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class C { void run() throws IOException { int n = ni(), m = ni(), k = ni(), q = n * m, h = 0, t = 0, inf = 123456; int[] x = new int[q], y = new int[q]; int[][] d = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) d[i][j] = inf; for (int i = 0; i < k; i++) { int u = ni() - 1, v = ni() - 1; d[u][v] = 0; x[t] = u; y[t] = v; t++; } if (k < q) while (t != h) { int u = x[h], v = y[h]; int l = d[u][v] + 1; h++; if (u > 0 && d[u - 1][v] > l) { d[u - 1][v] = l; x[t] = u - 1; y[t] = v; t++; } if (u < n - 1 && d[u + 1][v] > l) { d[u + 1][v] = l; x[t] = u + 1; y[t] = v; t++; } if (v > 0 && d[u][v - 1] > l) { d[u][v - 1] = l; x[t] = u; y[t] = v - 1; t++; } if (v < m - 1 && d[u][v + 1] > l) { d[u][v + 1] = l; x[t] = u; y[t] = v + 1; t++; } } int max = 0, tx = 0, ty = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (d[i][j] > max) { max = d[i][j]; tx = i; ty = j; } pw.print(1 + tx + " " + (1 + ty)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } String nl() throws IOException { return br.readLine(); } PrintWriter pw; BufferedReader br; StringTokenizer st; public static void main(String[] args) throws IOException { BufferedReader _br = new BufferedReader(new FileReader(new File("input.txt"))); PrintWriter _pw = new PrintWriter(new FileWriter(new File("output.txt"))); new C(_br, _pw).run(); _br.close(); _pw.close(); } public C(BufferedReader _br, PrintWriter _pw) { br = _br; pw = _pw; } }
cubic
35_C. Fire Again
CODEFORCES
/* * Hello! You are trying to hack my solution, are you? =) * Don't be afraid of the size, it's just a dump of useful methods like gcd, or n-th Fib number. * And I'm just too lazy to create a new .java for every task. * And if you were successful to hack my solution, please, send me this test as a message or to Abrackadabraa@gmail.com. * It can help me improve my skills and i'd be very grateful for that. * Sorry for time you spent reading this message. =) * Good luck, unknown rival. =) * */ import java.io.*; import java.math.*; import java.util.*; public class Abra { // double d = 2.2250738585072012e-308; void solve() throws IOException { int n = nextInt(), t = nextInt(); TreeMap<Integer, Integer> tm = new TreeMap<Integer, Integer>(); for (int i = 0; i < n; i++) tm.put(nextInt(), nextInt()); double tx = -1e9; int c = 2; for (Map.Entry<Integer, Integer> m : tm.entrySet()) { if (tx == -1e9) { tx = m.getKey() + m.getValue() / 2.0 + t; continue; } if (m.getKey() - m.getValue() / 2.0 >= tx) c++; if (m.getKey() - m.getValue() / 2.0 > tx) c++; tx = m.getKey() + m.getValue() / 2.0 + t; } out.print(c); } public static void main(String[] args) throws IOException { new Abra().run(); } StreamTokenizer in; PrintWriter out; boolean oj; BufferedReader br; void init() throws IOException { oj = System.getProperty("ONLINE_JUDGE") != null; Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt"); br = new BufferedReader(reader); in = new StreamTokenizer(br); out = new PrintWriter(writer); } long beginTime; void run() throws IOException { beginTime = System.currentTimeMillis(); long beginMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); init(); solve(); long endMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long endTime = System.currentTimeMillis(); if (!oj) { System.out.println("Memory used = " + (endMem - beginMem)); System.out.println("Total memory = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); System.out.println("Running time = " + (endTime - beginTime)); } out.flush(); } int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } String nextString() throws IOException { in.nextToken(); return in.sval; } double nextDouble() throws IOException { in.nextToken(); return in.nval; } myLib lib = new myLib(); void time() { System.out.print("It's "); System.out.println(System.currentTimeMillis() - beginTime); } static class myLib { long fact(long x) { long a = 1; for (long i = 2; i <= x; i++) { a *= i; } return a; } long digitSum(String x) { long a = 0; for (int i = 0; i < x.length(); i++) { a += x.charAt(i) - '0'; } return a; } long digitSum(long x) { long a = 0; while (x > 0) { a += x % 10; x /= 10; } return a; } long digitMul(long x) { long a = 1; while (x > 0) { a *= x % 10; x /= 10; } return a; } int digitCubesSum(int x) { int a = 0; while (x > 0) { a += (x % 10) * (x % 10) * (x % 10); x /= 10; } return a; } double pif(double ax, double ay, double bx, double by) { return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by)); } double pif3D(double ax, double ay, double az, double bx, double by, double bz) { return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by) + (az - bz) * (az - bz)); } double pif3D(double[] a, double[] b) { return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2])); } long gcd(long a, long b) { if (a == 0 || b == 0) return 1; if (a < b) { long c = b; b = a; a = c; } while (a % b != 0) { a = a % b; if (a < b) { long c = b; b = a; a = c; } } return b; } int gcd(int a, int b) { if (a == 0 || b == 0) return 1; if (a < b) { int c = b; b = a; a = c; } while (a % b != 0) { a = a % b; if (a < b) { int c = b; b = a; a = c; } } return b; } long lcm(long a, long b) { return a * b / gcd(a, b); } int lcm(int a, int b) { return a * b / gcd(a, b); } int countOccurences(String x, String y) { int a = 0, i = 0; while (true) { i = y.indexOf(x); if (i == -1) break; a++; y = y.substring(i + 1); } return a; } int[] findPrimes(int x) { boolean[] forErato = new boolean[x - 1]; List<Integer> t = new Vector<Integer>(); int l = 0, j = 0; for (int i = 2; i < x; i++) { if (forErato[i - 2]) continue; t.add(i); l++; j = i * 2; while (j < x) { forErato[j - 2] = true; j += i; } } int[] primes = new int[l]; Iterator<Integer> iterator = t.iterator(); for (int i = 0; iterator.hasNext(); i++) { primes[i] = iterator.next().intValue(); } return primes; } int rev(int x) { int a = 0; while (x > 0) { a = a * 10 + x % 10; x /= 10; } return a; } class myDate { int d, m, y; int[] ml = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; public myDate(int da, int ma, int ya) { d = da; m = ma; y = ya; if ((ma > 12 || ma < 1 || da > ml[ma - 1] || da < 1) && !(d == 29 && m == 2 && y % 4 == 0)) { d = 1; m = 1; y = 9999999; } } void incYear(int x) { for (int i = 0; i < x; i++) { y++; if (m == 2 && d == 29) { m = 3; d = 1; return; } if (m == 3 && d == 1) { if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) { m = 2; d = 29; } return; } } } boolean less(myDate x) { if (y < x.y) return true; if (y > x.y) return false; if (m < x.m) return true; if (m > x.m) return false; if (d < x.d) return true; if (d > x.d) return false; return true; } void inc() { if ((d == 31) && (m == 12)) { y++; d = 1; m = 1; } else { if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) { ml[1] = 29; } if (d == ml[m - 1]) { m++; d = 1; } else d++; } } } int partition(int n, int l, int m) {// n - sum, l - length, m - every // part // <= m if (n < l) return 0; if (n < l + 2) return 1; if (l == 1) return 1; int c = 0; for (int i = Math.min(n - l + 1, m); i >= (n + l - 1) / l; i--) { c += partition(n - i, l - 1, i); } return c; } int rifmQuality(String a, String b) { if (a.length() > b.length()) { String c = a; a = b; b = c; } int c = 0, d = b.length() - a.length(); for (int i = a.length() - 1; i >= 0; i--) { if (a.charAt(i) == b.charAt(i + d)) c++; else break; } return c; } String numSym = "0123456789ABCDEF"; String ZFromXToYNotation(int x, int y, String z) { if (z.equals("0")) return "0"; String a = ""; // long q = 0, t = 1; BigInteger q = BigInteger.ZERO, t = BigInteger.ONE; for (int i = z.length() - 1; i >= 0; i--) { q = q.add(t.multiply(BigInteger.valueOf(z.charAt(i) - 48))); t = t.multiply(BigInteger.valueOf(x)); } while (q.compareTo(BigInteger.ZERO) == 1) { a = numSym.charAt((int) (q.mod(BigInteger.valueOf(y)).intValue())) + a; q = q.divide(BigInteger.valueOf(y)); } return a; } double angleFromXY(int x, int y) { if ((x == 0) && (y > 0)) return Math.PI / 2; if ((x == 0) && (y < 0)) return -Math.PI / 2; if ((y == 0) && (x > 0)) return 0; if ((y == 0) && (x < 0)) return Math.PI; if (x > 0) return Math.atan((double) y / x); else { if (y > 0) return Math.atan((double) y / x) + Math.PI; else return Math.atan((double) y / x) - Math.PI; } } static boolean isNumber(String x) { try { Integer.parseInt(x); } catch (NumberFormatException ex) { return false; } return true; } static boolean stringContainsOf(String x, String c) { for (int i = 0; i < x.length(); i++) { if (c.indexOf(x.charAt(i)) == -1) return false; } return true; } long pow(long a, long n) { // b > 0 if (n == 0) return 1; long k = n, b = 1, c = a; while (k != 0) { if (k % 2 == 0) { k /= 2; c *= c; } else { k--; b *= c; } } return b; } int pow(int a, int n) { // b > 0 if (n == 0) return 1; int k = n, b = 1, c = a; while (k != 0) { if (k % 2 == 0) { k /= 2; c *= c; } else { k--; b *= c; } } return b; } double pow(double a, int n) { // b > 0 if (n == 0) return 1; double k = n, b = 1, c = a; while (k != 0) { if (k % 2 == 0) { k /= 2; c *= c; } else { k--; b *= c; } } return b; } double log2(double x) { return Math.log(x) / Math.log(2); } int lpd(int[] primes, int x) {// least prime divisor int i; for (i = 0; primes[i] <= x / 2; i++) { if (x % primes[i] == 0) { return primes[i]; } } ; return x; } int np(int[] primes, int x) {// number of prime number for (int i = 0; true; i++) { if (primes[i] == x) return i; } } int[] dijkstra(int[][] map, int n, int s) { int[] p = new int[n]; boolean[] b = new boolean[n]; Arrays.fill(p, Integer.MAX_VALUE); p[s] = 0; b[s] = true; for (int i = 0; i < n; i++) { if (i != s) p[i] = map[s][i]; } while (true) { int m = Integer.MAX_VALUE, mi = -1; for (int i = 0; i < n; i++) { if (!b[i] && (p[i] < m)) { mi = i; m = p[i]; } } if (mi == -1) break; b[mi] = true; for (int i = 0; i < n; i++) if (p[mi] + map[mi][i] < p[i]) p[i] = p[mi] + map[mi][i]; } return p; } boolean isLatinChar(char x) { if (((x >= 'a') && (x <= 'z')) || ((x >= 'A') && (x <= 'Z'))) return true; else return false; } boolean isBigLatinChar(char x) { if (x >= 'A' && x <= 'Z') return true; else return false; } boolean isSmallLatinChar(char x) { if (x >= 'a' && x <= 'z') return true; else return false; } boolean isDigitChar(char x) { if (x >= '0' && x <= '9') return true; else return false; } class NotANumberException extends Exception { private static final long serialVersionUID = 1L; String mistake; NotANumberException() { mistake = "Unknown."; } NotANumberException(String message) { mistake = message; } } class Real { String num = "0"; long exp = 0; boolean pos = true; long length() { return num.length(); } void check(String x) throws NotANumberException { if (!stringContainsOf(x, "0123456789+-.eE")) throw new NotANumberException("Illegal character."); long j = 0; for (long i = 0; i < x.length(); i++) { if ((x.charAt((int) i) == '-') || (x.charAt((int) i) == '+')) { if (j == 0) j = 1; else if (j == 5) j = 6; else throw new NotANumberException("Unexpected sign."); } else if ("0123456789".indexOf(x.charAt((int) i)) != -1) { if (j == 0) j = 2; else if (j == 1) j = 2; else if (j == 2) ; else if (j == 3) j = 4; else if (j == 4) ; else if (j == 5) j = 6; else if (j == 6) ; else throw new NotANumberException("Unexpected digit."); } else if (x.charAt((int) i) == '.') { if (j == 0) j = 3; else if (j == 1) j = 3; else if (j == 2) j = 3; else throw new NotANumberException("Unexpected dot."); } else if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) { if (j == 2) j = 5; else if (j == 4) j = 5; else throw new NotANumberException("Unexpected exponent."); } else throw new NotANumberException("O_o."); } if ((j == 0) || (j == 1) || (j == 3) || (j == 5)) throw new NotANumberException("Unexpected end."); } public Real(String x) throws NotANumberException { check(x); if (x.charAt(0) == '-') pos = false; long j = 0; String e = ""; boolean epos = true; for (long i = 0; i < x.length(); i++) { if ("0123456789".indexOf(x.charAt((int) i)) != -1) { if (j == 0) num += x.charAt((int) i); if (j == 1) { num += x.charAt((int) i); exp--; } if (j == 2) e += x.charAt((int) i); } if (x.charAt((int) i) == '.') { if (j == 0) j = 1; } if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) { j = 2; if (x.charAt((int) (i + 1)) == '-') epos = false; } } while ((num.length() > 1) && (num.charAt(0) == '0')) num = num.substring(1); while ((num.length() > 1) && (num.charAt(num.length() - 1) == '0')) { num = num.substring(0, num.length() - 1); exp++; } if (num.equals("0")) { exp = 0; pos = true; return; } while ((e.length() > 1) && (e.charAt(0) == '0')) e = e.substring(1); try { if (e != "") if (epos) exp += Long.parseLong(e); else exp -= Long.parseLong(e); } catch (NumberFormatException exc) { if (!epos) { num = "0"; exp = 0; pos = true; } else { throw new NotANumberException("Too long exponent"); } } } public Real() { } String toString(long mantissa) { String a = "", b = ""; if (exp >= 0) { a = num; if (!pos) a = '-' + a; for (long i = 0; i < exp; i++) a += '0'; for (long i = 0; i < mantissa; i++) b += '0'; if (mantissa == 0) return a; else return a + "." + b; } else { if (exp + length() <= 0) { a = "0"; if (mantissa == 0) { return a; } if (mantissa < -(exp + length() - 1)) { for (long i = 0; i < mantissa; i++) b += '0'; return a + "." + b; } else { if (!pos) a = '-' + a; for (long i = 0; i < mantissa; i++) if (i < -(exp + length())) b += '0'; else if (i + exp >= 0) b += '0'; else b += num.charAt((int) (i + exp + length())); return a + "." + b; } } else { if (!pos) a = "-"; for (long i = 0; i < exp + length(); i++) a += num.charAt((int) i); if (mantissa == 0) return a; for (long i = exp + length(); i < exp + length() + mantissa; i++) if (i < length()) b += num.charAt((int) i); else b += '0'; return a + "." + b; } } } } boolean containsRepeats(int... num) { Set<Integer> s = new TreeSet<Integer>(); for (int d : num) if (!s.contains(d)) s.add(d); else return true; return false; } int[] rotateDice(int[] a, int n) { int[] c = new int[6]; if (n == 0) { c[0] = a[1]; c[1] = a[5]; c[2] = a[2]; c[3] = a[0]; c[4] = a[4]; c[5] = a[3]; } if (n == 1) { c[0] = a[2]; c[1] = a[1]; c[2] = a[5]; c[3] = a[3]; c[4] = a[0]; c[5] = a[4]; } if (n == 2) { c[0] = a[3]; c[1] = a[0]; c[2] = a[2]; c[3] = a[5]; c[4] = a[4]; c[5] = a[1]; } if (n == 3) { c[0] = a[4]; c[1] = a[1]; c[2] = a[0]; c[3] = a[3]; c[4] = a[5]; c[5] = a[2]; } if (n == 4) { c[0] = a[0]; c[1] = a[2]; c[2] = a[3]; c[3] = a[4]; c[4] = a[1]; c[5] = a[5]; } if (n == 5) { c[0] = a[0]; c[1] = a[4]; c[2] = a[1]; c[3] = a[2]; c[4] = a[3]; c[5] = a[5]; } return c; } int min(int... a) { int c = Integer.MAX_VALUE; for (int d : a) if (d < c) c = d; return c; } int max(int... a) { int c = Integer.MIN_VALUE; for (int d : a) if (d > c) c = d; return c; } int pos(int x) { if (x > 0) return x; else return 0; } long pos(long x) { if (x > 0) return x; else return 0; } double maxD(double... a) { double c = Double.MIN_VALUE; for (double d : a) if (d > c) c = d; return c; } double minD(double... a) { double c = Double.MAX_VALUE; for (double d : a) if (d < c) c = d; return c; } int[] normalizeDice(int[] a) { int[] c = a.clone(); if (c[0] != 0) if (c[1] == 0) c = rotateDice(c, 0); else if (c[2] == 0) c = rotateDice(c, 1); else if (c[3] == 0) c = rotateDice(c, 2); else if (c[4] == 0) c = rotateDice(c, 3); else if (c[5] == 0) c = rotateDice(rotateDice(c, 0), 0); while (c[1] != min(c[1], c[2], c[3], c[4])) c = rotateDice(c, 4); return c; } boolean sameDice(int[] a, int[] b) { for (int i = 0; i < 6; i++) if (a[i] != b[i]) return false; return true; } final double goldenRatio = (1 + Math.sqrt(5)) / 2; final double aGoldenRatio = (1 - Math.sqrt(5)) / 2; long Fib(int n) { if (n < 0) if (n % 2 == 0) return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5)); else return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5)); return Math.round((pow(goldenRatio, n) - pow(aGoldenRatio, n)) / Math.sqrt(5)); } class japaneeseComparator implements Comparator<String> { @Override public int compare(String a, String b) { int ai = 0, bi = 0; boolean m = false, ns = false; if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') { if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') m = true; else return -1; } if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') { if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') m = true; else return 1; } a += "!"; b += "!"; int na = 0, nb = 0; while (true) { if (a.charAt(ai) == '!') { if (b.charAt(bi) == '!') break; return -1; } if (b.charAt(bi) == '!') { return 1; } if (m) { int ab = -1, bb = -1; while (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') { if (ab == -1) ab = ai; ai++; } while (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') { if (bb == -1) bb = bi; bi++; } m = !m; if (ab == -1) { if (bb == -1) continue; else return 1; } if (bb == -1) return -1; while (a.charAt(ab) == '0' && ab + 1 != ai) { ab++; if (!ns) na++; } while (b.charAt(bb) == '0' && bb + 1 != bi) { bb++; if (!ns) nb++; } if (na != nb) ns = true; if (ai - ab < bi - bb) return -1; if (ai - ab > bi - bb) return 1; for (int i = 0; i < ai - ab; i++) { if (a.charAt(ab + i) < b.charAt(bb + i)) return -1; if (a.charAt(ab + i) > b.charAt(bb + i)) return 1; } } else { m = !m; while (true) { if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a' && b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') { if (a.charAt(ai) < b.charAt(bi)) return -1; if (a.charAt(ai) > b.charAt(bi)) return 1; ai++; bi++; } else if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a') return 1; else if (b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') return -1; else break; } } } if (na < nb) return 1; if (na > nb) return -1; return 0; } } Random random = new Random(); } void readIntArray(int[] a) throws IOException { for (int i = 0; i < a.length; i++) a[i] = nextInt(); } String readChars(int l) throws IOException { String r = ""; for (int i = 0; i < l; i++) r += (char) br.read(); return r; } class myFraction { long num = 0, den = 1; void reduce() { long d = lib.gcd(num, den); num /= d; den /= d; } myFraction(long ch, long zn) { num = ch; den = zn; reduce(); } myFraction add(myFraction t) { long nd = lib.lcm(den, t.den); myFraction r = new myFraction(nd / den * num + nd / t.den * t.num, nd); r.reduce(); return r; } public String toString() { return num + "/" + den; } } class myPoint { myPoint(int a, int b) { x = a; y = b; } int x, y; boolean equals(myPoint a) { if (x == a.x && y == a.y) return true; else return false; } public String toString() { return x + ":" + y; } } /* * class cubeWithLetters { String consts = "ЧКТФЭЦ"; char[][] letters = { { * 'А', 'Б', 'Г', 'В' }, { 'Д', 'Е', 'З', 'Ж' }, { 'И', 'Л', 'Н', 'М' }, { * 'О', 'П', 'С', 'Р' }, { 'У', 'Х', 'Щ', 'Ш' }, { 'Ы', 'Ь', 'Я', 'Ю' } }; * * char get(char x) { if (consts.indexOf(x) != -1) return x; for (int i = 0; * i < 7; i++) { for (int j = 0; j < 4; j++) { if (letters[i][j] == x) { if * (j == 0) return letters[i][3]; else return letters[i][j - 1]; } } } * return '!'; } * * void subrotate(int x) { char t = letters[x][0]; letters[x][0] = * letters[x][3]; letters[x][3] = letters[x][2]; letters[x][2] = * letters[x][1]; letters[x][1] = t; } * * void rotate(int x) { subrotate(x); char t; if (x == 0) { t = * letters[1][0]; letters[1][0] = letters[2][0]; letters[2][0] = * letters[3][0]; letters[3][0] = letters[5][2]; letters[5][2] = t; * * t = letters[1][1]; letters[1][1] = letters[2][1]; letters[2][1] = * letters[3][1]; letters[3][1] = letters[5][3]; letters[5][3] = t; } if (x * == 1) { t = letters[2][0]; letters[2][0] = letters[0][0]; letters[0][0] = * letters[5][0]; letters[5][0] = letters[4][0]; letters[4][0] = t; * * t = letters[2][3]; letters[2][3] = letters[0][3]; letters[0][3] = * letters[5][3]; letters[5][3] = letters[4][3]; letters[4][3] = t; } if (x * == 2) { t = letters[0][3]; letters[0][3] = letters[1][2]; letters[1][2] = * letters[4][1]; letters[4][1] = letters[3][0]; letters[3][0] = t; * * t = letters[0][2]; letters[0][2] = letters[1][1]; letters[1][1] = * letters[4][0]; letters[4][0] = letters[3][3]; letters[3][3] = t; } if (x * == 3) { t = letters[2][1]; letters[2][1] = letters[4][1]; letters[4][1] = * letters[5][1]; letters[5][1] = letters[0][1]; letters[0][1] = t; * * t = letters[2][2]; letters[2][2] = letters[4][2]; letters[4][2] = * letters[5][2]; letters[5][2] = letters[0][2]; letters[0][2] = t; } if (x * == 4) { t = letters[2][3]; letters[2][3] = letters[1][3]; letters[1][3] = * letters[5][1]; letters[5][1] = letters[3][3]; letters[3][3] = t; * * t = letters[2][2]; letters[2][2] = letters[1][2]; letters[1][2] = * letters[5][0]; letters[5][0] = letters[3][2]; letters[3][2] = t; } if (x * == 5) { t = letters[4][3]; letters[4][3] = letters[1][0]; letters[1][0] = * letters[0][1]; letters[0][1] = letters[3][2]; letters[3][2] = t; * * t = letters[4][2]; letters[4][2] = letters[1][3]; letters[1][3] = * letters[0][0]; letters[0][0] = letters[3][1]; letters[3][1] = t; } } * * public String toString(){ return " " + letters[0][0] + letters[0][1] + * "\n" + " " + letters[0][3] + letters[0][2] + "\n" + letters[1][0] + * letters[1][1] + letters[2][0] + letters[2][1] + letters[3][0] + * letters[3][1] + "\n" + letters[1][3] + letters[1][2] + letters[2][3] + * letters[2][2] + letters[3][3] + letters[3][2] + "\n" + " " + * letters[4][0] + letters[4][1] + "\n" + " " + letters[4][3] + * letters[4][2] + "\n" + " " + letters[5][0] + letters[5][1] + "\n" + " " * + letters[5][3] + letters[5][2] + "\n"; } } * * * Vector<Integer>[] a; int n, mc, c1, c2; int[] col; * * void wave(int x, int p) { for (Iterator<Integer> i = a[x].iterator(); * i.hasNext(); ) { int t = i.next(); if (t == x || t == p) continue; if * (col[t] == 0) { col[t] = mc; wave(t, x); } else { c1 = x; c2 = t; } } } * * void solve() throws IOException { * * String s = "ЕПОЕЬРИТСГХЖЗТЯПСТАПДСБИСТЧК"; //String s = * "ЗЬУОЫТВЗТЯПУБОЫТЕАЫШХЯАТЧК"; cubeWithLetters cube = new * cubeWithLetters(); for (int x = 0; x < 4; x++) { for (int y = x + 1; y < * 5; y++) { for (int z = y + 1; z < 6; z++) { cube = new cubeWithLetters(); * out.println(cube.toString()); cube.rotate(x); * out.println(cube.toString()); cube.rotate(y); * out.println(cube.toString()); cube.rotate(z); * out.println(cube.toString()); out.print(x + " " + y + " " + z + " = "); * for (int i = 0; i < s.length(); i++) { out.print(cube.get(s.charAt(i))); * } out.println(); } } } * * int a = nextInt(), b = nextInt(), x = nextInt(), y = nextInt(); * out.print((lib.min(a / (x / lib.gcd(x, y)), b / (y / lib.gcd(x, y))) * (x * / lib.gcd(x, y))) + " " + (lib.min(a / (x / lib.gcd(x, y)), b / (y / * lib.gcd(x, y))) * (y / lib.gcd(x, y)))); } */ }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.Scanner; public class GenerateLogin { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String a = scan.next(); String b = scan.next(); char last = b.charAt(0); String ans = ""+a.charAt(0); for(int i = 1;i<a.length();i++){ if(a.charAt(i)>=last)break; ans+=a.charAt(i); } ans+=last; System.out.println(ans); } }
linear
909_A. Generate Login
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class KingEscape { public static void main(String[] args) { Reader read = new Reader(); int n = read.nextInt(); int a1 = read.nextInt(); int a2 = read.nextInt(); int b1 = read.nextInt(); int b2 = read.nextInt(); int c1 = read.nextInt(); int c2 = read.nextInt(); if (b1 > a1 && b2 > a2 && c1 > a1 && c2 > a2) System.out.print("YES"); else if (b1 > a1 && b2 < a2 && c1 > a1 && c2 < a2) System.out.print("YES"); else if (b1 < a1 && b2 > a2 && c1 < a1 && c2 > a2) System.out.print("YES"); else if (b1 < a1 && b2 < a2 && c1 < a1 && c2 < a2) System.out.print("YES"); else System.out.print("NO"); } private static class Reader { private final BufferedReader reader; private final String separator; private String ln; private String[] tokens; private int ptr; Reader(String separator, InputStream input) { this.reader = new BufferedReader(new InputStreamReader(input)); this.separator = separator; this.ptr = -1; } Reader(String separator) { this(separator, System.in); } Reader() { this(" "); } String nextStr(){ if (Objects.isNull(ln)) { try { ln = reader.readLine(); } catch (IOException e) { System.out.println(e.getMessage()); } if (Objects.nonNull(ln)) { tokens = ln.split(separator); ptr = 0; } else { throw new NoSuchElementException("no next element"); } } else if (ptr == tokens.length) { ln = null; tokens = null; ptr = -1; return nextStr(); } return tokens[ptr++]; } int nextInt() { return Integer.parseInt(nextStr()); } long nextLong() { return Long.parseLong(nextStr()); } double nextDouble() { return Double.parseDouble(nextStr()); } } }
constant
1033_A. King Escape
CODEFORCES
import java.util.Scanner; public class Main{ static final double eps = 1e-10; public static void main(String []args){ Scanner cin = new Scanner(System.in); double a,v; double l,d,w; double time; a = cin.nextDouble(); v = cin.nextDouble(); l = cin.nextDouble(); d = cin.nextDouble(); w = cin.nextDouble(); if(v < w + eps) { double t1 = v / a; double len_bond = (v * v) / (2 * a); if(len_bond + eps > l) { time = Math.sqrt(2 * l / a); } else { double t2 = (l - len_bond) / v; time = t1 + t2; } System.out.println(time); } else { double len_bondv = (v * v) / (2 * a); double len_bondw = (w * w) / (2 * a); if(len_bondw + eps > d) { if(len_bondv + eps > l) time = Math.sqrt(2 * l / a); else{ double t1 = v / a; double t2 = (l - len_bondv) / v; time = t1 + t2; } } else { double len_bonds = (v * v - w * w) / (2 * a); if(len_bondv + len_bonds < d + eps) time = v / a + (d - len_bondv - len_bonds) / v + (v - w) / a; else { double f = Math.sqrt(d * a + w * w / 2); time = f / a + (f - w) / a; } if (len_bonds + eps > l - d) { double lv = Math.sqrt((l - d) * 2 * a + w * w); time += (lv - w) / a; } else { time += (v - w) / a + (l - d - len_bonds) / v; } } System.out.println(time); } } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ 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); F2SameSumBlocksHard solver = new F2SameSumBlocksHard(); solver.solve(1, in, out); out.close(); } static class F2SameSumBlocksHard { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); long[] a = in.nextLongArray(n); long[] p = in.calculatePrefixSum(a); Map<Long, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { long sum = 0; for (int j = i; j < n; j++) { sum += a[j]; map.merge(sum, 1, (x, y) -> x + y); } } List<sum> sums = new ArrayList<>(); for (long sum : map.keySet()) { sums.add(new sum(sum, map.get(sum))); } sums.sort((x, y) -> y.c - x.c); int ans = -1; int[] fca = null; long mxsum = -1; for (int i = 0; i < sums.size(); i++) { sum cs = sums.get(i); long sum = cs.sum; long c = cs.c; if (c < ans) { continue; } Map<Long, Integer> lm = new HashMap<>(); int[] ca = new int[n]; lm.put(0l, -1); for (int j = 0; j < n; j++) { long val = p[j]; if (j > 0) { ca[j] = ca[j - 1]; } long req = val - sum; if (lm.containsKey(req)) { int li = lm.get(req); if (li == -1) ca[j] = Math.max(1, ca[j]); else ca[j] = Math.max(1 + ca[li], ca[j]); } lm.put(val, j); } if (ca[n - 1] > ans) { ans = ca[n - 1]; mxsum = sum; fca = ca; } } List<Integer> al = new ArrayList<>(); long sum = 0; for (int i = n - 1; i >= 0; i--) { if (i > 0 && fca[i] != fca[i - 1]) { sum = 0; al.add(i + 1); do { sum += a[i]; i--; } while (i >= 0 && sum != mxsum); i++; al.add(i + 1); } else if (i == 0) { if (a[i] == mxsum) { al.add(i + 1); al.add(i + 1); } } } out.println(al.size() / 2); for (int i = al.size() - 1; i >= 0; i -= 2) { out.println(al.get(i) + " " + al.get(i - 1)); } } class sum { long sum; int c; public sum(long sum, int c) { this.sum = sum; this.c = c; } } } 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 static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; ++i) array[i] = nextLong(); return array; } public long[] calculatePrefixSum(long[] a) { int n = a.length; long[] prefixSum = new long[n]; prefixSum[0] = a[0]; for (int i = 1; i < n; i++) { prefixSum[i] = prefixSum[i - 1] + a[i]; } return prefixSum; } 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 print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
//Author: Patel Rag //Java version "1.8.0_211" import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long modExp(long x, long n, long mod) //binary Modular exponentiation { long result = 1; while(n > 0) { if(n % 2 == 1) result = (result%mod * x%mod)%mod; x = (x%mod * x%mod)%mod; n=n/2; } return result; } static long gcd(long a, long b) { if(a==0) return b; return gcd(b%a,a); } public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); long n = fr.nextLong(); long x = fr.nextLong(); long y = fr.nextLong(); long w = Long.min(x,y) - 1 + (x - Long.min(x,y)) + (y - Long.min(x,y)); long b = n - Long.max(x,y) + (Long.max(x,y) - x) + (Long.max(x,y) - y); if(w <= b) System.out.println("White"); else System.out.println("Black"); } } class Pair<U, V> // Pair class { public final U first; // first field of a Pair public final V second; // second field of a Pair private Pair(U first, V second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (!first.equals(pair.first)) return false; return second.equals(pair.second); } @Override public int hashCode() { return 31 * first.hashCode() + second.hashCode(); } public static <U, V> Pair <U, V> of(U a, V b) { return new Pair<>(a, b); } } class myComp implements Comparator<Pair> { public int compare(Pair a,Pair b) { if(a.first != b.first) return ((int)a.first - (int)b.first); if(a.second != b.second) return ((int)a.second - (int)b.second); return 0; } } class BIT //Binary Indexed Tree aka Fenwick Tree { public long[] m_array; public BIT(long[] dat) { m_array = new long[dat.length + 1]; Arrays.fill(m_array,0); for(int i = 0; i < dat.length; i++) { m_array[i + 1] = dat[i]; } for(int i = 1; i < m_array.length; i++) { int j = i + (i & -i); if(j < m_array.length) { m_array[j] = m_array[j] + m_array[i]; } } } public final long prefix_query(int i) { long result = 0; for(++i; i > 0; i = i - (i & -i)) { result = result + m_array[i]; } return result; } public final long range_query(int fro, int to) { if(fro == 0) { return prefix_query(to); } else { return (prefix_query(to) - prefix_query(fro - 1)); } } public void update(int i, long add) { for(++i; i < m_array.length; i = i + (i & -i)) { m_array[i] = m_array[i] + add; } } }
constant
1075_A. The King's Race
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class A { public static void main(String[] args) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { String input; while ((input = reader.readLine()) != null && input.length() > 0) { int n = Integer.parseInt(input); int start = 4; int end = n - start; while (start <= end) { if ((start % 2 == 0 || start % 3 == 0) && (end % 2 == 0 || end % 3 == 0)) { System.out.println(start + " " + end); break; } ++start; --end; } } } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedList; import java.util.StringTokenizer; import javafx.util.Pair; public class Solve6 { public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(System.out); new Solve6().solve(pw); pw.flush(); pw.close(); } public void solve(PrintWriter pw) throws IOException { FastReader sc = new FastReader(); int n = sc.nextInt(); int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = sc.nextInt(); } HashMap<Integer, LinkedList<Pair<Integer, Integer>>> h = new HashMap(); for (int i = 1; i <= n; i++) { int s = 0; for (int j = i; j >= 1; j--) { s += a[j]; LinkedList<Pair<Integer, Integer>> l; if (!h.containsKey(s)) { l = new LinkedList(); } else { l = h.get(s); } l.add(new Pair(j, i)); h.put(s, l); } } LinkedList<Pair<Integer, Integer>>[] l = new LinkedList[h.size() + 1]; for (int i = 1; i <= h.size(); i++) { l[i] = new LinkedList(); } int k = 0, max = 0, index = 0; for (LinkedList<Pair<Integer, Integer>> temp : h.values()) { k++; int i = 0, size = 0; for (Pair<Integer, Integer> pair : temp) { if (pair.getKey() > i) { i = pair.getValue(); l[k].add(pair); size++; if (size > max) { max = size; index = k; } } } } pw.println(l[index].size()); for (Pair<Integer, Integer> pair : l[index]) { pw.println(pair.getKey() + " " + pair.getValue()); } } static class FastReader { StringTokenizer st; BufferedReader br; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public boolean hasNext() throws IOException { String s = br.readLine(); if (s == null || s.isEmpty()) { return false; } st = new StringTokenizer(s); return true; } public String next() throws IOException { if (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s.isEmpty()) { return null; } st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; public class Main{ static long MOD = 1_000_000_007L; //static long MOD = 998_244_353L; //static long MOD = 1_000_000_033L; static long inv2 = (MOD + 1) / 2; static int[][] dir = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static long lMax = 0x3f3f3f3f3f3f3f3fL; static int iMax = 0x3f3f3f3f; static HashMap <Long, Long> memo = new HashMap(); static MyScanner sc = new MyScanner(); //static ArrayList <Integer> primes; static int nn = 300000; static long[] pow2; static long [] fac; static long [] pow; static long [] inv; static long [] facInv; static int[] base; static int[] numOfDiffDiv; static int[] numOfDiv; static ArrayList <Integer> primes; //static int[] primes; static int ptr = 0; static boolean[] isPrime; //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); // Start writing your solution here. ------------------------------------- /*fac = new long[nn + 1]; fac[1] = 1; for(int i = 2; i <= nn; i++) fac[i] = fac[i - 1] * i % MOD;*/ /*pow2 = new long[nn + 1]; pow2[0] = 1L; for(int i = 1; i <= nn; i++) pow2[i] = pow2[i - 1] * 2L;*/ /*inv = new long[nn + 1]; inv[1] = 1; for (int i = 2; i <= nn; ++i) inv[i] = (MOD - MOD / i) * inv[(int)(MOD % i)] % MOD;*/ /*facInv = new long[nn + 1]; facInv[0] = facInv[1] = 1; for (int i = 2; i <= nn; ++i) facInv[i] = facInv[i - 1] * inv[i] % MOD;*/ /*numOfDiffDiv = new int[nn + 1]; for(int i = 2; i <= nn; i++) if(numOfDiffDiv[i] == 0) for(int j = i; j <= nn; j += i) numOfDiv[j] ++;*/ /*numOfDiv = new int[nn + 1]; numOfDiv[1] = 1; for(int i = 2; i <= nn; i++) { for(int j = 2; j * j <= i; j++) { if(i % j == 0) { numOfDiv[i] = numOfDiv[i / j] + 1; break; } } }*/ //primes = sieveOfEratosthenes(100001); /* int t = 1; //t = sc.ni(); while(t-- > 0) { //boolean res = solve(); //out.println(res ? "YES" : "NO"); long res = solve(); out.println(res); }*/ int t = 1, tt = 0; //t = sc.ni(); for(int i = 1; i <40000; i++) squares.add(i * i); while(tt++ < t) { boolean res = solve(); //out.println("Case #" + tt + ": " + res); //out.println(res ? "YES" : "NO"); } out.close(); } static HashSet <Integer> squares = new HashSet(); static boolean solve() { /*String s = sc.nextLine(); char[] c = s.toCharArray(); int n = c.length;*/ //int n = sc.ni(); //long[] a = new long[n]; //for(int i = 0; i < n; i++) a[i] = sc.nl(); long res = 0; int n = sc.ni(); long m = sc.nl(); long[][][] dp = new long[2][5][5]; long[][][] dp2 = new long[2][5][5]; dp[0][2][1] = dp[1][2][2] = dp2[0][1][1] = 1L; for(int i = 3; i <= n; i++) { long[][] bef = dp[0]; long[][] aft = dp[1]; long[][] nbef = new long[i + 3][i + 3]; long[][] naft = new long[i + 3][i + 3]; for(int len = 1; len <= i; len++) { for(int ind = 1; ind <= len; ind++) { nbef[len + 1][1] += bef[len][ind]; nbef[len + 1][ind + 1] -= bef[len][ind]; naft[len + 1][ind + 1] += bef[len][ind]; //naft[len + 1][len + 2] -= bef[len][ind]; naft[len + 1][ind + 1] += aft[len][ind]; //naft[len + 1][len + 2] -= aft[len][ind]; nbef[len + 1][1] += dp2[0][len][ind] + dp2[1][len][ind]; //nbef[len + 1][len + 2] -= dp2[0][len][ind] + dp2[1][len][ind]; } } for(int len = 1; len <= i; len++) { for(int ind = 1; ind <= len; ind ++) { nbef[len][ind] = (nbef[len][ind] + nbef[len][ind - 1] + 10000000L * m) % m; naft[len][ind] = (naft[len][ind] + naft[len][ind - 1] + 10000000L * m) % m; } } dp2 = dp; dp = new long[][][]{nbef, naft}; } for(long[] row: dp[0]) for(long i : row) res += i; for(long[] row: dp[1]) for(long i : row) res += i; out.println(res % m); return false; } // edges to adjacency list by uwi public static int[][] packU(int n, int[] from, int[] to) { return packU(n, from, to, from.length); } public static int[][] packU(int n, int[] from, int[] to, int sup) { int[][] g = new int[n][]; int[] p = new int[n]; for (int i = 0; i < sup; i++) p[from[i]]++; for (int i = 0; i < sup; i++) p[to[i]]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < sup; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } // tree diameter by uwi public static int[] diameter(int[][] g) { int n = g.length; int f0 = -1, f1 = -1, d01 = -1; int[] q = new int[n]; boolean[] ved = new boolean[n]; { int qp = 0; q[qp++] = 0; ved[0] = true; for(int i = 0;i < qp;i++){ int cur = q[i]; for(int e : g[cur]){ if(!ved[e]){ ved[e] = true; q[qp++] = e; continue; } } } f0 = q[n-1]; } { int[] d = new int[n]; int qp = 0; Arrays.fill(ved, false); q[qp++] = f0; ved[f0] = true; for(int i = 0;i < qp;i++){ int cur = q[i]; for(int e : g[cur]){ if(!ved[e]){ ved[e] = true; q[qp++] = e; d[e] = d[cur] + 1; continue; } } } f1 = q[n-1]; d01 = d[f1]; } return new int[]{d01, f0, f1}; } public static long c(int n, int k) { return (fac[n] * facInv[k] % MOD) * facInv[n - k] % MOD; } // SegmentTree range min/max query by uwi public static class SegmentTreeRMQ { public int M, H, N; public int[] st; public SegmentTreeRMQ(int n) { N = n; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; st = new int[M]; Arrays.fill(st, 0, M, Integer.MAX_VALUE); } public SegmentTreeRMQ(int[] a) { N = a.length; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; st = new int[M]; for(int i = 0;i < N;i++){ st[H+i] = a[i]; } Arrays.fill(st, H+N, M, Integer.MAX_VALUE); for(int i = H-1;i >= 1;i--)propagate(i); } public void update(int pos, int x) { st[H+pos] = x; for(int i = (H+pos)>>>1;i >= 1;i >>>= 1)propagate(i); } private void propagate(int i) { st[i] = Math.min(st[2*i], st[2*i+1]); } public int minx(int l, int r){ int min = Integer.MAX_VALUE; if(l >= r)return min; while(l != 0){ int f = l&-l; if(l+f > r)break; int v = st[(H+l)/f]; if(v < min)min = v; l += f; } while(l < r){ int f = r&-r; int v = st[(H+r)/f-1]; if(v < min)min = v; r -= f; } return min; } public int min(int l, int r){ return l >= r ? 0 : min(l, r, 0, H, 1);} private int min(int l, int r, int cl, int cr, int cur) { if(l <= cl && cr <= r){ return st[cur]; }else{ int mid = cl+cr>>>1; int ret = Integer.MAX_VALUE; if(cl < r && l < mid){ ret = Math.min(ret, min(l, r, cl, mid, 2*cur)); } if(mid < r && l < cr){ ret = Math.min(ret, min(l, r, mid, cr, 2*cur+1)); } return ret; } } } public static char[] rev(char[] a){char[] b = new char[a.length];for(int i = 0;i < a.length;i++)b[a.length-1-i] = a[i];return b;} public static double dist(double a, double b){ return Math.sqrt(a * a + b * b); } public static long inv(long a){ return quickPOW(a, MOD - 2); } public class Interval { int start; int end; public Interval(int start, int end) { this.start = start; this.end = end; } } public static ArrayList<Integer> sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * 2; i <= n; i += p) { prime[i] = false; } } } ArrayList<Integer> primeNumbers = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (prime[i]) { primeNumbers.add(i); } } return primeNumbers; } public static int lowerBound(int[] a, int v){ return lowerBound(a, 0, a.length, v); } public static int lowerBound(int[] a, int l, int r, int v) { if(l > r || l < 0 || r > a.length)throw new IllegalArgumentException(); int low = l-1, high = r; while(high-low > 1){ int h = high+low>>>1; if(a[h] >= v){ high = h; }else{ low = h; } } return high; } public static int rlowerBound(int[] a, int v){ return lowerBound(a, 0, a.length, v); } public static int rlowerBound(int[] a, int l, int r, int v) { if(l > r || l < 0 || r > a.length)throw new IllegalArgumentException(); int low = l-1, high = r; while(high-low > 1){ int h = high+low>>>1; if(a[h] <= v){ high = h; }else{ low = h; } } return high; } public static long C(int n, int m) { if(m == 0 || m == n) return 1l; if(m > n || m < 0) return 0l; long res = fac[n] * quickPOW((fac[m] * fac[n - m]) % MOD, MOD - 2) % MOD; return res; } public static long quickPOW(long n, long m) { long ans = 1l; while(m > 0) { if(m % 2 == 1) ans = (ans * n) % MOD; n = (n * n) % MOD; m >>= 1; } return ans; } public static long quickPOW(long n, long m, long mod) { long ans = 1l; while(m > 0) { if(m % 2 == 1) ans = (ans * n) % mod; n = (n * n) % mod; m >>= 1; } return ans; } public static int gcd(int a, int b) { if(a % b == 0) return b; return gcd(b, a % b); } public static long gcd(long a, long b) { if(a % b == 0) return b; return gcd(b, a % b); } static class Randomized { public static void shuffle(int[] data) { shuffle(data, 0, data.length - 1); } public static void shuffle(int[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); int tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static void shuffle(long[] data) { shuffle(data, 0, data.length - 1); } public static void shuffle(long[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); long tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static int nextInt(int l, int r) { return RandomWrapper.INSTANCE.nextInt(l, r); } } static class RandomWrapper { private Random random; public static final RandomWrapper INSTANCE = new RandomWrapper(new Random()); public RandomWrapper() { this(new Random()); } public RandomWrapper(Random random) { this.random = random; } public int nextInt(int l, int r) { return random.nextInt(r - l + 1) + l; } } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Round1TaskB implements Runnable { static PrintWriter pw = null; static BufferedReader br = null; StringTokenizer st = null; public static void main(String[] args) throws IOException { pw = new PrintWriter(new OutputStreamWriter(System.out)); br = new BufferedReader(new InputStreamReader(System.in)); (new Thread(new Round1TaskB())).start(); } void nline() { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } int ni() { while (st == null || !st.hasMoreTokens()) nline(); return Integer.valueOf(st.nextToken()); } double nd() { while (st == null || !st.hasMoreTokens()) nline(); return Double.valueOf(st.nextToken()); } long nl() { while (st == null || !st.hasMoreTokens()) nline(); return Long.valueOf(st.nextToken()); } String nwrd() { while (st == null || !st.hasMoreTokens()) nline(); return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (IOException e) { } return null; } boolean isDigit(char c) { if (c <= '9' && c >= '0') return true; return false; } void rec(int t, int length) { if (length == 0) { return; } rec(t / 26, length - 1); pw.print((char) ('A' + (t % 26))); } void RC(int i, int j) { int num = 0; for (int t = i; t < j; t++) { num = num * 10 + format[t] - '0'; } int len = 0, base = 1, total = 0; while (true) { base *= 26; total += base; len++; if (num <= total) break; } num -= total / 26; rec(num, len); } void BC(int i, int j) { int total = 0, base = 1, rest = 0; for (int k = i; k< j; k++) { total += base; base *= 26; rest = rest * 26 + format[k] - 'A'; } pw.print(total + rest); } char format[]; public void solve() { format = nwrd().toCharArray(); int L = format.length; for (int i = 0; i < L - 1; i++) { if (isDigit(format[i]) && (format[i + 1] == 'C')) { RC(i + 2, L); for (int j = 1; j <= i; j++) { pw.print(format[j]); } pw.println(); return; } } for (int i = 0; i < L; i++) { if (isDigit(format[i])) { pw.print('R'); for (int j = i; j < L; j++) { pw.print(format[j]); } pw.print('C'); BC(0, i); pw.println(); return; } } } public void run() { int n = ni(); while (n-- > 0) { solve(); } pw.close(); } }
linear
1_B. Spreadsheets
CODEFORCES
// LM10: The next Ballon d'or import java.util.*; import java.io.*; import java.math.*; import javafx.util.Pair; public class Main { static class FastReader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public FastReader() { this(System.in); }public FastReader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String next(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;} public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;} public double d() throws IOException {return Double.parseDouble(next()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void scanIntArr(int [] arr){ for(int li=0;li<arr.length;++li){ arr[li]=i();}} public void scanLongArr(long [] arr){for (int i=0;i<arr.length;++i){arr[i]=l();}} public void shuffle(int [] arr){ for(int i=arr.length;i>0;--i) { int r=(int)(Math.random()*i); int temp=arr[i-1]; arr[i-1]=arr[r]; arr[r]=temp; } } } public static void main(String[] args)throws IOException { /* inputCopy 4 2 1 2 1 outputCopy 4 inputCopy 5 0 -1 -1 -1 -1 outputCopy 4 */ PrintWriter pw = new PrintWriter(System.out); FastReader fr = new FastReader(); int n=fr.i(); int [] arr=new int[n]; fr.scanIntArr(arr); int min=Integer.MAX_VALUE; int max=Integer.MIN_VALUE; long sum=0; if(n==1) { pw.println(arr[0]); pw.flush(); pw.close(); return; } for(int i=0;i<n;++i) { if(arr[i]<min) min=arr[i]; if(arr[i]>max) max=arr[i]; sum+=Math.abs(arr[i]); } if(min>0) { sum-=2*min; } if(max<0) { sum+=2*max; } pw.println(sum); pw.flush(); pw.close(); } }
linear
1038_D. Slime
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { static void insert(TreeMap<Integer, Integer>map,int v,int d) { if(!map.containsKey(v))map.put(v, 0); map.put(v, d+map.get(v)); if(map.get(v)==0)map.remove(v); } static void cut(TreeSet<Integer> cuts, TreeMap<Integer, Integer>segments,int v) { int upper = cuts.higher(v) , lower = cuts.lower(v); insert(segments, upper-lower, -1); insert(segments, upper-v, 1); insert(segments, v-lower, 1); cuts.add(v); } public static void main(String[] args) throws Throwable { Scanner sc = new Scanner(System.in); int w = sc.nextInt(), h = sc.nextInt() , n = sc.nextInt(); TreeSet<Integer> vCuts = new TreeSet<>() , hCuts = new TreeSet<>(); TreeMap<Integer, Integer> vSegments = new TreeMap<>() , hSegments = new TreeMap<>(); vCuts.add(0);vCuts.add(w); hCuts.add(0);hCuts.add(h); insert(vSegments, w, 1); insert(hSegments, h, 1); StringBuilder sb = new StringBuilder(); while(n-->0) { if(sc.next().equals("H")) cut(hCuts, hSegments, sc.nextInt()); else cut(vCuts, vSegments, sc.nextInt()); sb.append(1l*hSegments.lastKey() * vSegments.lastKey() + "\n"); } System.out.println(sb); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) {br = new BufferedReader(new InputStreamReader(s));} public Scanner(String file) throws FileNotFoundException {br = new BufferedReader(new FileReader(file));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken();} public int 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 int[] nexIntArray() throws Throwable { st = new StringTokenizer(br.readLine()); int[] a = new int[st.countTokens()]; for (int i = 0; i < a.length; i++)a[i] = nextInt(); return a; } public boolean ready() throws IOException {return br.ready();} } }
nlogn
528_A. Glass Carving
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class Main { private static final int MAX = 5000 + 10,mod = 1000000007; private static char [] S; private static int n; private static Integer [] [] dp = new Integer[MAX][MAX]; private static int solve(int pos,int open){ if(pos == n) return (open == 0) ? 1 : 0; if (dp[pos][open] != null) return dp[pos][open]; int res = 0; if (S[pos] == 's') { res = solve(pos + 1,open); if (open > 0) res += solve(pos,open - 1); if (res >= mod) res -= mod; } else { res = solve(pos+1,open + 1); } return dp[pos][open] = res; } public static void main(String[] args) throws Exception{ IO io = new IO(null,null); n = io.getNextInt(); S = new char[n]; for (int i = 0;i < n;i++) S[i] = io.getNext().charAt(0); io.println(solve(0,0)); io.close(); } } class IO{ private BufferedReader br; private StringTokenizer st; private PrintWriter writer; private String inputFile,outputFile; public boolean hasMore() throws IOException{ if(st != null && st.hasMoreTokens()) return true; if(br != null && br.ready()) return true; return false; } public String getNext() throws FileNotFoundException, IOException{ while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String getNextLine() throws FileNotFoundException, IOException{ return br.readLine().trim(); } public int getNextInt() throws FileNotFoundException, IOException{ return Integer.parseInt(getNext()); } public long getNextLong() throws FileNotFoundException, IOException{ return Long.parseLong(getNext()); } public void print(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f" ,x); } public void println(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f\n" ,x); } public void print(Object o) throws IOException{ writer.print(o.toString()); } public void println(Object o) throws IOException{ writer.println(o.toString()); } public IO(String x,String y) throws FileNotFoundException, IOException{ inputFile = x; outputFile = y; if(x != null) br = new BufferedReader(new FileReader(inputFile)); else br = new BufferedReader(new InputStreamReader(System.in)); if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile))); else writer = new PrintWriter(new OutputStreamWriter(System.out)); } protected void close() throws IOException{ br.close(); writer.close(); } }
quadratic
909_C. Python Indentation
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 A { 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 d = nextInt(); int[]x = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt(); } int ans = 2; for (int i = 1; i < n; i++) { if (x[i]-x[i-1]==2*d) ans++; else if (x[i]-x[i-1] > 2*d) ans += 2; } 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(); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.OutputStream; import java.util.HashSet; public class C { public static void main(String args[]) { Kattio sc = new Kattio(System.in); int n = sc.getInt(); String s = sc.getWord(); int[] found = new int['z' + 1]; int amount = 0; for(int i = 0; i<s.length(); i++) { char c = s.charAt(i); if(found[c] == 0) amount++; found[c]++; } int contains[] = new int['z' + 1]; int min = n; int start = 0; int end = 0; int in = 0; while(true) { if(in<amount) { if(end == n) break; char c = s.charAt(end); if(contains[c] == 0) in++; contains[c]++; end++; } else { if(min>end-start) min = end-start; char c = s.charAt(start); if(contains[c] == 1) in--; contains[c]--; start++; } } System.out.println(min); } } class Kattio extends PrintWriter { public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.*; import java.io.*; public class solve { Scanner in; PrintWriter out; public void solve() throws IOException { int n = in.nextInt(); long k = in.nextLong(); int[] a = new int[n]; Set<Long> b = new TreeSet<Long>(); for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); int ans = 0; for (int i = n - 1; i >= 0; i--) { if (!b.contains((long) k * a[i])) { ans++; b.add((long) a[i]); } } out.print(ans); } public void run() { try { in = new Scanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } 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()); } } public static void main(String[] arg) { new solve().run(); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.util.*; import java.io.*; public class e{ int n; double f[]; double a[][]; public void run(){ Locale.setDefault(Locale.US); Scanner in = new Scanner(System.in); n = in.nextInt(); a = new double[n][n]; for(int i=0;i<n;i++) for(int j=0;j<n;j++) a[i][j] = in.nextDouble(); f = new double[1<<n]; for(int i=0;i<1<<n;i++) f[i] = -1; f[(1<<n)-1] = 1.0; for(int i=0;i<n;i++) System.out.print(doIt(1<<i) + " "); } private double doIt(int mask){ if (f[mask] >=0) return f[mask]; f[mask] = 0; double k = getBits(mask); k*=(k-1)/2.0; for(int i=0;i<n;i++) if ((mask & (1 << i)) > 0) for(int j=0;j<n;j++) if ((mask & (1 << j)) == 0) f[mask]+=doIt(mask|(1<<j))*a[i][j]/k; return f[mask]; } private int getBits(int x){ int cnt = 0; while(x > 0){ x&=(x-1); cnt++; } return cnt+1; } public static void main(String args[]){ new e().run(); } }
np
16_E. Fish
CODEFORCES
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class C2 { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(new File("input.txt")); PrintWriter pw = new PrintWriter(new File("output.txt")); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int[]x = new int[k+1], y = new int[k+1]; for (int i = 1; i <= k; i++) { y[i] = sc.nextInt(); x[i] = sc.nextInt(); } int max = -1, y0 = 0, x0 = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int min = n+m+2; for (int j2 = 1; j2 <= k; j2++) { min = Math.min(min, Math.abs(i-y[j2])+Math.abs(j-x[j2])); } if (min > max) { max = min; y0 = i; x0 = j; } } } pw.println(y0+" "+x0); pw.close(); } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Map; import java.util.Map.Entry; import java.io.BufferedReader; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Liavontsi Brechka */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); F1BlokiRavnoiSummiProstayaRedakciya solver = new F1BlokiRavnoiSummiProstayaRedakciya(); solver.solve(1, in, out); out.close(); } static class F1BlokiRavnoiSummiProstayaRedakciya { InputReader in; Map<Long, List<F1BlokiRavnoiSummiProstayaRedakciya.Block>> sums; public void solve(int testNumber, InputReader in, PrintWriter out) { this.in = in; int n = ni(); long[] a = nla(n); sums = new HashMap<>(); for (int i = 0; i < n; i++) { long sum = 0; for (int j = i; j < n; j++) { sum += a[j]; sums.computeIfAbsent(sum, k -> new ArrayList<>()).add( new F1BlokiRavnoiSummiProstayaRedakciya.Block(i, j, sum)); } } for (Map.Entry<Long, List<F1BlokiRavnoiSummiProstayaRedakciya.Block>> e : sums.entrySet()) { Collections.sort(e.getValue()); } List<F1BlokiRavnoiSummiProstayaRedakciya.Block> res = Collections.emptyList(); for (Map.Entry<Long, List<F1BlokiRavnoiSummiProstayaRedakciya.Block>> e : sums.entrySet()) { List<F1BlokiRavnoiSummiProstayaRedakciya.Block> blocks = e.getValue(); List<F1BlokiRavnoiSummiProstayaRedakciya.Block> updated = new ArrayList<>(); for (F1BlokiRavnoiSummiProstayaRedakciya.Block next : blocks) { if (updated.size() == 0) updated.add(next); else { F1BlokiRavnoiSummiProstayaRedakciya.Block prev = updated.get(updated.size() - 1); if (next.l > prev.r) updated.add(next); } } if (updated.size() > res.size()) res = updated; } StringBuilder resS = new StringBuilder(); resS.append(res.size()).append('\n'); for (F1BlokiRavnoiSummiProstayaRedakciya.Block block : res) resS.append(block.l + 1).append(' ').append(block.r + 1).append('\n'); out.println(resS); } private long[] nla(int size) { return in.nextLongArray(size); } private int ni() { return in.nextInt(); } static class Block implements Comparable<F1BlokiRavnoiSummiProstayaRedakciya.Block> { int l; int r; long sum; public Block(int l, int r, long sum) { this.l = l; this.r = r; this.sum = sum; } public int compareTo(F1BlokiRavnoiSummiProstayaRedakciya.Block o) { int res = Integer.compare(r, o.r); if (res == 0) res = Integer.compare(l, o.l); return res; } } } static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public long[] nextLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; ++i) { array[i] = nextLong(); } return array; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FElongatedMatrix solver = new FElongatedMatrix(); solver.solve(1, in, out); out.close(); } } static class FElongatedMatrix { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int m = in.readInt(); int[][] mat = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mat[i][j] = in.readInt(); } } int[][] minDist = new int[n][n]; SequenceUtils.deepFill(minDist, (int) 1e9); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { minDist[i][j] = Math.min(minDist[i][j], Math.abs(mat[i][k] - mat[j][k])); } } } int[][] minDistBetweenHeadAndTail = new int[n][n]; SequenceUtils.deepFill(minDistBetweenHeadAndTail, (int) 1e9); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 1; k < m; k++) { minDistBetweenHeadAndTail[i][j] = Math.min(minDistBetweenHeadAndTail[i][j], Math.abs(mat[i][k] - mat[j][k - 1])); } } } Log2 log2 = new Log2(); BitOperator bo = new BitOperator(); int[][][] dp = new int[1 << n][n][n]; for (int i = 1; i < (1 << n); i++) { if (i == Integer.lowestOneBit(i)) { dp[i][log2.floorLog(i)][log2.floorLog(i)] = (int) 1e9; continue; } for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (bo.bitAt(i, j) == 0) { continue; } for (int t = 0; t < n; t++) { dp[i][j][k] = Math.max(dp[i][j][k], Math.min(dp[bo.setBit(i, j, false)][t][k], minDist[j][t])); } } } } int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ans = Math.max(ans, Math.min(dp[(1 << n) - 1][i][j], minDistBetweenHeadAndTail[j][i])); } } out.println(ans); } } static class SequenceUtils { public static void deepFill(Object array, int val) { if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof int[]) { int[] intArray = (int[]) array; Arrays.fill(intArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFill(obj, val); } } } } static class Log2 { public int floorLog(int x) { return 31 - Integer.numberOfLeadingZeros(x); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } 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; } } static class BitOperator { public int bitAt(int x, int i) { return (x >> i) & 1; } public int setBit(int x, int i, boolean v) { if (v) { x |= 1 << i; } else { x &= ~(1 << i); } return x; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.io.*; import java.util.*; public class Problem_A { public static void main(String[] args) { MyScanner scan = new MyScanner(); int n = scan.nextInt(); int[] elements = new int[n]; for (int i = 0; i < n; i++) elements[i] = scan.nextInt(); int x = 0; Arrays.sort(elements); while(n > 0) { x++; int[] temp = new int[n]; int j = 0; int size = n; int min = elements[0]; n--; for (int i = 1; i < size; i++) { if (elements[i]%min == 0) { n--; } else { temp[j++] = elements[i]; } } elements = temp; } out.println(x); out.close(); } public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static class MyScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; String next() { while (st == null || !st.hasMoreElements()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.IOException; import java.util.StringTokenizer; /* * @author Tnascimento */ public class MaeDosDragoes { // public static StringTokenizer tokenizer; // public static BufferedReader reader; public static PrintWriter saida = new PrintWriter(System.out, false); // public static String proximo() { // while (tokenizer == null || !tokenizer.hasMoreElements()) { // try { // tokenizer = new StringTokenizer(reader.readLine()); // } catch (RuntimeException e) { // e.printStackTrace(); // } // } // return tokenizer.nextToken(); // } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastScanner fastScanner = new FastScanner(); int proximoInt = fastScanner.nextInt(); double proximoDouble = fastScanner.nextInt(); long[] graph = new long[proximoInt]; for(Integer i = 0; i < proximoInt; i++) { for(Integer j =0; j < proximoInt; j++) { Integer val = fastScanner.nextInt(); if (val.equals(1) || i.equals(j)) { graph[i] |= 1L << j; } } } int szLeft = proximoInt/2; int szRight = proximoInt - szLeft; int[] dp = new int[1 << szLeft]; int maxMask = 1 << szLeft; for(int mask = 1; mask <maxMask; mask++) { int curMask = mask; for(int j = 0; j < szLeft; j++) { if (((1 << j) & mask) > 0) { curMask &= graph[j + szRight] >> szRight; dp[mask] = Math.max(dp[mask], dp[mask ^ (1 << j)]); } } if (mask == curMask) { dp[mask] = Math.max(dp[mask],Integer.bitCount(mask)); } } int ans = 0; int rmaxMask = 1 << szRight; for(int mask = 0; mask < rmaxMask; mask++) { int curMask = mask; int oMask = maxMask -1; for(int j = 0; j < szRight; j++) { if (((1 << j) & mask) > 0) { curMask &= (graph[j] & (rmaxMask-1)); oMask &= graph[j] >> szRight; } } if (curMask != mask) continue; ans = Math.max(ans, Integer.bitCount(mask) + dp[oMask]); } proximoDouble/=ans; saida.println(proximoDouble * proximoDouble * (ans * (ans-1))/2); saida.flush(); } }
np
839_E. Mother of Dragons
CODEFORCES
import java.io.*; import java.util.*; public class Solution { private static StringTokenizer st; private static int n; private static int k; private static boolean[][] graph; private static int[] dp; private static int maxCliqueSize; public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(reader.readLine()); n = Integer.parseInt(st.nextToken()); k = Integer.parseInt(st.nextToken()); graph = new boolean[n][n]; dp = new int[1 << (n / 2)]; for (int i = 0; i < n; ++i) { st = new StringTokenizer(reader.readLine()); for (int j = 0; j < n; ++j) graph[i][j] = st.nextToken().equals("1"); } reader.close(); /* fill dp for first subset */ int size1 = n / 2; int border = 1 << size1; for (int mask = 1; mask < border; ++mask) { /* check if mask is complete graph */ boolean isComplete = true; for (int i = 0; i < size1; ++i) { if (((mask >> i) & 1) == 0) continue; for (int j = i + 1; j < size1; ++j) { if (((mask >> j) & 1) == 0) continue; if (!graph[i][j]) { isComplete = false; break; } } if (!isComplete) break; } if (isComplete) dp[mask] = Integer.bitCount(mask); } for (int mask = 1; mask < border; ++mask) { for (int i = 0; i < size1; ++i) { if (((mask >> i) & 1) == 0) { dp[mask | (1 << i)] = Math.max(dp[mask | (1 << i)], dp[mask]); } } } /* process second subset */ maxCliqueSize = 1; int size2 = n - n /2; border = (1 << size2); for (int mask = 0; mask < border; ++mask) { boolean isComplete = true; for (int i = 0; i < size2; ++i) { if (((mask >> i) & 1) == 0) continue; for (int j = i + 1; j < size2; ++j) { if (((mask >> j) & 1) != 0 && !graph[i + size1][j + size1]) { isComplete = false; break; } } if (!isComplete) break; } if (!isComplete) continue; int mask1 = (1 << size1) - 1; for (int i = 0; i < size2; ++i) { if (((mask >> i) & 1) == 0) continue; for (int j = 0; j < size1; ++j) { if (!graph[j][i + size1] && ((mask1 >> j) & 1) != 0) mask1 ^= (1 << j); } } maxCliqueSize = Math.max(maxCliqueSize, dp[mask1] + Integer.bitCount(mask)); } // System.out.println(maxCliqueSize); double answer = (1.0 * k * k * (maxCliqueSize - 1) / (2 * maxCliqueSize)); System.out.printf("%.15f", answer); } }
np
839_E. Mother of Dragons
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;} public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;} public double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } // |----| /\ | | ----- | // | / / \ | | | | // |--/ /----\ |----| | | // | \ / \ | | | | // | \ / \ | | ----- ------- public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); int n=sc.i(); System.out.println("? "+1); int a=sc.i(); System.out.println("? "+(1+n/2)); int b=sc.i(); if(a==b) { System.out.println("! "+1); System.exit(0); } int inv=0; if(a>b) inv=1; int low=2; int high=n/2; int q=0; while(low<=high) { if(q==60) break; int mid=(low+high)/2; System.out.println("? "+mid); a=sc.i(); System.out.println("? "+(mid+n/2)); b=sc.i(); if(a==b) { System.out.println("! "+mid); System.exit(0); } else if(a<b) { if(inv==0) low=mid+1; else high=mid-1; } else { if(inv==0) high=mid-1; else low=mid+1; } q++; } System.out.println("! -1"); out.flush(); } }
logn
1019_B. The hat
CODEFORCES
import java.util.*; import java.io.*; import java.text.DecimalFormat; public class Main{ final long mod = (int)1e9+7, IINF = (long)1e19; final int MAX = (int)1e6+1, MX = (int)1e7+1, INF = (int)1e9; DecimalFormat df = new DecimalFormat("0.0000000000000"); FastReader in; PrintWriter out; static boolean multipleTC = false, memory = false; public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 26).start(); else new Main().run(); } void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); for(int i = 1, t = (multipleTC)?ni():1; i<=t; i++)solve(i); out.flush(); out.close(); } void solve(int TC) throws Exception{ long x = nl(), k = nl(); if(x==0)pn(0); else { x%=mod; long p = modPow(2,k); long b = mul((x-1+mod)%mod,p), e = mul(x,p); long ans = c(e)%mod; ans -= c(b)%mod; ans%=mod; if(ans<0)ans+=mod; ans = mul(ans, 2); ans = mul(ans, modPow(p, mod-2)); pn(ans); } } long modPow(long a, long p){ long o = 1; while(p>0){ if((p&1)==1)o = mul(a,o); a = mul(a,a); p>>=1; } return o; } long mul(long a, long b){ if(a>=mod)a%=mod; if(b>=mod)b%=mod; a*=b; if(a>=mod)a%=mod; return a; } long c(long c){ return (c*c+c)/2; } int[] reverse(int[] a){ int[] o = new int[a.length]; for(int i = 0; i< a.length; i++)o[i] = a[a.length-i-1]; return o; } int[] sort(int[] a){ if(a.length==1)return a; int mid = a.length/2; int[] b = sort(Arrays.copyOfRange(a,0,mid)), c = sort(Arrays.copyOfRange(a,mid,a.length)); for(int i = 0, j = 0, k = 0; i< a.length; i++){ if(j<b.length && k<c.length){ if(b[j]<c[k])a[i] = b[j++]; else a[i] = c[k++]; }else if(j<b.length)a[i] = b[j++]; else a[i] = c[k++]; } return a; } long[] sort(long[] a){ if(a.length==1)return a; int mid = a.length/2; long[] b = sort(Arrays.copyOfRange(a,0,mid)), c = sort(Arrays.copyOfRange(a,mid,a.length)); for(int i = 0, j = 0, k = 0; i< a.length; i++){ if(j<b.length && k<c.length){ if(b[j]<c[k])a[i] = b[j++]; else a[i] = c[k++]; }else if(j<b.length)a[i] = b[j++]; else a[i] = c[k++]; } return a; } int[] ia(int ind,int n){ int[] out = new int[ind+n]; for(int i = 0; i< n; i++)out[ind+i] = ni(); return out; } long[] la(int ind, int n){ long[] out = new long[ind+n]; for(int i = 0; i< n; i++)out[ind+i] = nl(); return out; } double[] da(int ind, int n){ double[] out = new double[ind+n]; for(int i = 0; i< n; i++)out[ind+i] = nd(); return out; } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n(){return in.next();} String nln(){return in.nextLine();} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ 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; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 9/16/11 * Time: 1:27 PM * To change this template use File | Settings | File Templates. */ import java.io.*; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.HashSet; import java.util.Queue; import java.util.StringTokenizer; public class TaskC extends Thread { public TaskC() { try { this.input = new BufferedReader(new FileReader("input.txt")); this.output = new PrintWriter("output.txt"); this.setPriority(Thread.MAX_PRIORITY); } catch (Throwable e) { System.exit(666); } } private void solve() throws Throwable { int n = nextInt(); int m = nextInt(); int k = nextInt(); Queue<Integer> qX = new ArrayDeque<Integer>(); Queue<Integer> qY = new ArrayDeque<Integer>(); boolean [][]was = new boolean[n][m]; for (int i = 0; i < k; ++i) { int x = nextInt() - 1, y = nextInt() - 1; qX.add(x); qY.add(y); was[x][y] = true; } int lastX = -1, lastY = -1; while (!qX.isEmpty()) { lastX = qX.poll(); lastY = qY.poll(); for (int i = 0; i < dx.length; ++i) { int nextX = lastX + dx[i], nextY = lastY + dy[i]; if (nextX < n && nextY < m && nextX >= 0 && nextY >= 0 && !was[nextX][nextY]) { qX.add(nextX); qY.add(nextY); was[nextX][nextY] = true; } } } ++lastX; ++lastY; output.println(lastX + " " + lastY); } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new TaskC().start(); } 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()); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } static final int PRIME = 3119; static final int[]dx = {1, -1, 0, 0}, dy = {0, 0, -1, 1}; private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.util.*; public class A { FastScanner in; PrintWriter out; void solve() { int tc = in.nextInt(); for (int t = 0; t < tc; t++) { int n = in.nextInt(); int m = in.nextInt(); O[] a = new O[n * m]; int[][] cols = new int[m][n + n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cols[j][i] = cols[j][i + n] = in.nextInt(); a[i * m + j] = new O(i, j, cols[j][i]); } } Arrays.sort(a); boolean[] used = new boolean[m]; int cntUsed = 0; for (O o : a) { if (!used[o.y]) { used[o.y] = true; cntUsed++; if (cntUsed == n) { break; } } } int[] dp = new int[1 << n]; int[] ndp = new int[1 << n]; int[] maxndp = new int[1 << n]; for (int col = 0; col < m; col++) { if (!used[col]) { continue; } int[] curColumn = cols[col]; for (int shift = 0; shift < n; shift++) { System.arraycopy(dp, 0, ndp, 0, ndp.length); for (int mask = 0; mask < 1 << n; mask++) { for (int bit = 0; bit < n; bit++) { if (((1 << bit) & mask) == 0) { int nmask = mask | (1 << bit); ndp[nmask] = Math.max(ndp[nmask], ndp[mask] + curColumn[bit + shift]); } } } for (int i = 0; i < ndp.length; i++) { maxndp[i] = Math.max(maxndp[i], ndp[i]); } } int[] tmp = dp; dp = maxndp; maxndp = tmp; } out.println(dp[dp.length - 1]); } } class O implements Comparable<O> { int x, y, value; public O(int x, int y, int value) { this.x = x; this.y = y; this.value = value; } @Override public int compareTo(O o) { return -Integer.compare(value, o.value); } } void run() { try { in = new FastScanner(new File("A.in")); out = new PrintWriter(new File("A.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new A().runIO(); } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.util.*; public class Main{ public static void main(String[]args){ for(Scanner cin=new Scanner(System.in);cin.hasNextLong();System.out.println(Math.max(0,(Long.highestOneBit(cin.nextLong()^cin.nextLong())<<1)-1))); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.util.*; import java.io.*; public class Solution{ public static long page(long p,long k){ return (p-1)/k; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); int m = sc.nextInt(); long k = sc.nextLong(); long[] p = new long[m]; long del = 0; long nb = 1; int op = 0; for(int i=0;i<m;i++) p[i] = sc.nextLong(); for(int i=1;i<m;i++){ if(page(p[i]-del,k)!=page(p[i-1]-del,k)){ del += nb; nb = 1; op++; }else{ nb++; } } if(nb!=0) op++; System.out.println(op); } }
linear
1191_C. Tokitsukaze and Discard Items
CODEFORCES
import java.util.*; public class A { static int [] reverse = new int [257]; public static void main (String [] arg) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int [] A =new int [n]; for (int i = 0; i<A.length; ++i) A[i] = sc.nextInt(); Arrays.sort(A); if (n == 1) { System.out.println( (A[0] == 1) ? "2" : "1"); return; } else if (A[0] == A[A.length-1] && A[0] == 1) { System.out.print("1"); for (int i = 1; i<n-1; ++i) System.out.print(" " + A[i]); System.out.println(" 2"); return; } else if (A[0] == A[A.length-1]) { System.out.print("1"); for (int i = 1; i<n; ++i) System.out.print(" " + A[i]); System.out.println(); return; } for (int i = 0; i<A.length; ++i) { int prev = (i == 0) ? Integer.MAX_VALUE : A[i-1]; int next = (i == A.length-1) ? Integer.MAX_VALUE : A[i+1]; int ans = Math.min(prev, Math.min(next, A[i])); if (i == 0) ans = 1; System.out.print((i == 0) ? "" + ans : " " + ans); } System.out.println(); } }
nlogn
135_A. Replacement
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class A { void run(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; boolean dif = false; for(int i=0;i<n;i++)a[i]=sc.nextInt(); Arrays.sort(a); if(n==1){ System.out.println(a[0]==1?2:1);return; } int[] m = new int[n]; for(int i=1;i<n;i++)if(a[i]!=a[i-1])dif=true; m[0] = 1; for(int i=1;i<n;i++)m[i]=a[i-1]; if(!dif&&a[0]==1)m[n-1]++; for(int i=0;i<n;i++)System.out.print(m[i]+(i==n-1?"\n":" ")); } public static void main(String[] args) { new A().run(); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.*; import java.util.*; public class C { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; C c = new C(filePath); } public C(String inputFile) { openInput(inputFile); readNextLine(); int N=NextInt(); boolean [] p = new boolean[N]; readNextLine(); int h=0; for(int i=0; i<N; i++) { p[i]=line.charAt(i)=='H'; if(p[i])h++; } int ret=N; for(int i=0; i<N; i++) { int m=0; for(int j=i; j<i+h; j++) { int n=j%N; if(!p[n])m++; } ret=Math.min(ret, m); } System.out.println(ret); closeInput(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.lang.Character.*; import static java.lang.Double.*; public class A { Scanner scan = new Scanner(System.in); void solve() { int n = scan.nextInt(); String[]A = new String[n]; String[]B = new String[n]; int res =0; for(int i=0;i<n;i++)A[i]=scan.next(); for(int i=0;i<n;i++)B[i]=scan.next(); for(int i=0;i<A.length;i++) { boolean fnd = false; for(int j=0;j<B.length;j++) { if(A[i].equals(B[j])) { fnd = true; B[j]=""; break; } } if(!fnd)res++; } System.out.println(res); } public static void main(String[] args) { new A().solve(); } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * Created with IntelliJ IDEA. * User: Alexey * Date: 16.09.12 * Time: 19:29 * To change this template use File | Settings | File Templates. */ public class stub implements Runnable { public static void main(String[] args) { new stub().run(); } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st; public String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private void solve() throws IOException { int[] cnt = new int[(int) 1e6]; int n = nextInt(); int k = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } int cur = 0; int left = 0; int i = left; while (i < n && cur != k) { if (cnt[a[i]] == 0) { cur++; } cnt[a[i]]++; i++; } i--; if (cur != k) { out.println("-1 -1"); return; } int right = i; while (cnt[a[left]] > 1) { cnt[a[left]]--; left++; } out.println((left + 1) + " " + (right + 1)); } public void run() { try { solve(); out.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } }
linear
224_B. Array
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[]parts = br.readLine().split("\\s+"); int n = Integer.parseInt(parts[0]); int a = Integer.parseInt(parts[1]); int b = Integer.parseInt(parts[2]); parts = br.readLine().split("\\s+"); int[]hard = new int[n]; for(int i = 0; i < n; i++){ hard[i] = Integer.parseInt(parts[i]); } Arrays.sort(hard); System.out.println(hard[b]-hard[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; public class Solution { class Q implements Comparable<Q> { int p, t; Q(int q, int w) { p = q; t = w; } @Override public int compareTo(Q arg0) { if (p == arg0.p) return t - arg0.t; return arg0.p - p; } } void solve() throws Exception { int n = nextInt(); int k = nextInt() - 1; Q[] a = new Q[n]; for (int i = 0; i < n; i++) a[i] = new Q(nextInt(), nextInt()); Arrays.sort(a); int ans = 1; for (int i = k - 1; i >= 0; i--) if (a[i].compareTo(a[k]) == 0) ans++; else break; for (int i = k + 1; i < n; i++) if (a[i].compareTo(a[k]) == 0) ans++; else break; 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); solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { out.close(); } } String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(nextToken()); } BufferedReader in; PrintWriter out; StringTokenizer st; }
nlogn
166_A. Rank List
CODEFORCES
import java.io.PrintStream; import java.util.Scanner; public class Cfbra { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintStream out = System.out; out.println(in.nextInt() / 2 * 3); } }
constant
84_A. Toy Army
CODEFORCES