src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.io.*; import java.util.*; public class CF1027D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] cc = new int[n]; for (int i = 0; i < n; i++) cc[i] = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] aa = new int[n]; for (int i = 0; i < n; i++) aa[i] = Integer.parseInt(st.nextToken()) - 1; int[] used = new int[n]; int ans = 0; for (int i = 0; i < n; i++) { if (used[i] == 2) continue; int j = i; while (used[j] == 0) { used[j] = 1; j = aa[j]; } if (used[j] == 1) { int c = cc[j]; while (used[j] == 1) { used[j] = 2; c = Math.min(c, cc[j]); j = aa[j]; } ans += c; } j = i; while (used[j] == 1) { used[j] = 2; j = aa[j]; } } System.out.println(ans); } }
linear
1027_D. Mouse Hunt
CODEFORCES
//package round43; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static String nextToken() throws IOException{ while (st==null || !st.hasMoreTokens()){ String s = bf.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } static int nextInt() throws IOException{ return Integer.parseInt(nextToken()); } static String nextStr() throws IOException{ return nextToken(); } static int f(byte s[], int n){ int l = 0, r = n-1; int res = 0; do{ while (l<n && s[l]=='H') l++; while (r>=0 && s[r]=='T') r--; if (l < r){ res++; } l++; r--; } while (l < r); return res; } public static void main(String[] args) throws IOException{ int n = nextInt(); byte s[] = nextStr().getBytes(); int res = f(s, n); for (int i=1; i<n; i++){ byte c = s[0]; for (int j=0; j<n-1; j++) s[j] = s[j+1]; s[n-1] = c; res = Math.min(res, f(s, n)); } out.println(res); out.flush(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.*; import java.util.*; public class CF387D { static class A { ArrayList<Integer> list = new ArrayList<>(); int u, v, d; } static int INF = Integer.MAX_VALUE; static boolean bfs(A[] aa, int n) { LinkedList<Integer> q = new LinkedList<>(); for (int u = 1; u <= n; u++) if (aa[u].v > 0) aa[u].d = INF; else { aa[u].d = 0; q.addLast(u); } aa[0].d = INF; while (!q.isEmpty()) { int u = q.removeFirst(); for (int v : aa[u].list) { int w = aa[v].u; if (aa[w].d == INF) { aa[w].d = aa[u].d + 1; if (w == 0) return true; q.addLast(w); } } } return false; } static boolean dfs(A[] aa, int n, int u) { if (u == 0) return true; for (int v : aa[u].list) { int w = aa[v].u; if (aa[w].d == aa[u].d + 1 && dfs(aa, n, w)) { aa[u].v = v; aa[v].u = u; return true; } } aa[u].d = INF; return false; } static int matchings(A[] aa, int n) { int cnt = 0; while (bfs(aa, n)) for (int u = 1; u <= n; u++) if (aa[u].v == 0 && dfs(aa, n, u)) cnt++; return cnt; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[] eu = new int[m]; int[] ev = new int[m]; for (int j = 0; j < m; j++) { st = new StringTokenizer(br.readLine()); eu[j] = Integer.parseInt(st.nextToken()); ev[j] = Integer.parseInt(st.nextToken()); } A[] aa = new A[n + 1]; int min = m + n * 3; for (int ctr = 1; ctr <= n; ctr++) { boolean loop = false; boolean[] ci = new boolean[n + 1]; boolean[] co = new boolean[n + 1]; for (int i = 0; i <= n; i++) aa[i] = new A(); int m_ = 0; for (int j = 0; j < m; j++) { int u = eu[j]; int v = ev[j]; if (u == ctr && v == ctr) loop = true; else if (u == ctr && v != ctr) ci[v] = true; else if (u != ctr && v == ctr) co[u] = true; else { aa[u].list.add(v); m_++; } } int cnt = loop ? 0 : 1; for (int i = 1; i <= n; i++) if (i != ctr) { if (!ci[i]) cnt++; if (!co[i]) cnt++; } int m2 = matchings(aa, n); cnt += (m_ - m2) + (n - 1 - m2); if (min > cnt) min = cnt; } System.out.println(min); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.HashMap; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintWriter; import java.io.OutputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int BAD = 11111; int rows; int cols; HashMap<IntIntPair, Integer>[] mem; boolean contains(int mem, int index) { if(index < 0) return false; return ((mem >> index) & 1) == 1; } int add(int mem, int index) { if(((mem >> index) & 1) == 0) { mem += (1 << index); } return mem; } int size(int mem) { int res = 0; while(mem > 0) { if(mem % 2 == 1) res++; mem /= 2; } return res; } void test() { if(contains(5, 0) == false) throw new RuntimeException(); if(contains(5, 1) == true) throw new RuntimeException(); if(contains(5, -1) == true) throw new RuntimeException(); if(contains(5, 2) == false) throw new RuntimeException(); if(contains(5, 3) == true) throw new RuntimeException(); if(add(0, 2) != 4) throw new RuntimeException(); if(add(4, 0) != 5) throw new RuntimeException(); if(add(5, 0) != 5) throw new RuntimeException(); if(size(5) != 2) throw new RuntimeException(); } int dp(int row, int remabove, int squareabove) { if(row == rows) { if(remabove == 0) return 0; return BAD; } if(mem[row].containsKey(new IntIntPair(remabove, squareabove))) return mem[row].get(new IntIntPair(remabove, squareabove)); int res = BAD; int possibilities = 1 << cols; for(int poss = 0; poss < possibilities; poss++) { int have = 0; for(int j = 0; j < cols; j++) if(((poss >> j) & 1) == 1) { have += 1 << j; } boolean works = true; for(int above = 0; above < cols; above++) if(((remabove >> above) & 1) == 1) { if(((have >> above) & 1) == 0) { works = false; break; } } if(works) { int remhere = 0; for(int j = 0; j < cols; j++) { if(!contains(have, j - 1) && !contains(have, j) && !contains(have, j + 1) && !contains(squareabove, j)) { remhere = add(remhere, j); } } res = Math.min(res, size(have) + dp(row + 1, remhere, have)); } } mem[row].put(new IntIntPair(remabove, squareabove), res); return res; } public void solve(int testNumber, InputReader in, OutputWriter out) { test(); int n = in.readInt(), m = in.readInt(); cols = Math.min(n, m); rows = Math.max(n, m); mem = new HashMap[rows]; for(int i = 0; i < mem.length; i++) mem[i] = new HashMap<>(); int res = dp(0, 0, 0); out.printLine(cols * rows - res); } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if(this == o) return true; if(o == null || getClass() != o.getClass()) return false; IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = Integer.hashCode(first); result = 31 * result + Integer.hashCode(second); return result; } public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings({"unchecked"}) public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if(value != 0) { return value; } return Integer.compare(second, o.second); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if(numChars == -1) throw new InputMismatchException(); if(curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch(IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if(c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while(!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if(filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } }
np
111_C. Petya and Spiders
CODEFORCES
/** * @author egaeus * @mail sebegaeusprogram@gmail.com * @veredict Accepted * @url <https://codeforces.com/problemset/problem/1238/E> * @category dp * @date 19/10/2019 **/ import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import static java.lang.Integer.bitCount; import static java.lang.Integer.parseInt; public class CF1238E { static long[][] Q; static int N; static int M; static long[] mem; static long[] sums; public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (String ln; (ln = in.readLine()) != null; ) { StringTokenizer st = new StringTokenizer(ln); N = parseInt(st.nextToken()); M = parseInt(st.nextToken()); char[] S = in.readLine().toCharArray(); Q = new long[M][M]; mem = new long[1 << M]; Arrays.fill(mem, -1); for (int i = 1; i < N; i++) Q[S[i - 1] - 'a'][S[i] - 'a'] = Q[S[i] - 'a'][S[i - 1] - 'a'] = Q[S[i - 1] - 'a'][S[i] - 'a'] + 1; calculateSums(); for (int i = (1 << M) - 1; i >= 0; i--) f(i); System.out.println(f(0)); } } static void calculateSums() { sums = new long[1 << M]; Arrays.fill(sums, -1); for (int u = 0; u < (1 << M); u++) { if (sums[u] == -1) { sums[u] = 0; for (int j = 0; j < M; j++) for (int k = j + 1; k < M; k++) if (((u & (1 << j)) == 0 && (u & (1 << k)) != 0) || ((u & (1 << j)) != 0 && (u & (1 << k)) == 0)) sums[u] += Q[j][k]; int neg = (~u) & ((1 << M) - 1); sums[neg] = sums[u]; } } } static long f(int u) { if (bitCount(u) == M) return 0; if (mem[u] >= 0) return mem[u]; long min = 10000000000L; for (int i = 0; i < M; i++) if ((u & (1 << i)) == 0) { u = u | (1 << i); min = Math.min(f(u) + sums[u], min); u = u ^ (1 << i); } return mem[u] = min; } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner t=new Scanner(System.in); long l=t.nextLong(); long r=t.nextLong(); if(r-l<2) System.out.println(-1); else if(r-l<3 && l%2!=0){ if(l%3!=0) System.out.println(-1); else if ((l+3)%2==0) System.out.println(-1); else System.out.println(l+" "+(l+1)+" "+(l+3)); } else{ while (l%2!=0) l++; System.out.println(l+" "+(l+1)+" "+(l+2)); } } }
constant
483_A. Counterexample
CODEFORCES
import java.util.*; import java.io.*; public class Waw{ public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long[] a = new long[n]; for(int i=0;i<n;i++) a[i] = sc.nextLong(); long[] p = new long[n]; p[n-1] = a[n-1]; for(int i=n-2;i>=0;i--){ if(a[i]<p[i+1]) p[i] = p[i+1]-1; else p[i] = a[i]; } long max = p[0]; long res = p[0] - a[0]; for(int i=1;i<n;i++){ if(max < p[i]) max = p[i]; res += max - a[i]; } System.out.println(res); } }
linear
924_C. Riverside Curio
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long n = scanner.nextLong(); long s = scanner.nextLong(); long l = 0, r = n + 1; while(r - l > 1) { long mid = (l + r) / 2; long k = mid, sum = 0; while(k != 0) { sum += k % 10; k /= 10; } if(mid - sum >= s) r = mid; else l = mid; } System.out.print(n - r + 1); } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Problem { public static void main(String[] arg){ FastScanner scan = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(); double ncr[][] = new double[n+1][n+1]; ncr[1][0] = ncr[0][1] = ncr[1][1] = 1.0; for(int i = 2; i <= n; i++){ for(int j = 0; j <= i; j++){ if(j == 0 || j == i) ncr[i][j] = 1.0; else ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; //System.out.print(ncr[i][j] + " "); } //System.out.println(); } double a[][] = new double[n+1][n+1]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) a[i][j] = scan.nextDouble(); double dp[] = new double[1<<19]; dp[(1<<n) - 1] = 1.0; for(int state = (1 << n) - 1; state >= 0; state--){ int len = 0; for(int i = 0; i < n; i++) if((state & (1 << i)) > 0) len++; for(int i = 0; i < n; i++){ if(((1 << i) & state) == 0) continue; for(int j = 0; j < i; j++){ if(((1 << j) & state) == 0) continue; dp[state & (~(1<<i))] += (dp[state] * a[j][i] / ncr[len][2]); dp[state & (~(1<<j))] += (dp[state] * a[i][j] / ncr[len][2]); //System.out.println(state + " / " + (state & (~(1<<i))) + " / " + dp[state] + " / " + a[j][i] + " / " + (dp[state] * a[j][i]) + " / " + dp[state & (~(1<<i))]); //System.out.println(state + " / " + (state & (~(1<<j))) + " / " + dp[state] + " / " + a[i][j] + " / " + (dp[state] * a[i][j]) + " / " + dp[state & (~(1<<j))]); //System.out.println(); } } } for(int i = 0; i < n; i++) System.out.print(String.format("%.6f", dp[1<<i]) + " "); out.close(); } public static long gcd(long a, long b){ if(b == 0) return a; if(a < b) return gcd(b, a); return gcd(b, a % b); } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream is) { try { br = new BufferedReader(new InputStreamReader(is)); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { return null; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.valueOf(next()); } } }
np
16_E. Fish
CODEFORCES
import java.util.*; public class Solution { public static void main(String[] args) { new Solution().calc(); } void calc() { Scanner cin = new Scanner(System.in); String s = cin.next(); int ret = 0; for (int i = 0; i < s.length(); i++) { for (int j = i + 1; j < s.length(); j++) { for (int k = 0; j + k < s.length(); k++) { if (s.charAt(i + k) != s.charAt(j + k)) break; ret = Math.max(k + 1, ret); } } } System.out.println(ret); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class AAA { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); int max = a[0]; int ind = 0; for (int k = 1; k < n; k++) { if (a[k] > max) { max = a[k]; ind = k; } } if (max != 1) { a[ind] = 1; Arrays.sort(a); for (int i = 0; i < a.length - 1; i++) System.out.print(a[i] + " "); System.out.println(a[a.length - 1]); } else { a[0] = 2; Arrays.sort(a); for (int i = 0; i < a.length - 1; i++) System.out.print(a[i] + " "); System.out.println(a[a.length - 1]); } } }
nlogn
135_A. Replacement
CODEFORCES
import static java.lang.Math.*; import static java.util.Arrays.*; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { Class<?> here = new Object(){}.getClass().getEnclosingClass(); try { String packageName = here.getPackage().getName(); packageName = "src/" + packageName.replaceAll("\\.", "/") + "/"; System.setIn(new FileInputStream(packageName + "input.txt")); // System.setOut(new PrintStream(new FileOutputStream(packageName + "output.txt"))); } catch (FileNotFoundException e) { } catch (NullPointerException e) { } Object o = Class.forName(here.getName()).newInstance(); o.getClass().getMethod("run").invoke(o); } static void tr(Object... os) { System.err.println(deepToString(os)); } MyScanner sc = null; PrintWriter out = null; public void run() throws Exception { sc = new MyScanner(System.in); out = new PrintWriter(System.out); for (;sc.hasNext();) { solve(); out.flush(); } out.close(); } void solve() { int n = sc.nextInt(); int k = sc.nextInt(); TreeSet<Integer> at = new TreeSet<Integer>(); for (int i = 0; i < n; i++) at.add(sc.nextInt()); Integer[] ai = at.toArray(new Integer[0]); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ai[i]; if (k == 1) { out.println(n); return; } boolean[] invalid = new boolean[n]; tr(a); int ans = 0; for (int i = 0, j = 0; i < n; i++) if (!invalid[i]) { ++ans; long kx = (long)k * a[i]; while (j < n && a[j] < kx) { j++; } if (j < n && kx == a[j]) { invalid[j] = true; } } out.println(ans); } void print(int[] a) { out.print(a[0]); for (int i = 1; i < a.length; i++) out.print(" " + a[i]); out.println(); } class MyScanner { String line; BufferedReader reader; StringTokenizer tokenizer; public MyScanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public void eat() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { line = reader.readLine(); if (line == null) { tokenizer = null; return; } tokenizer = new StringTokenizer(line); } catch (IOException e) { throw new RuntimeException(e); } } } public String next() { eat(); return tokenizer.nextToken(); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public boolean hasNext() { eat(); return (tokenizer != null && tokenizer.hasMoreElements()); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class cf337c { static long mod,n,m,k; public static void main(String[] args) { FastIO in = new FastIO(), out = in; n = in.nextLong(); m = in.nextLong(); k = in.nextLong(); mod = (long)1e9 + 9; long x = m - (n-n%k)/k * (k-1) - n%k; if(x < 0) x = 0; long ans = (pow(2,x+1)-2)*k + m-x*k; ans = ((ans%mod)+mod)%mod; out.println(ans); out.close(); } static long pow(long x, long p) { if(p == 0) return 1%mod; long ans = pow(x,p/2); ans = (ans*ans)%mod; if(p%2 == 1) ans = (ans*x)%mod; return ans; } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() { this(System.in,System.out); } public FastIO(InputStream in, OutputStream out) { super(new BufferedWriter(new OutputStreamWriter(out))); br = new BufferedReader(new InputStreamReader(in)); scanLine(); } public void scanLine() { try { st = new StringTokenizer(br.readLine().trim()); } catch(Exception e) { throw new RuntimeException(e.getMessage()); } } public int numTokens() { if(!st.hasMoreTokens()) { scanLine(); return numTokens(); } return st.countTokens(); } public String next() { if(!st.hasMoreTokens()) { scanLine(); return next(); } return st.nextToken(); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
logn
338_A. Quiz
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import java.text.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T =sc.nextInt(); int t =T/2; System.out.println(t*3); } }
constant
84_A. Toy Army
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class B_Round_371_Div1 { public static long MOD = 1000000007; static int c = 0; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); Scanner in = new Scanner(); int n = in.nextInt(); int minX = -1; int start = 1; int end = n; c = 0; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + mid + " 1 " + n + " " + n); System.out.flush(); int v = in.nextInt(); if (v == 2) { minX = mid; start = mid + 1; } else { end = mid - 1; } } //System.out.println("Minx " + minX); int maxX = -1; start = minX; end = n; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " 1 " + mid + " " + n); System.out.flush(); int v = in.nextInt(); if (v == 2) { maxX = mid; end = mid - 1; } else { start = mid + 1; } } // System.out.println("Maxx " + maxX); int minY = -1; start = 1; end = n; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + mid + " " + maxX + " " + n); System.out.flush(); int v = in.nextInt(); if (v == 2) { minY = mid; start = mid + 1; } else { end = mid - 1; } } // System.out.println("MinY " + minY); int maxY = -1; start = minY; end = n; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + minY + " " + maxX + " " + mid); System.out.flush(); int v = in.nextInt(); if (v == 2) { maxY = mid; end = mid - 1; } else { start = mid + 1; } } // System.out.println("MaxY " + maxY); int middleMinX = maxX; start = minX; end = maxX; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + minY + " " + mid + " " + maxY); System.out.flush(); int v = in.nextInt(); if (v == 1) { middleMinX = mid; end = mid - 1; } else { start = mid + 1; } } //System.out.println("MiddleMinX " + middleMinX); int middleMaxX = -1; start = middleMinX + 1; end = maxX; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + mid + " " + minY + " " + maxX + " " + maxY); System.out.flush(); int v = in.nextInt(); if (v == 1) { middleMaxX = mid; start = mid + 1; } else { end = mid - 1; } } // System.out.println("MiddleMaxX " + middleMaxX); if (middleMaxX == -1) { int middleMinY = -1; start = minY; end = maxY; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + minY + " " + maxX + " " + mid); System.out.flush(); int v = in.nextInt(); if (v == 1) { middleMinY = mid; end = mid - 1; } else { start = mid + 1; } } //System.out.println("MiddleMinY " + middleMinY); int middleMaxY = -1; start = middleMinY + 1; end = maxY; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + mid + " " + maxX + " " + maxY); System.out.flush(); int v = in.nextInt(); if (v == 1) { middleMaxY = mid; start = mid + 1; } else { end = mid - 1; } } //System.out.println("MiddleMaxY " + middleMaxY); if (minX == maxX) { System.out.println("! " + minX + " " + minY + " " + maxX + " " + middleMinY + " " + minX + " " + middleMaxY + " " + maxX + " " + maxY); System.out.flush(); } else { int[] a = calX(minX, maxX, minY, middleMinY, in); int[] b = calX(minX, maxX, middleMaxY, maxY, in); check(a); check(b); System.out.println("! " + a[0] + " " + minY + " " + a[1] + " " + middleMinY + " " + b[0] + " " + middleMaxY + " " + b[1] + " " + maxY); System.out.flush(); } } else if (minY == maxY) { System.out.println("! " + minX + " " + minY + " " + middleMinX + " " + maxY + " " + middleMaxX + " " + minY + " " + maxX + " " + maxY); System.out.flush(); } else { int[] a = calY(minX, middleMinX, minY, maxY, in); int[] b = calY(middleMaxX, maxX, minY, maxY, in); check(a); check(b); System.out.println("! " + minX + " " + a[0] + " " + middleMinX + " " + a[1] + " " + middleMaxX + " " + b[0] + " " + maxX + " " + b[1]); System.out.flush(); } } static void check(int[] v) { if (v[0] == -1 || v[1] == -1) { throw new NullPointerException(); } } static int increaseC(int c) { if (c == 200) { throw new NullPointerException(); } return c + 1; } public static int[] calY(int minX, int maxX, int minY, int maxY, Scanner in) { c = increaseC(c); System.out.println("? " + minX + " " + minY + " " + maxX + " " + (maxY - 1)); System.out.flush(); int v = in.nextInt(); c = increaseC(c); System.out.println("? " + minX + " " + (minY + 1) + " " + maxX + " " + maxY); System.out.flush(); int o = in.nextInt(); if (v == 1 && o == 1) { int a = -1; int start = minY; int end = maxY; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + minY + " " + maxX + " " + mid); System.out.flush(); if (in.nextInt() == 1) { a = mid; end = mid - 1; } else { start = mid + 1; } } int b = -1; start = minY; end = a; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + mid + " " + maxX + " " + a); System.out.flush(); if (in.nextInt() == 1) { b = mid; start = mid + 1; } else { end = mid - 1; } } return new int[]{b, a}; } else if (v == 1) { int a = -1; int start = minY; int end = maxY; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + minY + " " + maxX + " " + mid); System.out.flush(); if (in.nextInt() == 1) { a = mid; end = mid - 1; } else { start = mid + 1; } } return new int[]{minY, a}; } else if (o == 1) { int b = -1; int start = minY; int end = maxY; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + mid + " " + maxX + " " + maxY); System.out.flush(); if (in.nextInt() == 1) { b = mid; start = mid + 1; } else { end = mid - 1; } } return new int[]{b, maxY}; } else { return new int[]{minY, maxY}; } } public static int[] calX(int minX, int maxX, int minY, int maxY, Scanner in) { c = increaseC(c); System.out.println("? " + minX + " " + minY + " " + (maxX - 1) + " " + maxY); System.out.flush(); int v = in.nextInt(); c = increaseC(c); System.out.println("? " + (minX + 1) + " " + minY + " " + maxX + " " + maxY); System.out.flush(); int o = in.nextInt(); if (v == 1 && o == 1) { int a = -1; int start = minX; int end = maxX; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + minY + " " + mid + " " + maxY); System.out.flush(); if (in.nextInt() == 1) { a = mid; end = mid - 1; } else { start = mid + 1; } } int b = -1; start = minX; end = a; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + mid + " " + minY + " " + a + " " + maxY); System.out.flush(); if (in.nextInt() == 1) { b = mid; start = mid + 1; } else { end = mid - 1; } } return new int[]{b, a}; } else if (v == 1) { int a = -1; int start = minX; int end = maxX; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + minX + " " + minY + " " + mid + " " + maxY); System.out.flush(); if (in.nextInt() == 1) { a = mid; end = mid - 1; } else { start = mid + 1; } } return new int[]{minX, a}; } else if (o == 1) { int b = -1; int start = minX; int end = maxX; while (start <= end) { int mid = (start + end) >> 1; c = increaseC(c); System.out.println("? " + mid + " " + minY + " " + maxX + " " + maxY); System.out.flush(); if (in.nextInt() == 1) { b = mid; start = mid + 1; } else { end = mid - 1; } } return new int[]{b, maxX}; } else { return new int[]{minX, maxX}; } } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
logn
713_B. Searching Rectangles
CODEFORCES
import java.util.*; import java.io.*; public class cf5722{ public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(br.readLine()); long n=Long.parseLong(st.nextToken()); long k=Long.parseLong(st.nextToken()); long ans=((-3-(long)Math.sqrt(9+4*(1*2*(n+k))))/2); long ans1=((-3+(long)Math.sqrt(9+4*(1*2*(n+k))))/2); if(ans>0) System.out.println(n-ans); else{ System.out.println(n-ans1); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.*; import java.util.*; public class A { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, in, out); out.close(); } static class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int d = in.nextInt(); int a[] = new int[n]; int c[] = new int[2 * n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); c[2 * i] = a[i] - d; c[2 * i + 1] = a[i] + d; } Arrays.sort(c); int ans = 0; for (int i = 0; i < 2 * n; i++) { if (i != 0 && c[i] == c[i - 1]) continue; int mind = d + 1; for (int j = 0; j < n; j++) mind = Math.min(mind, Math.abs(a[j] - c[i])); if (mind == d) { ans += 1; } } out.println(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.*; import java.util.*; import java.util.regex.*; public class Main { static Scanner scan = new Scanner (System.in); static PrintStream out = System.out; static int n; static void solve () { System.out.println (0 + " " + 0 + " " + n); } public static void main (String[] args) { n = scan.nextInt(); solve (); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.Random; import java.util.StringJoiner; import java.util.StringTokenizer; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; public class Main { static int T; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); T = sc.nextInt(); PrintWriter pw = new PrintWriter(System.out); for (int i = 0; i < T; i++) { int n = sc.nextInt(); int[] a = sc.nextIntArray(n); int[] ans = solve(n, a); StringJoiner j = new StringJoiner(" "); for (int each : ans) { j.add(String.valueOf(each)); } pw.println(j.toString()); } pw.flush(); } static int[] solve(int N, int[] A) { // a/b が1に近いものを探す shuffle(A); Arrays.sort(A); int cur = A[0]; int time = 1; double r = 0; int prev = -1; int a = -1; int b = -1; for (int i = 1; i < N; i++) { if( cur == A[i] ) { time++; if( time == 2 ) { if( prev != -1 ) { double r1 = (double)prev/cur; if( r1 > r ) { r = r1; a = prev; b = cur; } } prev = cur; } if( time == 4 ) { return new int[]{cur, cur, cur, cur}; } } else { time = 1; cur = A[i]; } } return new int[]{a, a, b, b}; } static void shuffle(int[] a) { Random r = ThreadLocalRandom.current(); for (int i = a.length-1; i >= 0; i--) { int j = r.nextInt(i+1); int t = a[i]; a[i] = a[j]; a[j] = t; } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
nlogn
1027_C. Minimum Value Rectangle
CODEFORCES
import java.io.*; import java.util.*; public class C implements Runnable{ public static void main (String[] args) {new Thread(null, new C(), "_cf", 1 << 28).start();} long MOD = (long)1e9+7; public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println("Go!"); long x = fs.nextLong(); long k = fs.nextLong(); if(x == 0) { System.out.println(0); return; } if(k == 0) { System.out.println(mult(x, 2)); return; } long max = mult(x, power(2, k, MOD)); long min = sub(max, power(2, k, MOD)); long total = 0; if(min <= max) { total = sub(summ(max), summ(min)); } else { total = summ(max); total = add(total, sub(summ(MOD-1), summ(min))); } total = mult(total, 2); total = div(total, power(2, k, MOD)); out.println(total); out.close(); } long summ(long x) { x *= x+1; x /= 2; x %= MOD; return x; } long add(long a, long b) { a %= MOD; b %= MOD; a += b; a %= MOD; return a; } long sub(long a, long b) { a %= MOD; b %= MOD; a -= b; while(a < 0) a += MOD; a %= MOD; return a; } long mult(long a, long b) { a %= MOD; b %= MOD; a *= b; a %= MOD; return a; } long div(long a, long b) { a %= MOD; b %= MOD; a *= inv(b); a %= MOD; return a; } long inv(long x) { long res = power(x, MOD-2, MOD); while(res < 0) res += MOD; res %= MOD; return res; } long power (long x, long y, long m) { long res = 1; x %= m; while(y > 0) { if(y % 2 == 1) { res = (res * x) % m; } y >>= 1L; x = (x * x) % m; } return res; } void sort (int[] a) { int n = a.length; for(int i = 0; i < 50; i++) { Random r = new Random(); int x = r.nextInt(n), y = r.nextInt(n); int temp = a[x]; a[x] = a[y]; a[y] = temp; } Arrays.sort(a); } class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class A { public static void main(String[] args) { Scanner s = new Scanner(System.in); int N = s.nextInt(); int K = s.nextInt(); int[] primes = getPrimesFast(N); Set<Integer> ints = new HashSet<Integer>(); for(int i=0;i<primes.length;i++) { ints.add(primes[i]); } for(int i=1;i<primes.length;i++) { ints.remove(primes[i] + primes[i-1]+1); } boolean res = primes.length - ints.size() >= K; System.out.print(res?"YES":"NO"); } public static int[] getPrimesFast(int n) { if (n <= 1) { return new int[0]; } boolean[] b = new boolean[n + 1]; int m = n - 1; for (int i = 2; i * i <= n; i++) { if (!b[i]) { for (int j = i + i; j <= n; j += i) { if (!b[j]) { m--; b[j] = true; } } } } int[] primes = new int[m]; int j = 0; for (int i = 2; i <= n; i++) { if (!b[i]) { primes[j++] = i; } } return primes; } }
linear
17_A. Noldbach problem
CODEFORCES
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; import java.math.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); int[] A=new int[n]; String[] s=br.readLine().split(" "); for(int i=0;i<n;i++){ A[i]=Integer.parseInt(s[i]); } Map memo=new HashMap(); int[] f=new int[n]; for(int i=0;i<n;i++){ if(!memo.containsKey(A[i])){ memo.put(A[i],1); } else{ int ct=(int)memo.get(A[i]); memo.put(A[i],ct+1); } int tot=0; if(memo.containsKey(A[i]-1)){ tot+=(int)memo.get(A[i]-1); } if(memo.containsKey(A[i]+1)){ tot+=(int)memo.get(A[i]+1); } tot+=(int)memo.get(A[i]); f[i]=tot; } BigInteger res=new BigInteger("0"); for(int i=0;i<n;i++){ int tot1=i+1-f[i]; int tot2=0; if(memo.containsKey(A[i]-1)){ tot2+=(int)memo.get(A[i]-1); } if(memo.containsKey(A[i]+1)){ tot2+=(int)memo.get(A[i]+1); } tot2+=(int)memo.get(A[i]); tot2=n-i-1-(tot2-f[i]); //res+=(long)(tot1-tot2)*(long)A[i]; res=res.add(BigInteger.valueOf((long)(tot1-tot2)*(long)A[i])); } System.out.println(res); } }
nlogn
903_D. Almost Difference
CODEFORCES
import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.io.BufferedReader; import java.util.List; import java.util.Map; import java.math.BigInteger; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author shu_mj @ http://shu-mj.com */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { Scanner in; PrintWriter out; public void solve(int testNumber, Scanner in, PrintWriter out) { this.in = in; this.out = out; run(); } void run() { int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int[] is = in.nextIntArray(n); Map<Integer, Integer> id = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { id.put(is[i], i); } SCC.V[] vs = new SCC.V[n * 2]; for (int i = 0; i < vs.length; i++) vs[i] = new SCC.V(); for (int i = 0; i < n; i++) { if (id.containsKey(a - is[i])) { int j = id.get(a - is[i]); vs[i].add(vs[j]); vs[j + n].add(vs[i + n]); } else { vs[i].add(vs[i + n]); } if (id.containsKey(b - is[i])) { int j = id.get(b - is[i]); vs[i + n].add(vs[j + n]); vs[j].add(vs[i]); } else { vs[i + n].add(vs[i]); } } SCC.scc(vs); for (int i = 0; i < n; i++) { if (vs[i].comp == vs[i + n].comp) { out.println("NO"); return ; } } out.println("YES"); for (int i = 0; i < n; i++) { if (vs[i].comp > vs[i + n].comp) { out.print("0 "); } else { out.print("1 "); } } out.println(); } } class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String s) { st = new StringTokenizer(s); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] nextIntArray(int n) { int[] is = new int[n]; for (int i = 0; i < n; i++) { is[i] = nextInt(); } return is; } } class SCC { public static int n; public static V[] us; public static int scc(V[] vs) { n = vs.length; us = new V[n]; for (V v : vs) if (!v.visit) dfs(v); for (V v : vs) v.visit = false; for (V u : us) if (!u.visit) dfsRev(u, n++); return n; } public static void dfs(V v) { v.visit = true; for (V u : v.fs) if (!u.visit) dfs(u); us[--n] = v; } public static void dfsRev(V v, int k) { v.visit = true; for (V u : v.rs) if (!u.visit) dfsRev(u, k); v.comp = k; } public static class V { public boolean visit; public int comp; public List<V> fs = new ArrayList<V>(); public List<V> rs = new ArrayList<V>(); public void add(V u) { fs.add(u); u.rs.add(this); } } }
linear
468_B. Two Sets
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author caoash */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); BObtainingTheString solver = new BObtainingTheString(); solver.solve(1, in, out); out.close(); } static class BObtainingTheString { public void solve(int testNumber, FastScanner br, PrintWriter pw) { int n = br.nextInt(); String s = br.nextString(); String t = br.nextString(); char[] sarr = new char[n]; char[] tarr = new char[n]; int[] sAppear = new int[26]; int[] tAppear = new int[26]; for (int i = 0; i < s.length(); i++) { sarr[i] = s.charAt(i); tarr[i] = t.charAt(i); sAppear[s.charAt(i) - 'a']++; tAppear[t.charAt(i) - 'a']++; } for (int i = 0; i < 26; i++) { if (sAppear[i] != tAppear[i]) { pw.println(-1); pw.close(); } } ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { char curr = tarr[i]; for (int j = i + 1; j < n; j++) { if (sarr[j] == curr) { for (int k = j; k > i; k--) { ans.add(k); char temp = sarr[k - 1]; sarr[k - 1] = sarr[k]; sarr[k] = temp; } break; } } } pw.println(ans.size()); for (int e : ans) { pw.print(e + " "); } pw.close(); } } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastScanner.SpaceCharFilter filter; public FastScanner(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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); } } }
quadratic
1015_B. Obtaining the String
CODEFORCES
import java.io.*; import java.util.*; public class test { public static void main(String[] args) { new test().run(); } PrintWriter out = null; void run() { Scanner in = new Scanner(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int[] h = new int[n]; for (int i = 0; i < n; i++) h[i] = in.nextInt(); Arrays.sort(h); if (h[b] == h[b - 1]) out.println(0); else out.println(h[b] - h[b - 1]); out.close(); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.Collection; import java.io.FileWriter; import java.io.IOException; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.Objects; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Queue; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Nafiur Rahman Khadem Shafin 🙂 */ 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); ProblemCFireAgain solver = new ProblemCFireAgain (); solver.solve (1, in, out); out.close (); } static class ProblemCFireAgain { private static final byte[] dx = {-1, 0, 0, 1}; private static final byte[] dy = {0, -1, 1, 0}; private static int[][] lvl; private static int max; private static int n; private static int m; private static int k; private static ProblemCFireAgain.Pair[] bgn; private static ProblemCFireAgain.Pair res; private static void bfs2d () { Queue<ProblemCFireAgain.Pair> bfsq = new LinkedList<ProblemCFireAgain.Pair> (); for (ProblemCFireAgain.Pair src : bgn) { lvl[src.a][src.b] = 0; bfsq.add (src); } while (!bfsq.isEmpty ()) { ProblemCFireAgain.Pair op = bfsq.poll (); int plvl = lvl[op.a][op.b]; // System.out.println ("ber hoise "+op+" "+plvl); if (plvl>max) { res = op; max = plvl; } for (int i = 0; i<4; i++) { int newX = op.a+dx[i]; int newY = op.b+dy[i]; // System.out.println (newX+" "+newY+" "+n+" "+m); if (newX>0 && newX<=n && newY>0 && newY<=m && lvl[newX][newY] == -1) { bfsq.add (new ProblemCFireAgain.Pair (newX, newY)); lvl[newX][newY] = (plvl+1); // System.out.println ("dhukse "+newX+" "+newY); } } } } public void solve (int testNumber, InputReader _in, PrintWriter _out) { /* * file input-output 😮. Multi source bfs. Same as snackdown problem. * */ try (InputReader in = new InputReader (new FileInputStream ("input.txt")); PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter ("output.txt")))) { n = in.nextInt (); m = in.nextInt (); k = in.nextInt (); bgn = new ProblemCFireAgain.Pair[k]; for (int i = 0; i<k; i++) { bgn[i] = new ProblemCFireAgain.Pair (in.nextInt (), in.nextInt ()); } max = Integer.MIN_VALUE; lvl = new int[n+5][m+5]; for (int i = 0; i<n+4; i++) { Arrays.fill (lvl[i], -1); } bfs2d (); // System.out.println (max); out.println (res); } catch (Exception e) { // e.printStackTrace (); } } private static class Pair { int a; int b; Pair (int a, int b) { this.a = a; this.b = b; } public String toString () { return a+" "+b; } public boolean equals (Object o) { if (this == o) return true; if (!(o instanceof ProblemCFireAgain.Pair)) return false; ProblemCFireAgain.Pair pair = (ProblemCFireAgain.Pair) o; return a == pair.a && b == pair.b; } public int hashCode () { return Objects.hash (a, b); } } } static class InputReader implements AutoCloseable { 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 { String str; if ((str = reader.readLine ()) != null) tokenizer = new StringTokenizer (str); else return null;//to detect eof } catch (IOException e) { throw new RuntimeException (e); } } return tokenizer.nextToken (); } public int nextInt () { return Integer.parseInt (next ()); } public void close () throws Exception { reader.close (); } } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { long k; private void solve() throws IOException { long n = nl(); k = nl(); if (n == 1) { prln(0); return; } if (n <= k) { prln(1); return; } long l = 1, r = k - 1; long mid = (l + r + 1) / 2; long old = -1; while (old != mid) { old = mid; if (take(mid) >= n) r = mid; if (take(mid) < n) l = mid; mid = (l + r + 1) / 2; } if (mid >= k || mid <= 0) { prln(-1); return; } if (take(mid) == n) { prln(mid); return; } if (mid == k - 1) prln(-1); else if (take(mid) < n) prln(mid + 1); else prln(mid); } long take(long t) { return k * t - t * (t - 1) / 2 - (t - 1); } public static void main(String[] args) { new Main().run(); } public void run() { try { if (isFileIO) { pw = new PrintWriter(new File("output.out")); br = new BufferedReader(new FileReader("input.in")); } else { pw = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); } solve(); pw.close(); br.close(); } catch (IOException e) { System.err.println("IO Error"); } } private int[] nia(int n) throws IOException { int arr[] = new int[n]; for (int i = 0; i < n; ++i) arr[i] = Integer.parseInt(nextToken()); return arr; } private int[] niam1(int n) throws IOException { int arr[] = new int[n]; for (int i = 0; i < n; ++i) arr[i] = Integer.parseInt(nextToken()) - 1; return arr; } private long[] nla(int n) throws IOException { long arr[] = new long[n]; for (int i = 0; i < n; ++i) arr[i] = Long.parseLong(nextToken()); return arr; } private void pr(Object o) { pw.print(o); } private void prln(Object o) { pw.println(o); } private void prln() { pw.println(); } int ni() throws IOException { return Integer.parseInt(nextToken()); } long nl() throws IOException { return Long.parseLong(nextToken()); } double nd() throws IOException { return Double.parseDouble(nextToken()); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(br.readLine()); } return tokenizer.nextToken(); } // private void qsort(int a[]) { // Random rand = new Random(271828182l); // qsort(a, 0, a.length, rand); // } // // private void qsort(int a[], int l, int r, Random rand) { // if (r - l <= 1) // return; // // if (r - l == 2) { // if (a[r - 1] < a[l]) { // int t = a[r - 1]; // a[r - 1] = a[l]; // a[l] = t; // } // // return; // } // // int x = a[rand.nextInt(r - l) + l]; // int i = l, j = r - 1; // while (i < j) { // while (a[i] < x) // ++i; // while (a[j] > x) // --j; // if (i < j) { // int t = a[i]; // a[i] = a[j]; // a[j] = t; // ++i; // --j; // } // } // // qsort(a, l, j + 1, rand); // qsort(a, i, r, rand); // } private BufferedReader br; private StringTokenizer tokenizer; private PrintWriter pw; private final boolean isFileIO = false; }
logn
287_B. Pipeline
CODEFORCES
import java.text.DecimalFormat; import java.util.Scanner; public class A { public static void main(String[] args){ try{ Scanner scanner = new Scanner(System.in); String in = scanner.next(); int max = 0; for(int j=0;j<in.length()-1;j++){ for(int i=j;i<in.length();i++){ if(in.indexOf(in.substring(j, i)) != in.lastIndexOf(in.substring(j, i)) && (i-j)>max){ max = i-j; } } } System.out.println(max); }catch(Exception e){ e.printStackTrace(); } } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class ElevatorOrStairs { private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static final OutputStreamWriter writer = new OutputStreamWriter(System.out); public static void main(String...strings) throws Exception { String[] specs = reader.readLine().split(" "); int x = Integer.parseInt(specs[0]); int y = Integer.parseInt(specs[1]); int z = Integer.parseInt(specs[2]); int t1 = Integer.parseInt(specs[3]); int t2 = Integer.parseInt(specs[4]); int t3 = Integer.parseInt(specs[5]); reader.close(); String ans = solve(x, y, z, t1, t2, t3); writer.append(ans); writer.flush(); writer.close(); } private static String solve(int x, int y, int z, int t1, int t2, int t3) { int time_using_stairs = Math.abs(x - y) * t1; int elevator_time_between_floor = Math.abs(x - z) * t2; int elevator_from_z_to_x = elevator_time_between_floor + 2*t3; int time_using_elevator = elevator_from_z_to_x + (Math.abs(x - y) * t2) + t3; if(time_using_elevator <= time_using_stairs) { return "YES"; } return "NO"; } }
constant
1054_A. Elevator or Stairs?
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException{ Scanner cin = new Scanner(System.in); int t, n, m; t = cin.nextInt(); while(t > 0) { t--; int sum = 0; n = cin.nextInt(); m = cin.nextInt(); while(n > 0 && m > 0) { if(n < m) { int k = n; n = m; m = k; } sum += n / m; n %= m; } System.out.println(sum); } } }
constant
267_A. Subtractions
CODEFORCES
import java.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 D { static long[][][] dp; static int[][] hor, ver; static int n, m; static int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; public static boolean isValid (int row, int col) { return row >= 0 && col >= 0 && row < n && col < m; } public static void minCost (int row, int col, int k) { if (k == 0) return; if (k == 2) { long min = Long.MAX_VALUE; for (int i = 0; i < 4; i++) { if (isValid(row + dir[i][0], col + dir[i][1])) { if ((row + dir[i][0]) == row) { if ((col + dir[i][1]) > col) { min = Math.min(min, hor[row][col]); } else { min = Math.min(min, hor[row][col - 1]); } } else { if ((row + dir[i][0]) > row) { min = Math.min(min, ver[row][col]); } else { min = Math.min(min, ver[row - 1][col]); } } } } dp[row][col][k] = 2 * min; return; } if (dp[row][col][k] != Long.MAX_VALUE) return; long min = Long.MAX_VALUE; for (int i = 0; i < 4; i++) { if (isValid(row + dir[i][0], col + dir[i][1])) { if (k >= 4) { minCost(row + dir[i][0], col + dir[i][1], k - 2); int edge = 0; if ((row + dir[i][0]) == row) { if ((col + dir[i][1]) > col) { edge = hor[row][col]; } else { edge = hor[row][col - 1]; } } else { if ((row + dir[i][0]) > row) { edge = ver[row][col]; } else { edge = ver[row - 1][col]; } } min = Math.min(min, 2 * edge + dp[row + dir[i][0]][col + dir[i][1]][k - 2]); } } } dp[row][col][k] = min; } public static void main(String[] args) { Scanner input = new Scanner(System.in); n = input.nextInt(); m = input.nextInt(); int k = input.nextInt(); hor = new int[n][m - 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { hor[i][j] = input.nextInt(); } } ver = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { ver[i][j] = input.nextInt(); } } if (k % 2 != 0) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(-1 + " "); } System.out.println(""); } } else { dp = new long[n][m][k + 1]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) for (int x = 0; x <= k; x++) { dp[i][j][x] = Long.MAX_VALUE; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { minCost(i, j, k); System.out.print(dp[i][j][k] + " "); } System.out.println(""); } } input.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int N = in.nextInt(); if (N % 2 == 0){ out.println("4 " + (N - 4)); } else { out.println("9 " + (N - 9)); } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class E implements Runnable { public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();} int n, m; char[] str; int[][] occs, cost; int[] dp; public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println(""); n = fs.nextInt(); m = fs.nextInt(); str = fs.next().toCharArray(); occs = new int[m][m]; for(int i = 0; i < n-1; i++) { occs[str[i]-'a'][str[i+1]-'a']++; occs[str[i+1]-'a'][str[i]-'a']++; } //cost[mask][v] = numPairs with v for some all bits on in mask int all = (1<<m)-1; cost = new int[m][1<<m]; for(int i = 0; i < m; i++) { for(int mask = 1; mask < all; mask++) { if(((1<<i)&mask) > 0) continue; int lb = mask & (-mask); int trail = Integer.numberOfTrailingZeros(lb); int nmask = mask ^ lb; cost[i][mask] = cost[i][nmask]+occs[i][trail]; } } dp = new int[1<<m]; Arrays.fill(dp, -1); System.out.println(solve(0)); out.close(); } int oo = (int)1e9; int solve(int mask) { if(mask == (1<<m)-1) return 0; if(dp[mask] != -1) return dp[mask]; int res = oo; int addOn = 0; for(int nxt = 0; nxt < m; nxt++) { if(((1<<nxt)&mask) > 0) continue; addOn += cost[nxt][mask]; } for(int nxt = 0; nxt < m; nxt++) { if(((1<<nxt)&mask) > 0) continue; int ret = addOn+solve(mask | (1<<nxt)); res = Math.min(res, ret); } return dp[mask] = res; } class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.io.*; import java.util.*; public class ProblemD { InputReader in; PrintWriter out; void solve() { long l = in.nextLong(); long r = in.nextLong(); long ans = 0; boolean add = false; for (int k = 62; k >= 0; k--) { long cb = (1L << k); if ((l & cb) != (r & cb)) add = true; if (add) ans += (1L << k); } out.println(ans); } ProblemD(){ boolean oj = System.getProperty("ONLINE_JUDGE") != null; try { if (oj) { in = new InputReader(System.in); out = new PrintWriter(System.out); } else { Writer w = new FileWriter("output.txt"); in = new InputReader(new FileReader("input.txt")); out = new PrintWriter(w); } } catch(Exception e) { throw new RuntimeException(e); } solve(); out.close(); } public static void main(String[] args){ new ProblemD(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public InputReader(FileReader fr) { reader = new BufferedReader(fr); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Problem220A { static int[] numbers; static int[] numbersCopy; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int i = Integer.parseInt(in.readLine()); numbers = new int[i]; numbersCopy = new int[i]; StringTokenizer stringTokenizer = new StringTokenizer(in.readLine()); int numOutOfPlace = 0; for (int j = 0; j < i; j++) { numbers[j] = Integer.parseInt(stringTokenizer.nextToken()); numbersCopy[j] = numbers[j]; } Arrays.sort(numbers); for (int j = 0; j < i; j++) { if (numbers[j] != numbersCopy[j]) { numOutOfPlace++; if (numOutOfPlace > 2) { break; } } } if (numOutOfPlace == 0 || numOutOfPlace == 2) { System.out.println("YES"); } else { System.out.println("NO"); } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.*; import java.io.*; public class a { public static void main(String[] args) throws IOException { input.init(System.in); int n = input.nextInt(), k = input.nextInt(); TreeSet<Integer> ts = new TreeSet<Integer>(); int[] data = new int[n]; for(int i = 0; i<n; i++) { data[i] = input.nextInt(); } Arrays.sort(data); if(n>1 && k==1.*data[n-1]/data[0]) System.out.println(n-1); else { for(int i = 0; i<n; i++) { if(data[i]%k != 0) ts.add(data[i]); else { if(!ts.contains(data[i]/k)) ts.add(data[i]); } } System.out.println(ts.size()); } } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class A { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; public void solve() throws IOException { long A = nextLong(); long B = nextLong(); long ans = 0; while(A > 0){ if(A >= B){ ans += A/B; A %= B; if(A == 0) break; } else{ long tmp = A; A = B; B = tmp; } } out.println(ans); } /** * @param args */ public static void main(String[] args) { new A().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(); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * * * 3 2 3 5 * -2 -1 4 -1 2 7 3 * * 10 1 -10617 30886 -7223 -63085 47793 -61665 -14614 60492 16649 -58579 3 8 1 * 10 4 7 1 7 3 7 * * 22862 -34877 * * @author pttrung */ public class C_Round_35_Div2 { public static long MOD = 1000000007; static int[] X = {0, 1, 0, -1}; static int[] Y = {1, 0, -1, 0}; static int[][][] dp; public static void main(String[] args) throws FileNotFoundException { PrintWriter out = new PrintWriter(new FileOutputStream(new File( "output.txt"))); //PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[][] map = new int[n][m]; LinkedList<Point> q = new LinkedList(); int reX = -1; int reY = -1; for (int i = 0; i < k; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; reX = x; reY = y; map[x][y] = 1; q.add(new Point(x, y)); } while (!q.isEmpty()) { Point p = q.poll(); // System.out.println(map[p.x][p.y] + " " + p.x + " " + p.y); for (int i = 0; i < 4; i++) { int x = p.x + X[i]; int y = p.y + Y[i]; if (x >= 0 && y >= 0 && x < n && y < m && map[x][y] == 0) { map[x][y] = 1 + map[p.x][p.y]; if (map[x][y] > map[reX][reY]) { reX = x; reY = y; } q.add(new Point(x, y)); } } } out.println((reX + 1) + " " + (reY + 1)); out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); // br = new BufferedReader(new InputStreamReader(System.in)); br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task task = new Task(); task.solve(in, out); out.close(); } static class Rectangle { int x1, y1; int x2, y2; } static class Task { /** * BEFORE SUBMITTING!!! * MAKE SURE IT IS RIGHT!!!!! * LONG!! * Check if m,n aren't misused * Make sure the output format is right (YES/NO vs Yes/No, newlines vs spaces) * Run with n = 1 or n = 0 * Make sure two ints aren't multiplied to get a long * */ public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); //ideas: procurar linha que os divide e procurar dentro desses sub-retangulos // procurar até ser 1 //corner cases: se procurar até ser 1 e não verificar se tem 1 do outro lado posso chegar a 1,2...not good // tenho que procurar 1,1 int l = 1; int r = n; int ans = 0; while(r >= l) { int mid = (r + l) / 2; if(ask(in,out,1,1,mid, n) == 0) { l = mid + 1; } else { ans = mid; r = mid - 1; } } //par 1,1 //FDS ISTO if(ans < n && ask(in,out,ans + 1, 1,n,n) == 1) { Rectangle r1 = find(in,out,1,1,ans,n,n); Rectangle r2 = find(in,out,ans + 1,1,n,n,n); System.out.printf("! %d %d %d %d %d %d %d %d\n", r1.x1, r1.y1, r1.x2, r1.y2, r2.x1, r2.y1, r2.x2, r2.y2); } else { l = 1; r = n; ans = 0; while(r >= l) { int mid = (r + l) / 2; if(ask(in,out,1,1,n, mid) == 0) { l = mid + 1; } else { ans = mid; r = mid - 1; } } Rectangle r1 = find(in,out,1,1,n,ans,n); Rectangle r2 = find(in,out,1,ans + 1,n,n,n); System.out.printf("! %d %d %d %d %d %d %d %d\n", r1.x1, r1.y1, r1.x2, r1.y2, r2.x1, r2.y1, r2.x2, r2.y2); } } //HASDFDSJGHDFJKSGDFJSGJDFSGJDSFGJF //FKING WORK public Rectangle find(InputReader in, PrintWriter out,int x1, int y1, int x2, int y2, int n) { Rectangle rec = new Rectangle(); int ansx1 = x1; int ansx2 = x2; int ansy1 = y1; int ansy2 = y2; int l = x1; int r = x2; // quero o minimo v >= x2 while(r >= l) { int mid = (r + l) / 2; if(ask(in,out,x1,y1,mid,y2) == 1) { ansx2 = mid; r = mid - 1; } else { l = mid + 1; } } //out.printf("x2 = %d", ansx2); r = x2; l = x1; // quero o maximo v <= x1 while(r >= l) { int mid = (r + l) / 2; if(ask(in,out,mid,y1,x2,y2) == 1) { ansx1 = mid; l = mid + 1; } else { r = mid - 1; } } //out.printf("x1 = %d", ansx1); l = y1; r = y2; // quero o minimo v >= y2 while(r >= l) { int mid = (r + l) / 2; if(ask(in,out,x1,y1,x2,mid) == 1) { ansy2 = mid; r = mid - 1; } else { l = mid + 1; } } //out.printf("y2 = %d", ansy2); r = y2; l = y1; // quero o maximo v <= y1 while(r >= l) { int mid = (r + l) / 2; if(ask(in,out,x1,mid,x2,y2) == 1) { ansy1 = mid; l = mid + 1; } else { r = mid - 1; } } //out.printf("y1 = %d", ansy1); rec.x1 = ansx1; rec.x2 = ansx2; rec.y1 = ansy1; rec.y2 = ansy2; return rec; } public int ask(InputReader in, PrintWriter out, int x1, int y1, int x2, int y2) { System.out.printf("? %d %d %d %d\n",x1,y1,x2,y2); System.out.flush(); return in.nextInt(); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { } return null; } } }
logn
713_B. Searching Rectangles
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; import java.util.TreeSet; public class E { static Scanner in; static int next() throws Exception {return in.nextInt();}; // static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} // static BufferedReader in; static PrintWriter out; public static void main(String[] args) throws Exception { in = new Scanner(System.in); // in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = next(); if (n%4 == 0||n%7 == 0||n%44 == 0||n%47 == 0||n%74 == 0||n%77 == 0||n%444 == 0||n%447 == 0||n%474 == 0||n%744 == 0||n%774 == 0||n%747 == 0||n%477 == 0||n%777==0) out.println("YES"); else out.println("NO"); out.println(); out.close(); } }
constant
122_A. Lucky Division
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { static class Team implements Comparable<Team> { int pr; int time; int id; public Team(int P, int T, int I) { pr = P; time = T; id = I; } @Override public int compareTo(Team t) { return pr != t.pr ? t.pr - pr : time != t.time ? time - t.time : id - t.id; } } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); Team[] a = new Team[n]; int[] c = new int[n + 1]; for (int i = 0; i < n; i++) { st = new StringTokenizer(in.readLine()); int p = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); a[i] = new Team(p, t, i); } Arrays.sort(a); int prev = 1; c[1]++; for (int i = 1; i < n; i++) { if (a[i].pr == a[i - 1].pr && a[i].time == a[i - 1].time) for (int j = i + 1; j >= prev; j--) c[j] = i + 2 - prev; else { prev = i + 1; c[prev] = 1; } } out.println(c[k]); out.close(); } }
nlogn
166_A. Rank List
CODEFORCES
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.regex.*; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; public static void main(String[] args) throws Exception { br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); //int qq = 1; int qq = Integer.MAX_VALUE; //int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int r = readInt(); int c = readInt(); int n = readInt(); int[][] dist = new int[r][c]; for(int i = 0; i < r; i++) { Arrays.fill(dist[i], 1 << 25); } LinkedList<State> q = new LinkedList<State>(); while(n-- > 0) { q.add(new State(readInt()-1, readInt()-1)); dist[q.peekLast().x][q.peekLast().y] = 0; } int[] dx = new int[]{-1,1,0,0}; int[] dy = new int[]{0,0,-1,1}; State ret = q.peekLast(); while(!q.isEmpty()) { State curr = q.removeFirst(); ret = curr; for(int k = 0; k < dx.length; k++) { int nx = curr.x + dx[k]; int ny = curr.y + dy[k]; if(nx >= 0 && nx < r && ny >= 0 && ny < c && dist[nx][ny] > 1 + dist[curr.x][curr.y]) { dist[nx][ny] = 1 + dist[curr.x][curr.y]; q.add(new State(nx, ny)); } } } pw.println(ret.x+1 + " " + (ret.y+1)); } exitImmediately(); } static class State { public int x,y; public State(int x, int y) { super(); this.x = x; this.y = y; } } private static void exitImmediately() { pw.close(); System.exit(0); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextLine() throws IOException { if(!br.ready()) { exitImmediately(); } st = null; return br.readLine(); } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { exitImmediately(); } st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; public class B { public static void main (String[] args) throws IOException { BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(b.readLine()); while (n-- > 0) { String s = b.readLine(); if (s.matches("^[A-Z]+[0-9]+$")) { System.out.println(toRC(decodeCR(s))); } else { System.out.println(toCR(decodeRC(s))); } } } private static String toRC(int[] a) { return "R" + a[0] + "C" + a[1]; } private static String toCR(int[] a) { String r = ""; if (a[1] == 1) { r = "A"; } else { for (int x = a[1]; x > 0; x /= 26) { r = (char)('A' + (x - 1) % 26) + r; if (x % 26 == 0) x -= 26; } } return r + a[0]; } private static int[] decodeCR(String s) { int[] a = new int[2]; int i = 0; while (s.charAt(i) >= 'A') { a[1] = a[1] * 26 + (s.charAt(i) - 'A' + 1); i++; } a[0] = Integer.parseInt(s.substring(i)); // System.out.println("decoding CR: " + s + "..." + a[0] + ", " + a[1]); return a; } private static int[] decodeRC(String s) { assert s.charAt(0) == 'R'; int[] a = new int[2]; a[0] = Integer.parseInt(s.substring(1, s.indexOf('C'))); a[1] = Integer.parseInt(s.substring(s.indexOf('C') + 1)); // System.out.println("decoding RC: " + s + "..." + a[0] + ", " + a[1]); return a; } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner in =new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = in.nextInt(); for(int i = n-1; i > 0; i--) arr[i] -= arr[i-1]; arr[0] = 0; Arrays.sort(arr); long sum = 0; for(int i = n-k; i >= 0; i--) sum += arr[i]; System.out.println(sum); } }
nlogn
1197_C. Array Splitting
CODEFORCES
import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Scanner; import java.util.ArrayList; public class Main { static int d[][]; static int N; static boolean used[]; static class point { int x = 0; int y = 0; } static point dats[]; public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n = scan.nextLong(); long k = scan.nextLong(); if(n==1) { System.out.print("0"); return; } if(n<=k) { System.out.print("1"); return; } long d = 9-4*(2*n-k*k+k); if(d<0) { System.out.print("-1"); return; } double a = ((3+Math.sqrt(d)) / 2) ; if(a>=1) System.out.println(Math.max(2, k-(long)a+1)); else System.out.println(-1); } }
logn
287_B. Pipeline
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; public class Main{ Scanner sc=new Scanner(System.in); void run(){ int n = sc.nextInt(); int x[] = new int [n]; for (int i=0;i<n;i++) x[i] = sc.nextInt(); java.util.Arrays.sort(x); int i = 0; for(i=0;i<n-1;i++) { if (x[i] != x[i+1]) { System.out.println( x[i+1] ); return; } } System.out.println("NO"); return; } public static void main(String[] args){ new Main().run(); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.util.*; import java.io.*; public class E74 { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(); long time = System.currentTimeMillis(); int [][] a = new int[m][m]; int [][] pre = new int[m][(1 << m)]; for (int i = 0; i < n - 1; i++) { if (s.charAt(i) == s.charAt(i + 1)) continue; a[s.charAt(i) - 'a'][s.charAt(i + 1) - 'a']++; a[s.charAt(i + 1) - 'a'][s.charAt(i) - 'a']++; } //System.out.println("Process Input: " + (System.currentTimeMillis() - time)); for (int i = 0; i < m; i++) { int b = 0; int stor = 2; for (int j = 1; j < (1 << m); j++) { if (j == stor) { b++; stor = (1 << (b + 1)); } pre[i][j] = pre[i][j ^ (1 << b)] + a[i][b]; } } //System.out.println("Precomp: " + (System.currentTimeMillis() - time)); long [] dp = new long[1 << m]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for (int mask = 1; mask < (1 << m); mask++) { // loop on the last added character in the mask for (int i = 0; i < m; i++) { if (((mask >> i) & 1) == 0) continue; long prev = dp[mask ^ (1 << i)]; long contribution = (pre[i][mask] - pre[i][((1 << m) - 1) ^ mask]) * Integer.bitCount(mask); dp[mask] = Math.min(dp[mask], prev + contribution); } } //System.out.println("Done: " + (System.currentTimeMillis() - time)); out.println(dp[(1 << m) - 1]); out.close(); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
np
1238_E. Keyboard Purchase
CODEFORCES
// Don't place your source in a package import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int T=1; for(int t=0;t<T;t++){ int n=Int(); int k=Int(); int A[][]=new int[n][2]; int a=0,b=0,c=0; for(int i=0;i<A.length;i++){ A[i][0]=Int(); A[i][1]=Int()-1; if(A[i][1]==0)a++; else if(A[i][1]==1)b++; else c++; } Arrays.sort(A,(x,y)->{ return x[0]-y[0]; }); Solution sol=new Solution(out); sol.solution(A,k,a,b,c); } out.close(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ PrintWriter out; public Solution(PrintWriter out){ this.out=out; } int mod=1000000007; long dp3[][][][]; public void solution(int A[][],int T,int x,int y,int z){ long res=0; int n=A.length; long dp1[][]=new long[x+2][T+1];//a long dp2[][][]=new long[y+2][z+2][T+2];//bc dp3=new long[x+2][y+2][z+2][3]; //init long f[]=new long[n+10]; f[0]=f[1]=1; for(int i=2;i<f.length;i++){ f[i]=f[i-1]*i; f[i]%=mod; } for(int i=0;i<dp3.length;i++){ for(int j=0;j<dp3[0].length;j++){ for(int k=0;k<dp3[0][0].length;k++){ Arrays.fill(dp3[i][j][k],-1); } } } dp1[0][0]=1; for(int i=0;i<A.length;i++){//a int p=A[i][0],type=A[i][1]; if(type==0){ long newdp[][]=new long[dp1.length][dp1[0].length]; for(int cnt=1;cnt<=x;cnt++){ for(int j=1;j<dp1[0].length;j++){ if(j>=p){ newdp[cnt][j]+=dp1[cnt-1][j-p]; newdp[cnt][j]%=mod; } } } for(int cnt=0;cnt<=x;cnt++){ for(int j=0;j<dp1[0].length;j++){ newdp[cnt][j]+=dp1[cnt][j]; newdp[cnt][j]%=mod; } } dp1=newdp; } } dp2[0][0][0]=1; for(int i=0;i<A.length;i++){//b c int p=A[i][0],type=A[i][1]; if(type!=0){ long newdp[][][]=new long[dp2.length][dp2[0].length][dp2[0][0].length]; for(int a=0;a<dp2.length;a++){ for(int b=0;b<dp2[0].length;b++){ for(int j=0;j<dp2[0][0].length;j++){ if(j>=p){ if(type==1){ if(a-1>=0){ newdp[a][b][j]+=dp2[a-1][b][j-p]; } } else{ if(b-1>=0) { newdp[a][b][j]+=dp2[a][b-1][j-p]; } } } newdp[a][b][j]%=mod; } } } for(int a=0;a<dp2.length;a++){ for(int b=0;b<dp2[0].length;b++){ for(int j=0;j<dp2[0][0].length;j++){ newdp[a][b][j]+=dp2[a][b][j]; newdp[a][b][j]%=mod; } } } dp2=newdp; } } dp3[1][0][0][0]=1; dp3[0][1][0][1]=1; dp3[0][0][1][2]=1; for(int i=0;i<dp3.length;i++){ for(int j=0;j<dp3[0].length;j++){ for(int k=0;k<dp3[0][0].length;k++){ for(x=0;x<dp3[0][0][0].length;x++){ if(dp3[i][j][k][x]==-1){ dfs(i,j,k,x); } } } } } for(int i=0;i<dp3.length;i++){ for(int j=0;j<dp3[0].length;j++){ for(int k=0;k<dp3[0][0].length;k++){ for(int cur=0;cur<3;cur++){ for(int t=0;t<=T;t++){//price int aprice=t; int bcprice=T-t; long cnt1=dp1[i][aprice]; long cnt2=dp2[j][k][bcprice]; long combination=dp3[i][j][k][cur]; ///if(combination==-1)combination=0; long p1=(cnt1*f[i])%mod; long p2=(((f[j]*f[k])%mod)*cnt2)%mod; long p3=(p1*p2)%mod; res+=(p3*combination)%mod; res%=mod; } } } } } //System.out.println(dp2[1][0][2]+" "+dp3[1][1][0][0]); // for(long p[]:dp1){ // System.out.println(Arrays.toString(p)); //} out.println(res); } public long dfs(int a,int b,int c,int cur){ if(a<0||b<0||c<0){ return 0; } if(a==0&&b==0&&c==0){ return 0; } if(dp3[a][b][c][cur]!=-1)return dp3[a][b][c][cur]; long res=0; if(cur==0){ res+=dfs(a-1,b,c,1); res%=mod; res+=dfs(a-1,b,c,2); res%=mod; } else if(cur==1){ res+=dfs(a,b-1,c,0); res%=mod; res+=dfs(a,b-1,c,2); res%=mod; } else{ res+=dfs(a,b,c-1,0); res%=mod; res+=dfs(a,b,c-1,1); res%=mod; } res%=mod; dp3[a][b][c][cur]=res; return res; } } /* ;\ |' \ _ ; : ; / `-. /: : | | ,-.`-. ,': : | \ : `. `. ,'-. : | \ ; ; `-.__,' `-.| \ ; ; ::: ,::'`:. `. \ `-. : ` :. `. \ \ \ , ; ,: (\ \ :., :. ,'o)): ` `-. ,/,' ;' ,::"'`.`---' `. `-._ ,/ : ; '" `;' ,--`. ;/ :; ; ,:' ( ,:) ,.,:. ; ,:., ,-._ `. \""'/ '::' `:'` ,'( \`._____.-'"' ;, ; `. `. `._`-. \\ ;:. ;: `-._`-.\ \`. '`:. : |' `. `\ ) \ -hrr- ` ;: | `--\__,' '` ,' ,-' free bug dog */ /* 5 3 1 1 2 1 2 1 2 1 2 2 */
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(new FileWriter("output.txt")); Scanner in=new Scanner(new File("input.txt")); int n,m,k; n=in.nextInt(); m=in.nextInt(); k=in.nextInt(); Vector<Integer> vec=new Vector<Integer>(); Vector<Integer> temp=new Vector<Integer>(); boolean[][] mas=new boolean[n][m]; long time=System.currentTimeMillis(); for(int i=0;i<k;i++) { vec.add(in.nextInt()-1); vec.add(in.nextInt()-1); mas[vec.get(vec.size()-2)][vec.get(vec.size()-1)]=true; } int x,y; x=y=0; while(vec.size()!=0) { for(int i=0;i<vec.size();i+=2) { x=vec.get(i); y=vec.get(i+1); if(x>0 && !mas[x-1][y]) { temp.add(x-1); temp.add(y); mas[x-1][y]=true; } if(x<n-1 && !mas[x+1][y]) { temp.add(x+1); temp.add(y); mas[x+1][y]=true; } if(y>0 && !mas[x][y-1]) { temp.add(x); temp.add(y-1); mas[x][y-1]=true; } if(y<m-1 && !mas[x][y+1]) { temp.add(x); temp.add(y+1); mas[x][y+1]=true; } } vec=temp; temp=new Vector<Integer>(); } pw.println((x+1)+" "+(y+1)); System.out.println(System.currentTimeMillis()-time); in.close(); 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.Arrays; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { final int MOD = (int) (1e9 + 7); long[][] C; long[] fact; public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); precalc(n); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); a[i] = removeSquares(a[i]); } int[] g = getGroupSizes(a); long ans = solve(g); for (int x : g) { ans = ans * fact[x] % MOD; } out.println(ans); } private long solve(int[] a) { // For a description, see http://petr-mitrichev.blogspot.com/2017/07/a-week7.html long[] d = new long[1]; d[0] = 1; int totalPositions = 1; for (int x : a) { long[] nd = new long[d.length + x + 1]; for (int s = 0; s < d.length; s++) { if (d[s] == 0) { continue; } for (int m = 1; m <= x; m++) { for (int p = 0; p <= s && p <= m; p++) { long cur = d[s]; cur = cur * C[s][p] % MOD; cur = cur * C[totalPositions - s][m - p] % MOD; cur = cur * f(x, m) % MOD; int ns = s + x - m - p; nd[ns] += cur; if (nd[ns] >= MOD) { nd[ns] -= MOD; } } } } totalPositions += x; d = nd; } return d[0]; } private long f(int n, int k) { if (n < k) { return 0; } n -= k; return C[n + k - 1][k - 1]; } private void precalc(int n) { fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i < fact.length; i++) { fact[i] = i * fact[i - 1] % MOD; } C = new long[1000][1000]; C[0][0] = 1; for (int i = 1; i < C.length; i++) { C[i][0] = 1; for (int j = 1; j < C.length; j++) { C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; if (C[i][j] >= MOD) { C[i][j] -= MOD; } } } } private int[] getGroupSizes(int[] a) { Arrays.sort(a); List<Integer> res = new ArrayList<>(); for (int i = 0; i < a.length; ) { int j = i; while (j < a.length && a[i] == a[j]) { ++j; } res.add(j - i); i = j; } int[] r = new int[res.size()]; for (int i = 0; i < r.length; i++) { r[i] = res.get(i); } return r; } private int removeSquares(int n) { int res = 1; for (int d = 2; d * d <= n; d++) { if (n % d == 0) { int cur = 0; while (n % d == 0) { n /= d; ++cur; } if (cur % 2 == 1) { res *= d; } } } if (n > 1) { res *= n; } return res; } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
cubic
840_C. On the Bench
CODEFORCES
import java.util.*; import java.io.*; public class LCMChallenge { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); if(n < 3) { System.out.println(n); } else if(n % 2 == 1) { System.out.println((long)n * (n - 1) * (n - 2)); } else { if(n % 3 != 0) { System.out.println((long)n * (n - 1) * (n - 3)); } else { System.out.println((long)(n - 1) * (n - 2) * (n - 3)); } } } }
constant
235_A. LCM Challenge
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); long l = in.nextLong(); long r = in.nextLong(); if(r-l < 2 ){ System.out.println("-1"); } else if(r-l == 2 && l %2 ==1){ System.out.println("-1"); } else{ if(l%2 == 0){ System.out.println(l+ " "+(l+1)+" "+(l+2)); } else{ System.out.println((l+1)+ " "+(l+2)+" "+(l+3)); } } } }
constant
483_A. Counterexample
CODEFORCES
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package NumberTheory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author Sourav Kumar Paul */ public class A235 { public static void main(String[] args) throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); long n = Long.parseLong(reader.readLine()); //int gcd = gcd(924,923); //System.out.println(gcd); // System.out.println(gcd(923,461)); if(n<=2) System.out.println(n); else if(n==3) System.out.println("6"); else if(n % 2== 0) { if(n % 3 == 0) { System.out.println((n-3)*(n-1)*(n-2)); } else System.out.println(n * (n-1) * (n-3) ); } else System.out.println(n*(n-1)*(n-2)); } private static int gcd(int i, int j) { int a = Math.min(i,j); int b = Math.max(i,j); while(a != 0) { int temp = b % a; b = a; a = temp; } return b; } }
constant
235_A. LCM Challenge
CODEFORCES
import java.util.Scanner; public class ChainReaction { public static void main(String [] args) { Scanner kb = new Scanner(System.in); int num = kb.nextInt(); int[] beacons = new int[1000002]; for (int i=0; i<num; i++) { beacons[kb.nextInt()] = kb.nextInt(); } int [] dp = new int[1000002]; int max = 0; if (beacons[0] != 0) dp[0] = 1; for (int i=1; i<dp.length; i++) { if (beacons[i] == 0) { dp[i] = dp[i-1]; } else { int index = i-1-beacons[i]; if (index<0) dp[i] = 1; else dp[i] = 1 + dp[index]; } max = Math.max(max, dp[i]); //if (i<11) //System.out.println(i +" is "+dp[i]); } System.out.println(num-max); } }
linear
608_C. Chain Reaction
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Train_A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int [] h = new int[n]; for (int i = 0; i < n; i++) { h[i] = sc.nextInt(); } Arrays.sort(h); System.out.println(h[n-a] - h[b-1]); } }
nlogn
169_A. Chores
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.StringTokenizer; /** * Created by IntelliJ IDEA. * User: piyushd * Date: Dec 5, 2010 * Time: 4:09:41 PM * To change this template use File | Settings | File Templates. */ public class HamstersTigers { private BufferedReader in; private PrintWriter out; private StringTokenizer st; int solve(String a, int k){ int n = a.length(), ret = 0; int temp[] = new int[n]; for(int i = 0; i < n; i++) temp[(n + i - k) % n] = (a.charAt(i) == 'T') ? 1: 0; int left = 0, right = n - 1; while(left < right){ while(temp[left] == 0) left++; while(temp[right] == 1) right--; if(left < right){ int t = temp[left]; temp[left] = temp[right]; temp[right] = t; ret++; } } return ret; } void solve() throws IOException { int n = nextInt(); String a = next(); int ans = Integer.MAX_VALUE; for(int fix = 0; fix < n; fix++){ ans = Math.min(ans, solve(a, fix)); } out.println(ans); } HamstersTigers() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C://Users/piyushd/Desktop/codeforces/sample.txt")))); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new HamstersTigers(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.util.*; import java.io.*; public class ASimpleTask { /************************ SOLUTION STARTS HERE ***********************/ static long memo[][]; static int graph[]; static long hamiltonianPath(int mask , int u) { if(memo[mask][u] != -1) return memo[mask][u]; else if(u == Integer.numberOfTrailingZeros(mask)) // according to our convention A simple path is not allowed to end at the lowest vertex return 0; else { long sum = 0; for(int fromSet = mask ^ (1 << u);fromSet > 0; fromSet ^= Integer.lowestOneBit(fromSet)) { int v = Integer.numberOfTrailingZeros(fromSet); // System.out.printf("mask = %s , u = %d , v = %d\n" , Integer.toBinaryString(mask) , u , v); if((graph[u] & (1 << v)) != 0) sum += hamiltonianPath(mask ^ (1 << u), v); } return /*memo[mask][u] = */sum; } } private static void solveBottomUp(FastScanner s1, PrintWriter out){ int V = s1.nextInt(); int E = s1.nextInt(); graph = new int[V]; long DP[][] = new long[1 << V][V]; while(E-->0) { int u = s1.nextInt() - 1; int v = s1.nextInt() - 1; graph[u] |= (1 << v); graph[v] |= (1 << u); } for(int i=0;i<V;i++) DP[1 << i][i] = 1; for(int mask = 1 , end = 1 << V;mask < end;mask++) { for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); for(int fromSet = mask ^ (1 << u);fromSet > 0; fromSet ^= Integer.lowestOneBit(fromSet)) { int v = Integer.numberOfTrailingZeros(fromSet); // System.out.printf("mask = %s , u = %d , v = %d\n" , Integer.toBinaryString(mask) , u , v); if((graph[u] & (1 << v)) != 0) DP[mask][u] += DP[mask ^ (1 << u)][v]; } } } long totalCycles = 0; for(int mask = 1 , end = 1 << V;mask < end;mask++) { if(Integer.bitCount(mask) >= 3) { int start = Integer.numberOfTrailingZeros(mask); for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); if((graph[u] & (1 << start)) != 0) totalCycles += DP[mask][u]; } } } totalCycles /= 2; /* for(long l[] : DP) out.println(Arrays.toString(l));*/ out.println(totalCycles); } private static void solveTopDown(FastScanner s1, PrintWriter out){ int V = s1.nextInt(); int E = s1.nextInt(); graph = new int[V]; memo = new long[1 << V][V]; for(long l[] : memo) Arrays.fill(l, -1); while(E-->0) { int u = s1.nextInt() - 1; int v = s1.nextInt() - 1; graph[u] |= (1 << v); graph[v] |= (1 << u); } for(int i=0;i<V;i++) memo[1 << i][i] = 1; long totalCycles = 0; for(int mask = 1 , end = 1 << V;mask < end;mask++) { if(Integer.bitCount(mask) >= 3) { int start = Integer.numberOfTrailingZeros(mask); for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); if((graph[u] & (1 << start)) != 0) totalCycles += hamiltonianPath(mask, u); } } } totalCycles /= 2; out.println(totalCycles); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE *********************/ public static void main(String []args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); solveBottomUp(in, out); in.close(); out.close(); } static class FastScanner{ BufferedReader reader; StringTokenizer st; FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;} String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} char nextChar() {return next().charAt(0);} int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}} } /************************ TEMPLATE ENDS HERE ************************/ }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static long oo = 1000000000000L; public static void main(String[] args) throws IOException { int n = in.nextInt(); int q = in.nextInt(); ArrayDeque<Integer> dq = new ArrayDeque<>(); int max = -1; for(int i = 0; i < n; ++i) { int x = in.nextInt(); dq.add(x); max = Math.max(max, x); } ArrayList<Pair> ans = new ArrayList<>(); while(dq.peekFirst() != max) { int a = dq.pollFirst(); int b = dq.pollFirst(); ans.add(new Pair(a, b)); if(a > b) { dq.addFirst(a); dq.addLast(b); } else { dq.addFirst(b); dq.addLast(a); } } ArrayList<Integer> a = new ArrayList<>(); dq.pollFirst(); for(int x : dq) a.add(x); while(q --> 0) { long m = in.nextLong() - 1; if(m < ans.size()) { System.out.println(ans.get((int)m).first + " " + ans.get((int)m).second); } else { int idx = (int)((m - ans.size()) % a.size()); System.out.println(max + " " + a.get(idx)); } } out.close(); } static long lcm(long a, long b) { return a * b / gcd(a, b); } static boolean nextPermutation(int[] a) { for(int i = a.length - 2; i >= 0; --i) { if(a[i] < a[i+1]) { for(int j = a.length - 1; ; --j) { if(a[i] < a[j]) { int t = a[i]; a[i] = a[j]; a[j] = t; for(i++, j = a.length - 1; i < j; ++i, --j) { t = a[i]; a[i] = a[j]; a[j] = t; } return true; } } } } return false; } static void shuffle(int[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); int t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(long[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); long t = a[si]; a[si] = a[i]; a[i] = t; } } static int lower_bound(int[] a, int n, int k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int lower_bound(long[] a, int n, long k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return this.first != o.first ? this.first - o.first : this.second - o.second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; 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 (first != other.first) return false; if (second != other.second) return false; return true; } } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { 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 { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
linear
1180_C. Valeriy and Deque
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class PipelineRedo { public static void main(String[] args){ FastScanner sc = new FastScanner(); long n = sc.nextLong() - 1; long k = sc.nextInt() - 1; if(n==0){ System.out.println(0); return; }else if(n <= k){ System.out.println(1); return; }else if(n > k*(k+1)/2){ System.out.println(-1); return; } //n > k, and there exists a subset (1..k) = n //goal : sum( subset of (1...k) ) = n //obs: if exists a soln, it's always possible to push everything to the right-> t + left...k //so that t + left...k = n, so we just have to find the smallest left such that left..k <= n long rightSum = k*(k+1)/2; long lo = 1; long hi = k; while(lo < hi){ long mid = lo + (hi-lo+1)/2; long val = rightSum - mid*(mid-1)/2; if(val <= n){ hi = mid -1; }else{ lo = mid; } } //now lo points to the greatest left for which left..k > n //so lo+1 points to the smallest left for which left..k <= n //we still have an extra 't' to the left if(rightSum - (lo+1)*(lo)/2 == n){ System.out.println(k - (lo+1) + 1); }else{ System.out.println(1 + (k - (lo+1) + 1)); } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
logn
287_B. Pipeline
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class ProblemB3 { Map<Integer, List<int[]>> dest; private ProblemB3() throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); String h = rd.readLine(); String[] q = h.split("\\s+"); int a = Integer.parseInt(q[1]); int b = Integer.parseInt(q[2]); h = rd.readLine(); q = h.split(" "); int n = q.length; int[] p = new int[n]; for(int i=0;i<n;i++) { p[i] = Integer.parseInt(q[i]); } Set<Integer> pset = new HashSet<>(); for(int x: p) { pset.add(x); } dest = new HashMap<>(); boolean res = true; for(int x: p) { boolean aOk = pset.contains(a-x); boolean bOk = pset.contains(b-x); if(!aOk && !bOk) { res = false; break; } else { if(aOk) { addEdgeAndBack(x,a-x,0); } if(bOk) { addEdgeAndBack(x,b-x,1); } } } Set<Integer> aSet = new HashSet<>(); if(res && a != b) { for(int x: p) { List<int[]> e = getEdges(x); if(e.size() == 1) { int[] edge = e.get(0); boolean odd = true; int curA = edge[1]; int prev = x; while(true) { int cur = edge[0]; if(curA == 0 && odd) { aSet.add(prev); aSet.add(cur); } e = getEdges(cur); if(e.size() == 1) { if(!odd && e.get(0)[0] != cur) { res = false; } break; } int other = e.get(0)[0] == prev?1:0; edge = e.get(other); if(edge[1] == curA) { res = false; break; } curA = 1-curA; prev = cur; odd = !odd; } if(!res) { break; } } } } out(res?"YES":"NO"); if(res) { StringBuilder buf = new StringBuilder(); for(int i=0;i<n;i++) { if(i>0) { buf.append(' '); } buf.append(aSet.contains(p[i])?'0':'1'); } out(buf); } } private void addEdgeAndBack(int from, int to, int u) { addEdge(from, to, u); addEdge(to, from, u); } private void addEdge(int from, int to, int u) { List<int[]> edges = getEdges(from); for(int[] edge: edges) { if(edge[0] == to) { return; } } edges.add(new int[]{to, u}); } private List<int[]> getEdges(int from) { List<int[]> ds = dest.get(from); if(ds == null) { ds = new ArrayList<>(); dest.put(from, ds); } return ds; } private static void out(Object x) { System.out.println(x); } public static void main(String[] args) throws IOException { new ProblemB3(); } }
linear
468_B. Two Sets
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.Arrays; public class Main { static StreamTokenizer st=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); public static void main(String[] args) { int n=nextInt(); int m=nextInt(); long b[]=new long[n]; long g[]=new long[m]; for(int i=0;i<n;i++) b[i]=nextInt(); for(int i=0;i<m;i++) g[i]=nextInt(); Arrays.sort(b); Arrays.sort(g); if(b[n-1]>g[0]) System.out.println("-1"); else if(b[n-1]==g[0]){ long sum=0; for(int i=0;i<m;i++) sum+=g[i]; for(int i=0;i<n-1;i++){ sum+=(m*b[i]); } System.out.println(sum); }else{ long sum=0; for(int i=0;i<m;i++) sum+=g[i]; sum+=b[n-1]; sum+=(b[n-2]*(m-1)); for(int i=0;i<n-2;i++){ sum+=(m*b[i]); } System.out.println(sum); } } static int nextInt(){ try { st.nextToken(); } catch (IOException e) { e.printStackTrace(); } return (int)st.nval; } }
nlogn
1159_C. The Party and Sweets
CODEFORCES
import java.io.*; import java.util.*; public class a23 { public static void main(String args[])throws IOException { InputStreamReader read=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(read); String s,subs; // System.out.println("Enter"); s=in.readLine(); int i,j,k,l=0,a=1,sl=0; for(i=0;i<s.length();i++) { a=1; for(j=i;j<s.length();j++) { subs=s.substring(i,i+a); for(k=i;k<(s.length()-a+1);k++) { if(subs.compareTo(s.substring(k,k+a))==0) l++; if(l==2) { if(a>sl) sl=a; l=0; break; } } l=0; a++; } } System.out.println(sl); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; public class cf343a { static FastIO in = new FastIO(), out = in; public static void main(String[] args) { out.println(go(in.nextLong(),in.nextLong())); out.close(); } static long go(long a, long b) { return b==0?0:(go(b,a%b) + a/b); } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() { this(System.in, System.out); } public FastIO(InputStream in, OutputStream out) { super(new BufferedWriter(new OutputStreamWriter(out))); br = new BufferedReader(new InputStreamReader(in)); scanLine(); } public void scanLine() { try { st = new StringTokenizer(br.readLine().trim()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } public int numTokens() { if (!st.hasMoreTokens()) { scanLine(); return numTokens(); } return st.countTokens(); } public String next() { if (!st.hasMoreTokens()) { scanLine(); return next(); } return st.nextToken(); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
constant
343_A. Rational Resistance
CODEFORCES
import java.util.Scanner; public class TreasureHunt { public static String Solve() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); String kuro = sc.nextLine(), shiro = sc.nextLine(), katie = sc.nextLine(); sc.close(); String[] output = {"Kuro", "Shiro", "Katie", "Draw"}; if(n >= kuro.length()) return output[3]; int[] maxArr = new int[3]; int[][] freq = new int[3][58]; for(int i = 0; i < kuro.length(); i++) { maxArr[0] = ++freq[0][kuro.charAt(i) - 65] > maxArr[0]? freq[0][kuro.charAt(i) - 65] : maxArr[0]; maxArr[1] = ++freq[1][shiro.charAt(i) - 65] > maxArr[1]? freq[1][shiro.charAt(i) - 65] : maxArr[1]; maxArr[2] = ++freq[2][katie.charAt(i) - 65] > maxArr[2]? freq[2][katie.charAt(i) - 65] : maxArr[2]; } int winner = 0, max = 0; for(int i = 0; i < 3; i++) { if(kuro.length() - maxArr[i] >= n) maxArr[i] += n; else maxArr[i] = n == 1? kuro.length() - 1: kuro.length(); if(max < maxArr[i]) { winner = i; max = maxArr[i]; } else if(max == maxArr[i]) winner = 3; } return output[winner]; } public static void main(String[] args) { System.out.println(Solve()); } }
linear
979_B. Treasure Hunt
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Wolfgang Beyer */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { long n = in.nextLong(); long s = in.nextLong(); if (n - digitSum(n) < s) { out.println(0); return; } long left = 0; long right = n; while (left < right) { long mid = left + (right - left) / 2; if (mid - digitSum(mid) >= s) { // if condition(mid) == true right = mid; } else { left = mid + 1; } } out.println(n - left + 1); } long digitSum(long a) { long result = 0; while (a > 0) { result += a % 10; a /= 10; } return result; } } static class InputReader { private static BufferedReader in; private static StringTokenizer tok; public InputReader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public long nextLong() { return Long.parseLong(next()); } public String next() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); //tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter } } catch (IOException ex) { System.err.println("An IOException was caught :" + ex.getMessage()); } return tok.nextToken(); } } }
logn
817_C. Really Big Numbers
CODEFORCES
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; int n; int m; char[][] mat; long base = 397; void solve() throws IOException { n = nextInt(); m = nextInt(); mat = new char[n][m]; for (int i = 0; i < n; i++) { mat[i] = nextString().toCharArray(); } int alpha = 26; long[] pow = new long[alpha]; pow[0] = 1; for (int i = 1; i < alpha; i++) { pow[i] = pow[i - 1] * base % MOD; } long res = 0; for (int l = 0; l < m; l++) { //[l, r] long[] hash = new long[n]; long[] mask = new long[n]; for (int r = l; r < m; r++) { for (int i = 0; i < n; i++) { hash[i] += pow[mat[i][r] - 'a']; hash[i] %= MOD; mask[i] = mask[i] ^ (1L << (mat[i][r] - 'a')); } int start = 0; while (start < n) { if ((mask[start] & (mask[start] - 1)) != 0) { start++; continue; } int end = start; List<Long> l1 = new ArrayList<>(); while (end < n && (mask[end] & (mask[end] - 1)) == 0) { l1.add(hash[end]); end++; } start = end; res += manacher(l1); } } } outln(res); } long manacher(List<Long> arr) { int len = arr.size(); long[] t = new long[len * 2 + 3]; t[0] = -1; t[len * 2 + 2] = -2; for (int i = 0; i < len; i++) { t[2 * i + 1] = -3; t[2 * i + 2] = arr.get(i); } t[len * 2 + 1] = -3; int[] p = new int[t.length]; int center = 0, right = 0; for (int i = 1; i < t.length - 1; i++) { int mirror = 2 * center - i; if (right > i) { p[i] = Math.min(right - i, p[mirror]); } // attempt to expand palindrome centered at i while (t[i + (1 + p[i])] == t[i - (1 + p[i])]) { p[i]++; } // if palindrome centered at i expands past right, // adjust center based on expanded palindrome. if (i + p[i] > right) { center = i; right = i + p[i]; } } long res = 0; for (int i = 0; i < 2 * len; i++) { int parLength = p[i + 2]; if (i % 2 == 0) { res += (parLength + 1) / 2; } else { res += parLength / 2; } } return res; } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { outln(String.format("%.9f%n", val)); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
nlogn
1080_E. Sonya and Matrix Beauty
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner x=new Scanner(System.in); int n=x.nextInt(); if(n%2==0){ System.out.println((n-4)+" "+"4"); } else{ System.out.println((n-9)+" "+"9"); } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.util.*; public class Main { public static void main(String [] args){ Scanner in=new Scanner(System.in); int n=in.nextInt(); double value[][]=new double[n][n]; for(int i=0;i<n;i++) for(int j=0;j<n;j++)value[i][j]=in.nextDouble(); double ans[]=new double[1<<n]; int mask=(1<<n); ans[(1<<n)-1]=1.0; for(int i=mask-1;i>=0;i--){ int cnt=Integer.bitCount(i); int pairs=cnt*(cnt-1)/2; for(int j=0;j<n;j++){ if(((i>>j)&1)==0)continue; for(int k=j+1;k<n;k++){ if(((i>>k)&1)==0)continue; ans[i^(1<<k)]+=ans[i]*value[j][k]/pairs; ans[i^(1<<j)]+=ans[i]*value[k][j]/pairs; } } } for(int i=0;i<n;i++) System.out.print(ans[1<<i]+" "); } }
np
16_E. Fish
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; /** * Created by aditya on 5/3/17. */ public class Main3 { static long x, k; static long MOD = (long)1e9 + 7; public static void main(String args[]) throws Exception{ FastInput fi = new FastInput(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); x = fi.nextLong(); k = fi.nextLong(); if(x == 0) { System.out.println(0); return; } // System.out.println(pow(2, k+1)); long q1 = (pow(2, k+1) * (x%MOD)) % MOD; long q2 = pow(2, k); long q3 = 1; // System.out.println(q1); // System.out.println(q2); // System.out.println(q3); long exp = (q1-q2 + MOD + MOD)%MOD; exp = (exp + q3)%MOD; // exp = (exp*2)%MOD; pw.println(exp); pw.close(); } static long pow(long n, long k) { if(k == 0) return 1; if(k == 1) return n; long ret = pow(n, k/2)%MOD; ret = (ret*ret)%MOD; if(k%2 == 1) ret = (ret*n)%MOD; return ret; } static class FastInput { private Reader in; private BufferedReader br; private StringTokenizer st; public FastInput(Reader in) { this.in=in; br = new BufferedReader(in); } public String nextString() { while(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { System.out.println(e.getStackTrace()); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } public long nextLong() { return Long.parseLong(nextString()); } public double nextDouble() { return Double.parseDouble(nextString()); } } }
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.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jeel Vaishnav */ 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); G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion(); solver.solve(1, in, out); out.close(); } static class G1PlaylistForPolycarpEasyVersion { public void solve(int testNumber, InputReader sc, PrintWriter out) { int n = sc.nextInt(); int T = sc.nextInt(); int mod = (int) 1e9 + 7; int dp[][][] = new int[1 << n][226][3]; int t[] = new int[n]; int g[] = new int[n]; for (int i = 0; i < n; ++i) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; dp[1 << i][t[i]][g[i]] = 1; } for (int i = 0; i < (1 << n); ++i) { for (int j = 0; j < n; ++j) { if ((i >> j & 1) == 1) { int newMask = i ^ (1 << j); for (int k = t[j]; k <= T; ++k) { for (int l = 0; l < 3; ++l) { if (l == g[j]) continue; dp[i][k][g[j]] = (dp[i][k][g[j]] + dp[newMask][k - t[j]][l]) % mod; } } } } } long ans = 0; for (int i = 0; i < (1 << n); ++i) { for (int j = 0; j < 3; ++j) { ans += dp[i][T][j]; } } ans %= mod; out.print(ans); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.SplittableRandom; 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 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); 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(); int[] a = in.nextIntArray(n); int[] b = a.clone(); b = Arrays.copyOf(b, a.length + 2); b[a.length] = 0; b[a.length + 1] = (int) 2e9; ArrayUtils.sort(b); b = ArrayUtils.uniqueArray(b); SegmentTreeSumL segmentTreeSumL = new SegmentTreeSumL(b.length + 1); SegmentTreeSumL size = new SegmentTreeSumL(b.length + 1); for (int i = 0; i < n; ++i) { segmentTreeSumL.update(Arrays.binarySearch(b, a[i]), a[i]); size.update(Arrays.binarySearch(b, a[i]), 1); } Debug debug = new Debug(out); BigInteger sum = new BigInteger("0"); for (int i = 0; i < n; ++i) { segmentTreeSumL.update(Arrays.binarySearch(b, a[i]), -a[i]); size.update(Arrays.binarySearch(b, a[i]), -1); int indG = ArrayUtils.LowerBound(b, a[i] + 2); indG = Math.min(indG, b.length); long s1 = size.getRangeSum(indG, b.length); long sum1 = segmentTreeSumL.getRangeSum(indG, b.length); //debug.tr("1", s1, sum1); sum = sum.add(BigInteger.valueOf(sum1 - s1 * a[i])); int indL = ArrayUtils.LowerBound(b, a[i] - 1) - 1; indL = Math.max(0, indL); long s2 = size.getRangeSum(0, indL); long sum2 = segmentTreeSumL.getRangeSum(0, indL); //debug.tr("2", s2, sum2); sum = sum.add(BigInteger.valueOf(sum2 - s2 * a[i])); } out.println(sum.toString()); } } static class ArrayUtils { public static int LowerBound(int[] a, int v) { int high = a.length; int low = -1; while (high - low > 1) { int mid = (high + low) >>> 1; if (a[mid] >= v) { high = mid; } else { low = mid; } } return high; } public static int[] sort(int[] a) { a = shuffle(a, new SplittableRandom()); Arrays.sort(a); return a; } public static int[] shuffle(int[] a, SplittableRandom gen) { for (int i = 0, n = a.length; i < n; i++) { int ind = gen.nextInt(n - i) + i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } public static int[] uniqueArray(int[] a) { int n = a.length; int p = 0; for (int i = 0; i < n; i++) { if (i == 0 || a[i] != a[i - 1]) a[p++] = a[i]; } return Arrays.copyOf(a, p); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; private FastReader.SpaceCharFilter filter; 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 int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } private boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class SegmentTreeSumL { long[] lazy; long[] seg; long[] a; int size; int N; public SegmentTreeSumL(long[] a) { this.N = a.length; size = 4 * N; seg = new long[size]; lazy = new long[size]; this.a = a; build(0, N - 1, 0); } public SegmentTreeSumL(int n) { this.N = n; size = 4 * N; seg = new long[size]; lazy = new long[size]; } private void build(int s, int e, int c) { if (s == e) { seg[c] = a[s]; return; } int m = (s + e) >>> 1; build(s, m, 2 * c + 1); build(m + 1, e, 2 * c + 2); seg[c] = seg[2 * c + 1] + seg[2 * c + 2]; } public void update(int index, int value) { update(0, N - 1, 0, index, value); } private void update(int s, int e, int c, int index, int value) { if (s == e) { seg[c] += value; return; } int m = (s + e) >>> 1; if (index <= m) { update(s, m, 2 * c + 1, index, value); } else { update(m + 1, e, 2 * c + 2, index, value); } seg[c] = seg[2 * c + 1] + seg[2 * c + 2]; } public long getRangeSum(int l, int r) { return getRangeSum(0, N - 1, 0, l, r); } private long getRangeSum(int s, int e, int c, int l, int r) { if (s > e || l > r || l > e || r < s) return 0; if (lazy[c] != 0) { if (s != e) { lazy[2 * c + 1] += lazy[c]; lazy[2 * c + 2] += lazy[c]; } seg[c] += (e - s + 1) * (1L) * lazy[c]; lazy[c] = 0; } if (s == e) { return seg[c]; } if (s >= l && e <= r) { return seg[c]; } int m = (s + e) >>> 1; return getRangeSum(s, m, 2 * c + 1, l, r) + getRangeSum(m + 1, e, 2 * c + 2, l, r); } } static class Debug { PrintWriter out; boolean oj; public Debug(PrintWriter out) { oj = System.getProperty("ONLINE_JUDGE") != null; this.out = out; } } }
nlogn
903_D. Almost Difference
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); G1playlist solver = new G1playlist(); solver.solve(1, in, out); out.close(); } static class G1playlist { int mod = 1000000007; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int T = in.scanInt(); int[][] song = new int[n][2]; for (int i = 0; i < n; i++) { song[i][0] = in.scanInt(); song[i][1] = in.scanInt() - 1; } int[][][] dp = new int[T + 1][(1 << n)][3]; for (int i = 0; i < n; i++) if (song[i][0] <= T) { dp[song[i][0]][(1 << i)][song[i][1]] = 1; } for (int t = 0; t <= T; t++) { for (int i = 0; i < (1 << n); i++) { for (int j = 0; j < 3; j++) { if (dp[t][i][j] == 0) continue; for (int k = 0; k < n; k++) { if (((1 << k) & i) == 0 && t + song[k][0] <= T && song[k][1] != j) dp[t + song[k][0]][(1 << k) | i][song[k][1]] = (dp[t + song[k][0]][(1 << k) | i][song[k][1]] + dp[t][i][j]) % mod; } } } } long ans = 0; for (int i = 0; i < (1 << n); i++) { for (int j = 0; j < 3; j++) { ans = (ans + dp[T][i][j]) % mod; } } out.println(ans); } } 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
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class Noldbach { public Scanner in = new Scanner(System.in); public PrintStream out = System.out; public boolean[] yes; public int n, k; public void main() { n = in.nextInt(); k = in.nextInt(); genPrime(); int i; yes = new boolean[n+1]; int x; for(i=0;i+1<prime.length;++i) { x = prime[i]+prime[i+1]+1; if(x <= n && fac[x] == x) yes[x] = true; } int count = 0; for(i=0;i<yes.length;++i) if(yes[i]) ++count; out.println((count>=k?"YES":"NO")); }//end public void main() //Generating Primes public int N = 100000+100; public int[] fac, rest; public int[] prime; public void genPrime() { ArrayList<Integer> ap = new ArrayList<Integer>(); fac = new int[N]; rest = new int[N]; int x,y; for(x=0;x<N;++x) { fac[x] = x; rest[x] = 1; } for(x=2;x<N;++x) if(fac[x]==x) { ap.add(x); for(y=x+x;y<N;y+=x) if(fac[y]==y) { fac[y] = x; rest[y] = y/x; } } prime = new int[ap.size()]; for(int i=0;i<prime.length;++i) prime[i] = ap.get(i); } public static void main(String[] args) { (new Noldbach()).main(); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n = scan.nextLong(); long s = scan.nextLong(); long low = 0; long high = n + 1; while (high-low>1) { long sum = 0; long mid = (high + low) / 2; long value = findSum(mid, sum); if (mid - value >= s) high = mid; else low = mid; } System.out.println(n - high + 1); scan.close(); } public static long findSum(long n, long sum) { if (n == 0) return sum; return findSum(n / 10, sum + n % 10); } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class F{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair { int l; int r; Pair(int l,int r) { this.l = l; this.r = r; } } public static void main(String[] args) { OutputStream outputStream = System.out; FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(outputStream); int n = sc.nextInt(); int a[] = new int[n]; Pair pr; HashMap<Long,ArrayList> hm = new HashMap<>(); ArrayList<Pair> ar; for(int i = 0; i < n; i++) { a[i] = sc.nextInt(); } long sum = 0; for(int r = 0; r < n; r++) { sum = 0; for(int l = r; l >= 0; l--) { sum += a[l]; if(!hm.containsKey(sum)) { ar = new ArrayList<>(); ar.add(new Pair(l,r)); hm.put(sum,ar); } else { ar = hm.get(sum); ar.add(new Pair(l,r)); hm.put(sum,ar); } } } int count = 0; int maxCount = 0; long maxSum = 0; for(Map.Entry<Long,ArrayList> entry:hm.entrySet()) { sum = entry.getKey(); ar = entry.getValue(); count = 0; int r = -1; for(int i = 0; i < ar.size(); i++) { if(ar.get(i).l > r) { count++; r = ar.get(i).r; } } if(count > maxCount) { maxCount = count; maxSum = sum; } } ar = hm.get(maxSum); out.println(maxCount); //out.println((ar.get(0).l+1)+" "+(ar.get(0).r+1)); int r = -1; for(int i = 0; i < ar.size(); i++) { if(ar.get(i).l > r) { out.println((ar.get(i).l+1) +" "+(ar.get(i).r+1)); r = ar.get(i).r; } } out.close(); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.Locale; import java.util.Scanner; public class PipelineSolver { private long n; private long k; public static void main(String[] args) { PipelineSolver solver = new PipelineSolver(); solver.readData(); int solution = solver.solve(); solver.print(solution); } private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } private int lcm(int a, int b) { return a * b / gcd(a, b); } private void print(int[] values) { StringBuilder builder = new StringBuilder(); for (int value : values) { builder.append(value); builder.append(" "); } print(builder); } private void print(Object value) { System.out.println(value); } private void print(boolean value) { System.out.println(value ? "YES" : "NO"); } private void print(int value) { System.out.println(value); } private void print(long value) { System.out.println(value); } private void print(double value) { System.out.printf(Locale.ENGLISH, "%.10f", value); } private int[] getDigits(int number) { int[] digits = new int[10]; int index = digits.length - 1; int digitsCount = 0; while (number > 0) { digits[index] = number % 10; number /= 10; index--; digitsCount++; } int[] result = new int[digitsCount]; System.arraycopy(digits, digits.length - digitsCount, result, 0, digitsCount); return result; } private int[] readArray(Scanner scanner, int size) { int[] result = new int[size]; for (int i = 0; i < size; i++) { result[i] = scanner.nextInt(); } return result; } private void readData() { Scanner scanner = new Scanner(System.in); n = scanner.nextLong(); k = scanner.nextLong(); } private int solve() { if (n == 1) { return 0; } if (n <= k) { return 1; } int result; long l; long d = (5 - 2 * k) * (5 - 2 * k) - 4 * (2 * n - 4 * k + 4); if (d < 0) { result = -1; } else { l = Math.min(Math.max((int)((2 * k - 3 - Math.sqrt(d)) / 2), 0), Math.max((int)((2 * k - 3 + Math.sqrt(d)) / 2), 0)); long difference = n - k * (l + 1) + l * (l + 3) / 2; if (l > k - 2) { result = -1; } else if (l == k - 2) { result = difference == 0 ? (int) (l + 1) : -1; } else { result = (int) (l + 1 + (difference == 0 ? 0 : 1)); } } return result; } }
logn
287_B. Pipeline
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class E_fast { static int g[][]; static int n, m; static char[] s; static int dp[], inf = (int) 2e9; static int cost[][]; public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); n = in.nextInt(); m = in.nextInt(); s = in.next().toCharArray(); g = new int[m][m]; for (int i = 1; i < n; i++) { int x = s[i - 1] - 'a', y = s[i] - 'a'; if (x != y) { g[x][y]++; g[y][x]++; } } cost = new int[m][1 << m]; for (int i = 0; i < m; i++) { int w = 0; for (int j = 0; j < m; j++) w += g[i][j]; pre(i, 0, 0, -w); } dp = new int[1 << m]; Arrays.fill(dp, -1); pw.println(solve(0, 0)); pw.close(); } static void pre(int x, int pos, int mask, int w) { if (pos >= m) { cost[x][mask] = w; return; } pre(x, pos + 1, mask, w); pre(x, pos + 1, set(mask, pos), w + 2 * g[x][pos]); } static int solve(int pos, int mask) { if (pos >= m) return 0; if (dp[mask] != -1) return dp[mask]; int min = inf; for (int i = 0; i < m; i++) { if (!check(mask, i)) { int res = cost[i][mask] * pos + solve(pos + 1, set(mask, i)); min = min(min, res); } } return dp[mask] = min; } static boolean check(int N, int pos) { return (N & (1 << pos)) != 0; } static int set(int N, int pos) { return N = N | (1 << pos); } static int reset(int N, int pos) { return N = N & ~(1 << pos); } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() throws Exception { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public String nextLine() throws Exception { String line = null; tokenizer = null; line = reader.readLine(); return line; } public int nextInt() throws Exception { return Integer.parseInt(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.util.*; import java.io.*; public class Solution { public static void main(String [] args) throws IOException { PrintWriter pw=new PrintWriter(System.out);//use pw.println() not pw.write(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(br.readLine()); /* inputCopy 5 3 xyabd outputCopy 29 inputCopy 7 4 problem outputCopy 34 inputCopy 2 2 ab outputCopy -1 inputCopy 12 1 abaabbaaabbb outputCopy 1 */ int n=Integer.parseInt(st.nextToken()); int k=Integer.parseInt(st.nextToken()); st=new StringTokenizer(br.readLine()); String str=st.nextToken(); char [] arr=str.toCharArray(); Arrays.sort(arr); int weight=arr[0]-96; char a=arr[0]; int included=1; for(int i=1;i<arr.length;++i) { if(included==k) break; char c=arr[i]; if(c-a<2) continue; weight+=arr[i]-96; ++included; a=arr[i]; } if(included==k) pw.println(weight); else pw.println(-1); pw.close();//Do not forget to write it after every program return statement !! } } /* →Judgement Protocol Test: #1, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 5 3 xyabd Output 29 Answer 29 Checker Log ok 1 number(s): "29" Test: #2, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 7 4 problem Output 34 Answer 34 Checker Log ok 1 number(s): "34" Test: #3, time: 139 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 2 2 ab Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #4, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 12 1 abaabbaaabbb Output 1 Answer 1 Checker Log ok 1 number(s): "1" Test: #5, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 13 qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa Output 169 Answer 169 Checker Log ok 1 number(s): "169" Test: #6, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 14 qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #7, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 1 1 a Output 1 Answer 1 Checker Log ok 1 number(s): "1" Test: #8, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 1 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Output 1 Answer 1 Checker Log ok 1 number(s): "1" Test: #9, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 2 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #10, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 13 13 uwgmkyqeiaocs Output 169 Answer 169 Checker Log ok 1 number(s): "169" Test: #11, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 13 13 hzdxpbfvrltnj Output 182 Answer 182 Checker Log ok 1 number(s): "182" Test: #12, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 1 1 n Output 14 Answer 14 Checker Log ok 1 number(s): "14" Test: #13, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 10 8 smzeblyjqw Output 113 Answer 113 Checker Log ok 1 number(s): "113" Test: #14, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 20 20 tzmvhskkyugkuuxpvtbh Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #15, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 30 15 wjzolzzkfulwgioksfxmcxmnnjtoav Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #16, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 40 30 xumfrflllrrgswehqtsskefixhcxjrxbjmrpsshv Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #17, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 31 ahbyyoxltryqdmvenemaqnbakglgqolxnaifnqtoclnnqiabpz Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #18, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 10 7 iuiukrxcml Output 99 Answer 99 Checker Log ok 1 number(s): "99" Test: #19, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 38 2 vjzarfykmrsrvwbwfwldsulhxtykmjbnwmdufa Output 5 Answer 5 Checker Log ok 1 number(s): "5" Test: #20, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 12 6 fwseyrarkwcd Output 61 Answer 61 Checker Log ok 1 number(s): "61" Test: #21, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 2 2 ac Output 4 Answer 4 Checker Log ok 1 number(s): "4" Test: #22, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 1 1 c Output 3 Answer 3 Checker Log ok 1 number(s): "3" Test: #23, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 2 2 ad Output 5 Answer 5 Checker Log ok 1 number(s): "5" Test: #24, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER Input 2 1 ac Output -1 Answer 1 Checker Log wrong answer 1st number */
linear
1011_A. Stages
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class MAIN { public static void main(String args[]) { Scanner sn=new Scanner(System.in); int n,n1,n2,n3; int arr[]={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}; n=sn.nextInt(); if(n==2) { n1=n2=1; n3=0; } else if(n==1) { n3=n2=0; n1=1; } else if(n==0) { n1=n2=n3=0; } else if(n==3) { n1=n2=n3=1; } else { int index=bsearch(arr,0,arr.length-1,n); n1=arr[index-1]; n2=arr[index-3]; n3=arr[index-4]; } System.out.println(n3+" "+n2+" "+n1); } static int bsearch(int arr[],int l,int h,int n) { if(l>h) return -1; int mid=(l+h)/2; if(n==arr[mid]) return mid; else if(n>arr[mid]) return(bsearch(arr,mid+1,h,n)); else return(bsearch(arr,l,mid-1,n)); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner scan=new Scanner(System.in); long x=scan.nextLong(); long k=scan.nextLong(); long MOD=1000000007; if(x==0){System.out.println(0);return;} x%=MOD; long a=(new Num()).pow(2L,k+1); long b=(new Num()).pow(2L,k); long res=(a*x)%MOD-b+1; if(res<0){res+=MOD;} System.out.println(res%MOD); } } class Num{ long MOD=1000000007; long pow(long x,long k){ long base=x%MOD; long res=1; while(k>0){ if((k&1)==1){ res=(res*base)%MOD; } base=(base*base)%MOD; k>>=1; } return res; } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.*; import java.util.*; public class utkarsh{ BufferedReader br; PrintWriter out; int game(int s, int mid, int e, int[] a){ int i, j, n, m; n = mid - s + 1; m = e - mid; int b[] = new int[n]; int c[] = new int[m]; for(i = 0; i < n; i++) b[i] = a[s + i]; for(j = 0; j < m; j++) c[j] = a[mid + 1 + j]; i = j = 0; int ans = 0; for(int k = s; k <= e; k++){ if(i == n){ a[k] = c[j++]; }else if(j == m){ a[k] = b[i++]; }else{ if(b[i] < c[j]){ a[k] = b[i++]; }else{ a[k] = c[j++]; ans += n - i; } } } return ans; } int play(int s, int e, int[] a){ if(s >= e) return 0; int m = (s + e) >> 1; return play(s, m, a) + play(m+1, e, a) + game(s, m, e, a); } void solve(){ br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int i, j, k, l, r, n; n = ni(); int a[] = new int[n]; int d[] = new int[n]; for(i = 0; i < n; i++) { a[i] = ni(); d[i] = a[i]; } int ans = (play(0, n-1, d) & 1); int q = ni(); while(q-- > 0){ l = ni(); r = ni(); ans ^= ((r - l + 1) * (r - l) / 2); //out.println(ans); if((ans & 1) > 0) out.println("odd"); else out.println("even"); } out.flush(); } int ni(){ return Integer.parseInt(ns()); } String ip[]; int len, sz; String ns(){ if(len >= sz){ try{ ip = br.readLine().split(" "); len = 0; sz = ip.length; }catch(IOException e){ throw new InputMismatchException(); } if(sz <= 0) return "-1"; } return ip[len++]; } public static void main(String[] args){ new utkarsh().solve(); } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; import java.io.*; public class Main { static long mod = 1000000007; static int INF = 1000000000; public static void main(String[] args){ FastScanner scanner = new FastScanner(); int n = scanner.nextInt(); int m = scanner.nextInt(); String s = scanner.next(); int[][] cnt = new int[20][20]; for(int i = 0; i < n-1; i++){ cnt[s.charAt(i)-'a'][s.charAt(i+1)-'a']++; cnt[s.charAt(i+1)-'a'][s.charAt(i)-'a']++; } //dp[i]:= 文字列i(この中に同一文字は含まれない)を作った時のコストの最小値 int[] dp = new int[(1<<m)]; for(int i = 0; i < (1<<m); i++){ dp[i] = INF; } dp[0] = 0; for(int i = 0; i < (1<<m); i++){ int cost = 0; for(int j = 0; j < m; j++){ if((i>>j & 1) == 0){ for(int k = 0; k < m; k++){ if((~i>>k & 1) == 0){ cost += cnt[j][k]; } } } } for(int j = 0; j < m; j++){ dp[i|1<<j] = Math.min(dp[i|1<<j],dp[i]+cost); } } System.out.println(dp[(1<<m)-1]); } static class BIT{ int n; int[] bit; public BIT(int n){ this.n = n; bit = new int[n+1]; } void add(int idx, int val){ for(int i = idx+1; i <= n; i += i&(-i)) bit[i-1] += val; } int sum(int idx){ int res = 0; for(int i = idx+1; i > 0; i -= i&(-i)) res += bit[i-1]; return res; } int sum(int begin, int end){ if(begin == 0) return sum(end); return sum(end)-sum(begin-1); } } static class Pair implements Comparable<Pair>{ int first, second; Pair(int a, int b){ first = a; second = b; } @Override public boolean equals(Object o){ if (this == o) return true; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return first == p.first && second == p.second; } @Override public int compareTo(Pair p){ return first == p.first ? second - p.second : first - p.first; //firstで昇順にソート //return (first == p.first ? second - p.second : first - p.first) * -1; //firstで降順にソート //return second == p.second ? first - p.first : second - p.second;//secondで昇順にソート //return (second == p.second ? first - p.first : second - p.second)*-1;//secondで降順にソート //return first * 1.0 / second > p.first * 1.0 / p.second ? 1 : -1; // first/secondの昇順にソート //return first * 1.0 / second < p.first * 1.0 / p.second ? 1 : -1; // first/secondの降順にソート //return second * 1.0 / first > p.second * 1.0 / p.first ? 1 : -1; // second/firstの昇順にソート //return second * 1.0 / first < p.second * 1.0 / p.first ? 1 : -1; // second/firstの降順にソート //return Math.atan2(second, first) > Math.atan2(p.second, p.first) ? 1 : -1; // second/firstの昇順にソート //return first + second > p.first + p.second ? 1 : -1; //first+secondの昇順にソート //return first + second < p.first + p.second ? 1 : -1; //first+secondの降順にソート //return first - second < p.first - p.second ? 1 : -1; //first-secondの降順にソート } } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next());} } }
np
1238_E. Keyboard Purchase
CODEFORCES
import sun.reflect.generics.tree.Tree; import java.io.*; import java.math.BigInteger; import java.net.Inet4Address; import java.util.*; public class l { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static long mod = (int) (1e9 + 7); static int n; static StringBuilder sol; static class pair implements Comparable<pair> { int L,R; public pair( int x,int y) { L=x;R=y; } public int compareTo(pair o) { if (L!=o.L)return L-o.L; return o.R-R; } public String toString(){ return L+" "+R; } } static boolean is; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); //FileWriter f = new FileWriter("C:\\Users\\Ibrahim\\out.txt"); PrintWriter pw = new PrintWriter(System.out); int m = sc.nextInt(); int n = sc.nextInt(); int q = sc.nextInt(); TreeSet<Integer>length= new TreeSet<>(); length.add(0); length.add(n); TreeSet<Integer>width= new TreeSet<>(); width.add(0); width.add(m); TreeMap<Integer,Integer>len= new TreeMap<>(); len.put(n,1); TreeMap<Integer,Integer>wid= new TreeMap<>(); wid.put(m,1); while (q-->0){ String t= sc.next(); if (t.equals("H")) { int x = sc.nextInt(); int k1 = length.ceiling(x); int k2 = length.floor(x); if (x != k1) { int s = k1 - k2; int con = len.get(s); if (con == 1) len.remove(s); else len.put(s, con - 1); len.put((k1 - x), len.getOrDefault((k1 - x), 0) + 1); len.put((x - k2), len.getOrDefault((x - k2), 0) + 1); length.add(x); } } else { int x = sc.nextInt(); int k1 = width.ceiling(x); int k2 = width.floor(x); if (x != k1) { int s = k1 - k2; //System.out.println(s+" "+k1+" "+k2); int con = wid.get(s); if (con == 1) wid.remove(s); else wid.put(s, con - 1); wid.put((k1 - x), wid.getOrDefault((k1 - x), 0) + 1); wid.put((x - k2), wid.getOrDefault((x - k2), 0) + 1); width.add(x); } } pw.println(1l*len.lastKey()*wid.lastKey()); } pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
nlogn
527_C. Glass Carving
CODEFORCES
import java.util.Scanner; public class B2 { public static void main (String args[]){ Scanner in = new Scanner(System.in); long n = in.nextLong(); long k = in.nextLong(); long upn = k; long tmp=upn; if(n==1){ System.out.println(0); return; } if(n<=k){ System.out.println(1); return; } //--- if(!bS(n, k, upn)){ System.out.println(-1); return; } boolean flag = false; while(bS(n, k, upn)){ tmp = upn; flag = true; upn=5*upn/6; if(tmp==upn) break; } long ans = tmp; if(!flag) upn=0; for(int i = (int)tmp;i>=upn;i--){ if(bS(n, k, i)){ ans=i; } else break; } System.out.println(ans); } static boolean bS(long key,long k ,long n) { long pipe = (n * (k-n+k+1))/2; pipe = pipe - n+1; if(pipe>=key){ return true; } else return false; } }
logn
287_B. Pipeline
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main { public static void main(String ...args) throws Throwable { Scanner in = new Scanner(System.in); String init = in.nextLine(); HashSet<String> h = new HashSet<String>(); for (int len = init.length() - 1; len >= 1; --len) { h.clear(); for (int pos = 0; pos + len <= init.length(); ++pos) { String now = init.substring(pos, pos + len); if (h.contains(now)) { System.out.println(len); return; } h.add(now); } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.HashMap; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author MaxHeap */ 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); F1SameSumBlocksEasy solver = new F1SameSumBlocksEasy(); solver.solve(1, in, out); out.close(); } static class F1SameSumBlocksEasy { Map<Long, List<IntPair>> sums = new HashMap<>(); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long[] arr = in.nextLongArray(n); long[] pref = ArrayUtils.prefixSum(arr); for (int i = 0; i < n; ++i) { for (int j = i; j >= 0; --j) { long sum = pref[i + 1] - pref[j]; if (sums.containsKey(sum)) { sums.get(sum).add(Factories.makeIntPair(j, i)); } else { List<IntPair> pairs = new ArrayList<>(); pairs.add(Factories.makeIntPair(j, i)); sums.put(sum, pairs); } } } int best = 0; List<IntPair> res = new ArrayList<>(); for (long sum : sums.keySet()) { List<IntPair> pairs = sums.get(sum); List<IntPair> temp = new ArrayList<>(); int last = -1; for (IntPair cur : pairs) { if (cur.first > last) { last = cur.second; temp.add(cur); } } if (temp.size() > best) { best = temp.size(); res = temp; } } out.println(best); for (IntPair pair : res) { out.println((pair.first + 1) + " " + (pair.second + 1)); } } } static class ArrayUtils { public static long[] prefixSum(long[] arr) { long[] acc = new long[arr.length + 1]; for (int i = 1; i <= arr.length; ++i) { acc[i] = acc[i - 1] + arr[i - 1]; } return acc; } } static interface FastIO { } static final class Factories { private Factories() { } public static IntPair makeIntPair(int first, int second) { return new IntPair(first, second); } } static class IntPair implements Comparable<IntPair> { public int first; public int second; public IntPair() { first = second = 0; } public IntPair(int first, int second) { this.first = first; this.second = second; } public int compareTo(IntPair a) { if (first == a.first) { return Integer.compare(second, a.second); } return Integer.compare(first, a.first); } public String toString() { return "<" + first + ", " + second + ">"; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntPair a = (IntPair) o; if (first != a.first) { return false; } return second == a.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } } static class InputReader implements FastIO { private InputStream stream; private static final int DEFAULT_BUFFER_SIZE = 1 << 16; private static final int EOF = -1; private byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == EOF) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return EOF; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public long nextLong() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } long res = 0; while (c >= 48 && c <= 57) { res *= 10L; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.*; import java.util.*; public class a{ static BufferedReader br; static PrintWriter pw; static int N, M, K; static ArrayList<Integer> graph[][]; public static void main(String args[]) throws IOException{ br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); K = Integer.parseInt(st.nextToken()); if(K % 2 == 1){ for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ pw.print("-1 "); } pw.println(); } br.close(); pw.close(); return; } graph = new ArrayList[N][M]; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ graph[i][j] = new ArrayList<Integer>(); } } for(int i = 0; i < N; i++){ st = new StringTokenizer(br.readLine()); for(int j = 0; j < M-1; j++){ int w = Integer.parseInt(st.nextToken()); graph[i][j].add(w); } } for(int i = 0; i < N; i++){ graph[i][M-1].add(0); } for(int i = 0; i < N-1; i++){ st = new StringTokenizer(br.readLine()); for(int j = 0; j < M; j++){ int w = Integer.parseInt(st.nextToken()); graph[i][j].add(w); } } K /= 2; for(int i = 0; i < M; i++) graph[N-1][i].add(0); long ans[][][] = new long[K+1][N][M]; for(int i = 0; i < N; i++){ Arrays.fill(ans[0][i], 0); } for(int i = 1; i <= K; i++){ for(int x = 0; x < N; x++){ for(int y = 0; y < M; y++){ long cur = (long)1e17; if(x < N-1){ cur = (long)Math.min(cur, graph[x][y].get(1) + ans[i-1][x+1][y]); } if(y < M-1){ cur = (long)Math.min(cur, graph[x][y].get(0) + ans[i-1][x][y+1]); } if(x > 0){ cur = (long)Math.min(cur, graph[x-1][y].get(1) + ans[i-1][x-1][y]); //pw.println("CUR: " + cur + " X: " + x + " Y: " + y + " get = " + graph[x-1][y].get(0)); } if(y > 0){ cur = (long)Math.min(cur, graph[x][y-1].get(0) + ans[i-1][x][y-1]); } ans[i][x][y] = cur; } } } for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ pw.print(ans[K][i][j] * 2 + " "); } pw.println(); } br.close(); pw.close(); } static class pii implements Comparable<pii>{ int f, s, k; pii(int f, int s, int k){ this.f = f; this.s = s; this.k = k; } public int compareTo(pii x){ return Integer.compare(f, x.f); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.util.Arrays; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author hheng */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int N = in.nextInt(); int k = in.nextInt(); Team[] t = new Team[N]; for (int i=0; i<N; i++) t[i] = new Team(in.nextInt(), in.nextInt()); Arrays.sort(t); int p_k = t[k-1].p, t_k = t[k-1].t; int count = 0; for (int i=0; i<N; i++) if (t[i].p==p_k && t[i].t ==t_k) count++; out.println(count); } } class Team implements Comparable<Team>{ int p, t; Team(int a, int b) { p=a; t=b;} public int compareTo(Team g) { if (p < g.p) return 1; if (p > g.p) return -1; if (t < g.t) return -1; if (t > g.t) return 1; return 0; } }
nlogn
166_A. Rank List
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Solution implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer st; int[] x; int[] y; int n; int X, Y; int[] d; int[][] dist; int sqr(int a) { return a * a; } int dist(int X, int Y, int i) { return sqr(X - x[i]) + sqr(Y - y[i]); } int[] dp; byte[][] pred; int rec(int mask) { if (dp[mask] == -1) { int res = 1 << 29; boolean ok = false; for (int i = 0; i < n; ++i) if ((mask & (1 << i)) > 0) { ok = true; int mm = mask & ~(1 << i); for (int j = i; j < n; j++) if ((mask & (1 << j)) > 0) { int nmask = mm & ~(1 << j); int a = rec(nmask) + d[i] + d[j] + dist[i][j]; if (a < res) { res = a; pred[0][mask] = (byte) (i); pred[1][mask] = (byte) (j); } } break; } if (!ok) res = 0; dp[mask] = res; } return dp[mask]; } void solve() throws IOException { X = ni(); Y = ni(); n = ni(); // if (n > 5) // return; x = new int[n]; y = new int[n]; for (int i = 0; i < n; i++) { x[i] = ni(); y[i] = ni(); } d = new int[n]; dist = new int[n][n]; for (int i = 0; i < n; ++i) d[i] = dist(X, Y, i); for (int i = 0; i < n; ++i) for (int j = 0; j < n; j++) { dist[i][j] = dist(x[i], y[i], j); } pred = new byte[2][1 << n]; dp = new int[1 << n]; Arrays.fill(dp, -1); out.println(rec((1 << n) - 1)); int a = (1 << n) - 1; while (a > 0) { if (pred[0][a] != pred[1][a]) out.print(0 + " " + (pred[0][a] + 1) + " " + (pred[1][a] + 1) + " "); else out.print(0 + " " + (pred[0][a] + 1) + " "); int na = a & ~(1 << pred[0][a]); na &= ~(1 << pred[1][a]); a = na; } out.println(0); } public Solution() throws IOException { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int ni() throws IOException { return Integer.valueOf(ns()); } long nl() throws IOException { return Long.valueOf(ns()); } double nd() throws IOException { return Double.valueOf(ns()); } public static void main(String[] args) throws IOException, InterruptedException { Thread th = new Thread(null, new Solution(), "", 536870912); th.start(); th.join(); } @Override public void run() { try { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Exception e) { // TODO: handle exception } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.awt.Point; public class CodeForces { static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final long MOD = 1000000009; long power(long a, long b) { long res = 1; while (b > 0) { if ((b & 1) == 1) { res *= a; if (res >= MOD) res %= MOD; } a *= a; if (a >= MOD) a %= MOD; b >>= 1; } return res; } void runCase(int caseNum) throws IOException { long n = nextLong(); long m = nextLong(); long k = nextLong(); if (n - m >= n / k) { System.out.println(m); return; } long res = 0; long rem = (k - 1) * (n - m); m -= rem; long bound = m / k; res = (power(2, bound + 1) + MOD - 2) % MOD; res *= k; res %= MOD; // for (long i = 0; i < bound; ++i) { // res += k; // res <<= 1; // if (res >= MOD) // res %= MOD; // } res += rem; res += m % k; res %= MOD; System.out.println(res); } public static void main(String[] args) throws IOException { if (ONLINE_JUDGE){ System.out.println(); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(System.out); //out = new PrintWriter("output.txt"); } new CodeForces().runIt(); out.flush(); out.close(); return; } static BufferedReader in; private StringTokenizer st; static PrintWriter out; static int pos; static String curInput = ""; String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void runIt() throws IOException { st = new StringTokenizer(""); // int N = nextInt(); // for (int i = 0; i < N; i++) { // runCase(i + 1); // } runCase(0); out.flush(); } }
logn
338_A. Quiz
CODEFORCES
import java.util.Scanner; public class B { public static final boolean DEBUG = false; Scanner sc; public void debug(Object o) { if (DEBUG) { int ln = Thread.currentThread().getStackTrace()[2].getLineNumber(); String fn = Thread.currentThread().getStackTrace()[2].getFileName(); System.out.println("(" + fn + ":" + ln+ "): " + o); } } public void pln(Object o) { System.out.println(o); } long getNumber(int x, int y, int n, int m) { int n1 = Math.max(0, x + m - n); int n2 = Math.max(0, y + m - n); int n3 = Math.max(0, 1 - (x - m)); int n4 = Math.max(0, 1 - (y - m)); int n12 = Math.max(0, n1 + n2 - m - 1); int n23 = Math.max(0, n2 + n3 - m - 1); int n34 = Math.max(0, n3 + n4 - m - 1); int n41 = Math.max(0, n4 + n1 - m - 1); // debug(n1 + " " + n2 + " " + n3 + " " + n4); // debug(n12 + " " + n23 + " " + n34 + " " + n41); int m1 = m+1; long nr = 1 + ((long)m1)*m1*2 - m1*2; nr -= ((long)n1)*n1 + ((long)n2)*n2 + ((long)n3)*n3 + ((long)n4)*n4; nr += ((long)n12)*(n12+1)/2 + ((long)n23)*(n23+1)/2 + ((long)n34)*(n34+1)/2 + ((long)n41)*(n41+1)/2; return nr; } public void run() { // pln(getNumber(1, 1, 10000, 10000000)); // pln(getNumber(1000, 1000, 1000, 1000000)); // if (true) return; sc = new Scanner(System.in); int n = sc.nextInt(); int x = sc.nextInt(); int y = sc.nextInt(); int c = sc.nextInt(); if (c <= 1) { pln(0); return; } int ll = 0; int rr = 2*n+20; while(true) { int m = (ll+rr) / 2; if (getNumber(x, y, n, m) >= c) { rr = m; } else { ll = m; } // debug(ll + " " + rr); if (rr - ll < 3) { for (int m2=ll; m2<=rr; m2++) { if (getNumber(x, y, n, m2) >= c) { pln(m2); return; } } } } } public static void main(String[] args) { B t = new B(); t.run(); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line = stdin.readLine(); String[] prms = line.split(" "); long a = Long.parseLong(prms[0]); long b = Long.parseLong(prms[1]); long cnt = 0; while (a > 0 && b > 0) { if (a >= b) { cnt += a / b; a = a % b; } long c = a; a = b; b = c; } System.out.println(cnt); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; public class Solution { private static final long MODULUS = 1000000007; private static final boolean DEBUG = false; private static long modularPow(long base, long exponent, long modulus) { long result = 1; while (exponent > 0) { if (exponent % 2 == 1) { result = (result * base) % modulus; } exponent >>= 1; base = (base * base) % modulus; } return result; } public static void main(String[] args) throws FileNotFoundException { long beginTime = System.nanoTime(); InputStream is = DEBUG ? new FileInputStream("resources/codeforcesedu43/ProblemC-1.in") : System.in; try (Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(is)))) { long x = scanner.nextLong(); long k = scanner.nextLong(); if (x != 0) { x = (2 * x - 1) % MODULUS; long twoPowK = modularPow(2, k, MODULUS); x = (x * twoPowK + 1) % MODULUS; } System.out.println(x % 1000000007); } System.err.println( "Done in " + ((System.nanoTime() - beginTime) / 1e9) + " seconds."); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Locale; import java.io.OutputStream; import java.io.PrintWriter; import java.util.RandomAccess; import java.util.AbstractList; import java.io.Writer; import java.util.List; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.InputMismatchException; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Jacob Jiang */ 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 { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] b = a.clone(); ArrayUtils.safeSort(b); int diff = 0; for (int i = 0; i < n; i++) { if (a[i] != b[i]) diff++; } out.println(diff <= 2 ? "YES" : "NO"); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] nextIntArray(int count) { int[] result = new int[count]; for (int i = 0; i < count; i++) { result[i] = nextInt(); } return result; } } class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(String x) { writer.println(x); } public void close() { writer.close(); } } class ArrayUtils { public static List<Integer> asList(int[] array) { return new IntList(array); } private static class IntList extends AbstractList<Integer> implements RandomAccess { int[] array; private IntList(int[] array) { this.array = array; } public Integer get(int index) { return array[index]; } public Integer set(int index, Integer element) { int result = array[index]; array[index] = element; return result; } public int size() { return array.length; } } public static void safeSort(int[] array) { Collections.shuffle(asList(array)); Arrays.sort(array); } }
nlogn
220_A. Little Elephant and Problem
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, root = 3; DecimalFormat df = new DecimalFormat("0.0000000000000"); double eps = 1e-9; 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 << 28).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{ int n = ni(); int[] f1 = new int[9], f2 = new int[9]; MyHashSet<String> set = new MyHashSet<>(); for(int i = 0; i< n; i++){ String s = n(); set.add(s); f1[s.length()]++; } int[] f = new int[4]; for(int i = 0; i< n; i++){ String s = n(); if(set.remove(s))continue; else f[s.length()-1]++; } int ans = 0; for(int i = 0; i< 4; i++)ans+=f[i]; pn(ans); } class MyHashSet<T>{ private int size; private HashMap<T, Integer> map; public MyHashSet(){ size = 0; map = new HashMap<>(); } public int size(){return size;} public void add(T t){ size++; map.put(t, map.getOrDefault(t, 0)+1); } public int cnt(T t){return map.getOrDefault(t,0);} public boolean remove(T t){ if(!map.containsKey(t))return false; size--; int c = map.get(t); if(c==1)map.remove(t); else map.put(t, c-1); return true; } } 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; } 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; } } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rb_wahid */ 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); ASubtractions solver = new ASubtractions(); solver.solve(1, in, out); out.close(); } static class ASubtractions { int sub(int a, int b) { if (a % b == 0) return a / b; else return a / b + sub(b, a % b); } public void solve(int testNumber, InputReader in, OutputWriter out) { int t = in.nextInt(); int a, b; while (t-- > 0) { a = in.nextInt(); b = in.nextInt(); out.println(sub(a, b)); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
constant
267_A. Subtractions
CODEFORCES
import java.io.*; import java.util.*; public class Main { 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 static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int best = 1; int bestTime = Integer.MAX_VALUE; for(int i=0;i<n;i++) { int time; int a = sc.nextInt(); time = (a%n==0 || a%n<=i) ? a/n : (a+n)/n; if(time < bestTime) { best = i + 1; bestTime = time; } } pw.println(best); pw.close(); } }
linear
996_B. World Cup
CODEFORCES
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class D911 { public static long total = 0; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); ArrayList<Integer> temp = new ArrayList<>(); int[] ar = new int[n]; int[] memo = new int[n]; for (int i = 0; i < n; i++) { int t = in.nextInt(); int index = -1*Collections.binarySearch(temp, t)-1; temp.add(index, t); ar[i] = t; memo[i] = i - index; total += memo[i]; } int m = in.nextInt(); for (int i = 0; i < m; i++) { // int a = in.nextInt() - 1, b = in.nextInt() - 1; // query(ar, memo, in.nextInt() - 1, in.nextInt() - 1); total += (-1*(in.nextInt() - 1 - in.nextInt() + 1) + 1) / 2; System.out.println(total%2 == 0 ? "even" : "odd"); } } public static void query(int[] ar, int[] memo, int a, int b) { if (a >= b) { return; } if (ar[a] < ar[b]) { memo[a]++; total++; } else { memo[b]--; total--; } int t = ar[a]; ar[b] = ar[a]; ar[b] = t; t = memo[a]; memo[b] = memo[a]; memo[b] = t; query(ar, memo, a + 1, b - 1); } }
quadratic
911_D. Inversion Counting
CODEFORCES