src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.util.*; import java.math.*; public class Main { static final long MOD = 1000000007L; public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k = scan.nextInt(); int res = -1; int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) { arr[i] = scan.nextInt(); } BitSet bits = new BitSet(); int count = 0; int end = -1; for (int i = 0; i < arr.length; i++) { if (!bits.get(arr[i])) { bits.set(arr[i]); count++; if (count == k) { end = i; break; } } } if (end == -1) { System.out.print("-1 -1"); return; } bits = new BitSet(); count = 0; int start = end; while (start >= 0) { if (!bits.get(arr[start])) { bits.set(arr[start]); count++; if (count == k) { break; } } start--; } System.out.println((start + 1) + " " + (end + 1)); } }
linear
224_B. Array
CODEFORCES
import java.util.Optional; import java.util.Scanner; import java.util.StringJoiner; public class Main { public static void main(String[] args) { Main main = new Main(); main.solveC(); } private void solveA() { Scanner sc = new Scanner(System.in); String str = sc.next(); long answer = str.chars().filter( asc -> asc == 'a' || asc == 'i' || asc == 'u' || asc == 'e' || asc == 'o' || asc == '1' || asc == '3' || asc == '5' || asc == '7' || asc == '9').count(); System.out.println(answer); } private void solveB() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); sc.nextLine(); char[][] map = new char[N + 2][M + 2]; map[0] = new char[M + 2]; map[N + 1] = new char[M + 2]; int s_r = -1; int s_c = -1; for (int c = 0; c < M + 2; c++) { map[0][c] = '#'; map[N + 1][c] = '#'; } for (int r = 1; r <= N; r++) { map[r][0] = '#'; String line = sc.nextLine(); for (int c = 1; c <= M; c++) { map[r][c] = line.charAt(c - 1); if (map[r][c] == 'S') { s_r = r; s_c = c; } } map[r][M + 1] = '#'; } String inst = sc.next(); long ans = 0L; for (int left = 0; left < 4; left++) { for (int up = 0; up < 4; up++) { for (int right = 0; right < 4; right++) { for (int down = 0; down < 4; down++) { if (left == up || left == right || left == down || up == right || up == down || right == down) { continue; } int r_r = s_r; int r_c = s_c; for (int i = 0; i < inst.length(); i++) { char asc = inst.charAt(i); if (asc == '0' + left) { r_c--; } if (asc == '0' + up) { r_r--; } if (asc == '0' + right) { r_c++; } if (asc == '0' + down) { r_r++; } if (map[r_r][r_c] == '#') { break; } if (map[r_r][r_c] == 'E') { ans++; break; } } } } } } System.out.println(ans); } private void solveC() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); double R = 0.0 + sc.nextInt(); double[] x = new double[N]; double[] y = new double[N]; for (int i = 0; i < N; i++) { x[i] = 0.0 + sc.nextInt(); double max_y = R; for (int j = 0; j < i; j++) { double dy = 4 * R * R - (x[i] - x[j]) * (x[i] - x[j]); if (dy >= 0) { double tmp_y = y[j] + Math.sqrt(dy); if (max_y < tmp_y) { max_y = tmp_y; } } } y[i] = max_y; } StringJoiner sj = new StringJoiner(" "); for (int i = 0; i < N; i++) { sj.add(String.valueOf(y[i])); } System.out.println(sj.toString()); } private void solveD() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); System.out.println(N); } private void solveE() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); System.out.println(N); } private void solveF() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); System.out.println(N); } interface Graph { void link(int from, int to, long cost); Optional<Long> getCost(int from, int to); int getVertexNum(); } interface FlowResolver { long maxFlow(int from, int to); } /** * グラフの行列による実装 * 接点数の大きいグラフで使うとMLEで死にそう */ class ArrayGraph implements Graph { private Long[][] costArray; private int vertexNum; public ArrayGraph(int n) { costArray = new Long[n][]; for (int i = 0; i < n; i++) { costArray[i] = new Long[n]; } vertexNum = n; } @Override public void link(int from, int to, long cost) { costArray[from][to] = new Long(cost); } @Override public Optional<Long> getCost(int from, int to) { return Optional.ofNullable(costArray[from][to]); } @Override public int getVertexNum() { return vertexNum; } } /** * DFS(深さ優先探索)による実装 * 計算量はO(E*MaxFlow)のはず (E:辺の数, MaxFlow:最大フロー) */ class DfsFlowResolver implements FlowResolver { private Graph graph; public DfsFlowResolver(Graph graph) { this.graph = graph; } /** * 最大フロー(最小カット)を求める * @param from 始点(source)のID * @param to 終点(target)のID * @return 最大フロー(最小カット) */ public long maxFlow(int from, int to) { long sum = 0L; long currentFlow; do { currentFlow = flow(from, to, Long.MAX_VALUE / 3, new boolean[graph.getVertexNum()]); sum += currentFlow; } while (currentFlow > 0); return sum; } /** * フローの実行 グラフの更新も行う * @param from 現在いる節点のID * @param to 終点(target)のID * @param current_flow ここまでの流量 * @param passed 既に通った節点か否かを格納した配列 * @return 終点(target)に流した流量/戻りのグラフの流量 */ private long flow(int from, int to, long current_flow, boolean[] passed) { passed[from] = true; if (from == to) { return current_flow; } for (int id = 0; id < graph.getVertexNum(); id++) { if (passed[id]) { continue; } Optional<Long> cost = graph.getCost(from, id); if (cost.orElse(0L) > 0) { long nextFlow = current_flow < cost.get() ? current_flow : cost.get(); long returnFlow = flow(id, to, nextFlow, passed); if (returnFlow > 0) { graph.link(from, id, cost.get() - returnFlow); graph.link(id, from, graph.getCost(id, from).orElse(0L) + returnFlow); return returnFlow; } } } return 0L; } } /** * 1-indexedのBIT配列 */ class BinaryIndexedTree { private long[] array; public BinaryIndexedTree(int size) { this.array = new long[size + 1]; } /** * 指定した要素に値を加算する * 計算量はO(logN) * @param index 加算する要素の添字 * @param value 加算する量 */ public void add(int index, long value) { for (int i = index; i < array.length; i += (i & -i)) { array[i] += value; } } /** * 1〜指定した要素までの和を取得する * 計算量はO(logN) * @param index 和の終端 * @return 1〜indexまでの和 */ public long getSum(int index) { long sum = 0L; for (int i = index; i > 0; i -= (i & -i)) { sum += array[i]; } return sum; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int res = n; String str = Integer.toString(n); res = Math.max(res, Integer.parseInt(str.substring(0, str.length() - 1))); res = Math.max(res, Integer.parseInt(str.substring(0, str.length() - 2) + str.substring(str.length() - 1))); System.out.println(res); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { new A().run(); } private void run() { Scanner sc = new Scanner(System.in); String s = sc.next(); sc.close(); int res = 0; for (int i = 0; i < s.length(); i++) for (int j = i + 1; j <= s.length(); j++) { String sub = s.substring(i, j); int c = count(s, sub); if (c >= 2) res = Math.max(res, sub.length()); } System.out.println(res); } private int count(String s, String sub) { int res = 0; while (s.length() > 0) { if (s.startsWith(sub)) res++; s = s.substring(1); } return res; } }
cubic
23_A. You're Given a String...
CODEFORCES
//package code; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Random; import java.util.Scanner; import java.util.TreeMap; /** * * @author malek */ public class MainA { public static void main(String[] args) throws Exception { //String cwd = System.getProperty("user.dir") + "\\"; Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintStream out = new PrintStream(System.out); //Scanner in = new Scanner(new BufferedInputStream(new FileInputStream(cwd + "src\\code\\in.in"))); //PrintStream out = new PrintStream(cwd + "src\\code\\out.out"); //======================= Solution solution = new Solution(in, out); solution.solve(); //======================= in.close(); out.close(); } static private class Solution { final int inf = (int)1e9; //final int MAX_N = 1000 * 1000 + 100; int n, x, y, c; int f(int u, int r, int sec){ if(u == 0 && r == 0) return 0; if(u == 0){ return r - 1; } if(r == 0){ return u - 1; } return Math.min(sec - 1, u - 1 + r - 1); } boolean isok(int sec){ int up = x - 1; int down = n - x; int right = n - y; int left = y - 1; int u = 0, d = 0, r = 0, l = 0; int total = 1; int add = 4; for(int i = 1; i <= sec; i++){ int cc = 0; if(i > up && ++cc > 0) u++; if(i > down && ++cc > 0) d++; if(i > right && ++cc > 0) r++; if(i > left && ++cc > 0) l++; total += add - cc; total -= Math.max(0, f(u, r, i)); total -= Math.max(0, f(u, l, i)); total -= Math.max(0, f(d, r, i)); total -= Math.max(0, f(d, l, i)); if(total >= c) return true; add += 4; } return false; } public void solve() { n = in.nextInt(); x = in.nextInt(); y = in.nextInt(); c = in.nextInt(); if(c == 1){ out.println(0); return; } int lo = 0, hi = 60000; while(lo < hi){ int mid = (lo + hi)/2; if(isok(mid)){ hi = mid; } else{ lo = mid + 1; } } out.println(lo); } public Solution(Scanner in, PrintStream out) { this.in = in; this.out = out; } Scanner in; PrintStream out; } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main { static int[][][] dp; public static void main(String[] args) { Scanner r = new Scanner(System.in); int n = r.nextInt(); int m = r.nextInt(); if(n > m){int t = n; n = m; m = t;} dp = new int[m+1][1 << 7][1 << 7]; for(int[][] i : dp) for(int[] j : i) Arrays.fill(j, -1); int min = go(m, 0, (1<<n) -1, n, m); System.out.println(n * m - min); } private static int go(int rem, int prev, int need, int n, int m) { // for(int i = rem; i < m; i++) // System.out.print(" "); // System.out.println(rem + ": " + prev +","+need); if(rem == 0)return prev == 0?0:1 << 20; if(dp[rem][prev][need] != -1)return dp[rem][prev][need]; int min = 1 << 20; for(int now = 0; now < 1 << n; now++){ if((~now & prev) != 0)continue; int after = need & ~(now) & ~(now << 1) & ~(now >> 1); int next = ~(now) & ((1 << n)-1); int current = Integer.bitCount(now) + go(rem-1, after ,next, n, m); min = Math.min(min, current); } return dp[rem][prev][need] = min; } }
np
111_C. Petya and Spiders
CODEFORCES
import java.util.Scanner; public class ProblemA { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long[] answer = new long[3]; if (n == 1) { answer[0] = 0; answer[1] = 0; answer[2] = 1; } else if (n > 1) { long f1 = 0; long f2 = 1; long m = 0; while (m < n) { answer[0] = answer[1]; answer[1] = f1; answer[2] = f2; m = f1 + f2; f1 = f2; f2 = m; } answer[2] = answer[1]; } System.out.println(answer[0] + " " + answer[1] + " " + answer[2]); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n, t[], g[], MOD = (int) 1e9 + 7; static int[][][] memo1, memo2[], memo3[]; static int dp1(int idx, int remCnt, int remSum) { if (idx == n) return remSum == 0 && remCnt == 0 ? 1 : 0; if (remCnt < 0 || remSum < 0) return 0; if (memo1[idx][remCnt][remSum] != -1) return memo1[idx][remCnt][remSum]; int ans = dp1(idx + 1, remCnt, remSum); if (g[idx] == 0) { ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]); if (ans >= MOD) ans -= MOD; } return memo1[idx][remCnt][remSum] = ans; } static int dp2(int idx, int remCnt1, int remCnt2, int remSum) { if (idx == n) return remSum == 0 && remCnt1 == 0 && remCnt2 == 0 ? 1 : 0; if (remSum < 0 || remCnt1 < 0 || remCnt2 < 0) return 0; if (memo2[idx][remCnt1][remCnt2][remSum] != -1) return memo2[idx][remCnt1][remCnt2][remSum]; int ans = dp2(idx + 1, remCnt1, remCnt2, remSum); if (g[idx] == 1) ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]); else if (g[idx] == 2) ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]); return memo2[idx][remCnt1][remCnt2][remSum] = ans; } private static int dp3(int cnt0, int cnt1, int cnt2, int last) { if (cnt0 < 0 || cnt1 < 0 || cnt2 < 0) return 0; if (cnt0 + cnt1 + cnt2 == 0) return 1; if (memo3[last][cnt0][cnt1][cnt2] != -1) return memo3[last][cnt0][cnt1][cnt2]; long ans = 0; if (last != 0) ans += dp3(cnt0 - 1, cnt1, cnt2, 0); if (last != 1) ans += dp3(cnt0, cnt1 - 1, cnt2, 1); if (last != 2) ans += dp3(cnt0, cnt1, cnt2 - 1, 2); return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); int[] fac = new int[n + 1]; t = new int[n]; g = new int[n]; int[] cnt = new int[3]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (int) (i * 1L * fac[i - 1] % MOD); int T = sc.nextInt(); for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; cnt[g[i]]++; } memo1 = new int[n][cnt[0] + 1][T + 1]; memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1]; memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= cnt[0]; j++) Arrays.fill(memo1[i][j], -1); for (int j = 0; j <= cnt[1]; j++) for (int k = 0; k <= cnt[2]; k++) Arrays.fill(memo2[i][j][k], -1); } for (int i = 0; i < 4; i++) for (int j = 0; j <= cnt[0]; j++) for (int k = 0; k <= cnt[1]; k++) Arrays.fill(memo3[i][j][k], -1); int ans = 0; for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++) for (int sum0 = 0; sum0 <= T; sum0++) for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++) for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) { long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD; ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD; ways *= fac[cnt0]; ways %= MOD; ways *= fac[cnt1]; ways %= MOD; ways *= fac[cnt2]; ways %= MOD; ans += ways; if (ans >= MOD) ans -= MOD; } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.PrintWriter; import java.util.*; /** * Created by trung.pham on 28/12/17. */ public class C_Round_455_Div2 { static long[][]dp; static long MOD =(long) 1e9 + 7; public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); char[]data = new char[n]; dp = new long[n][n]; for(long []a : dp){ Arrays.fill(a,-1); } for(int i = 0; i < n; i++){ data[i] = in.next().charAt(0); } out.println(cal(0, 0, data)); out.close(); } static long cal(int index, int nested, char[]data ){ //System.out.println(index + " " + nested); if(index + 1 == data.length){ return 1; } if(dp[index][nested] != -1){ return dp[index][nested]; } long result = 0; boolean isLoop = data[index] == 'f'; if(isLoop){ result = cal(index + 1, nested + 1, data); }else{ result = cal(index + 1, nested, data); if(nested > 0){ result += cal(index, nested - 1, data); result %= MOD; } } // System.out.println(result + " " + index + " " + nested); return dp[index][nested]= result; } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Solution implements Runnable { public static void main(String[] args) { (new Thread(null, new Solution(), "1", 1l << 28)).start(); } public void run() { try { // in = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { out.close(); } } BufferedReader in; PrintWriter out; StringTokenizer st = null; String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { //if (!in.ready()) return null; st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(nextToken()); } void solve() throws Exception { int n = nextInt(); int[] a = new int[n]; int sum = 0; for (int i = 0; i < n; i++) sum += (a[i] = nextInt()); Arrays.sort(a); int ans = 0; int s = 0; for (int i = n - 1; i >= 0; i--) { s += a[i]; ans++; if (2 * s > sum) break; } out.println(ans); } }
nlogn
160_A. Twins
CODEFORCES
import java.io.*; import java.awt.geom.Point2D; import java.text.*; import java.math.*; import java.util.*; public class Main implements Runnable { final String filename = ""; public void solve() throws Exception { int n = iread(), m = iread(); int INF = -1; if (m > n) { int t = m; m = n; n = t; } int[][][] d = new int[2][1 << m][1 << m]; for (int i = 0; i < 1 << m; i++) Arrays.fill(d[0][i], INF); int[] cnt = new int[1 << m]; for (int i = 0; i < 1 << m; i++) cnt[i] = cnt[i / 2] + i % 2; int step = 0; d[0][0][0] = 0; for (int u = 0; u < n; u++) { for (int i = 0; i < 1 << m; i++) Arrays.fill(d[step ^ 1][i], INF); for (int mask1 = 0; mask1 < 1 << m; mask1++) for (int mask2 = 0; mask2 < 1 << m; mask2++) { int t = d[step][mask1][mask2]; if (t == INF) continue; for (int mask = 0; mask < 1 << m; mask++) { if ((mask1 & mask) != mask1) continue; int mask01 = ((1 << m) - 1) & ~mask2; for (int j = 0; j < m; j++) if ((mask & (1 << j)) != 0) { if (j > 0) mask01 &= ~(1 << (j - 1)); mask01 &= ~(1 << j); if (j + 1 < m) mask01 &= ~(1 << (j + 1)); } int mask02 = mask; int t2 = t + cnt[((1 << m) - 1) & ~mask]; if (d[step ^ 1][mask01][mask02] < t2) { d[step ^ 1][mask01][mask02] = t2; } } } step ^= 1; } int ans = INF; for (int mask = 0; mask < 1 << m; mask++) { ans = Math.max(ans, d[step][0][mask]); } out.write(ans + "\n"); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); // in = new BufferedReader(new FileReader(filename+".in")); // out = new BufferedWriter(new FileWriter(filename+".out")); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { try { Locale.setDefault(Locale.US); } catch (Exception e) { } // new Thread(new Main()).start(); new Thread(null, new Main(), "1", 1 << 25).start(); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.io.*; import java.util.*; public class EMatrix{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.flush();out.close(); } static class TaskE { final int max = (int)(1E9); int n , m; int a[][]; int gm[]; boolean visit[][]; int dp[][]; boolean check(int d){ if(n == 1){ for(int i = 0; i < m - 1; i++){ if(Math.abs(a[0][i] - a[0][i + 1]) < d)return false; } return true; } int nm[] = new int[n], pm[] = new int[n]; for(int i = 0; i < n; i++){ boolean r; for(int j = 0; j < n; j++){ if(j == i)continue; r = true; for(int k = 0; k < m; k++){ if(Math.abs(a[i][k] - a[j][k]) < d){ r = false; break; } } if(r){ nm[i] |= (1 << j); } r = true; for(int k = 0; k < m - 1; k++){ if(Math.abs(a[i][k + 1] - a[j][k]) < d){ r = false; break; } } if(r){ pm[i] |= (1 << j); } } } // for(int i = 0; i < n; i++){ // System.out.println(nm[i] + " " + pm[i]); // } for(int i = 0; i < n; i++){ gm = new int[n]; gm[i] = nm[i]; for(int j = 0; j < n; j++){ if(j == i)continue; if((nm[j] & (1 << i)) != 0){ gm[j] = nm[j] ^ (1 << i); }else{ gm[j] = nm[j]; } } for(int j = 0; j < n; j++){ if(j == i)continue; if((pm[i] >> j) % 2 == 1){ gm[j] |= (1 << i); } } visit = new boolean[n][1 << n]; dp = new int[n][1 << n]; // for(int x = 0; x < n; x++)System.out.println(gm[x]); if(dfs(i, i, (1 << i)) == n){ return true; } } return false; } int dfs(int u, int r, int mask){ // System.out.println(u + " " + r + " " + mask); if(u == r && mask == (1 << n) - 1)return 0; if(visit[u][mask])return dp[u][mask]; visit[u][mask] = true; int val = 0; for(int i = 0; i < n; i++){ if((gm[u] >> i) % 2 == 1 && ((i == r && mask == (1 << n) - 1) || (mask >> i) % 2 != 1)){ val = Math.max(val, 1 + dfs(i, r, mask | (1 << i))); } } // System.out.println(u + " " + mask + " " + val); return dp[u][mask] = val; } public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); a = new int[n][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ a[i][j] = in.nextInt(); } } int l = 0, r = max, ans = 0; while(l <= r){ int m = (l + r) >> 1; if(check(m)){ ans = m; l = m + 1; }else{ r = m - 1; } } out.println(ans); } // pair ja[][];long w[];int from[],to[],c[]; // void make(int n,int m,InputReader in){ // ja=new pair[n+1][];w=new long[m];from=new int[m];to=new int[m];c=new int[n+1]; // for(int i=0;i<m;i++){ // int u=in.nextInt(),v=in.nextInt();long wt=in.nextLong(); // c[u]++;c[v]++;from[i]=u;to[i]=v;w[i]=wt; // } // for(int i=1;i<=n;i++){ // ja[i]=new pair[c[i]];c[i]=0; // } // for(int i=0;i<m;i++){ // ja[from[i]][c[from[i]]++]=new pair(to[i],w[i]); // ja[to[i]][c[to[i]]++]=new pair(from[i],w[i]); // } // } // int[] radixSort(int[] f){ return radixSort(f, f.length); } // int[] radixSort(int[] f, int n) // { // int[] to = new int[n]; // { // int[] b = new int[65537]; // for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++; // for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; // for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i]; // int[] d = f; f = to;to = d; // } // { // int[] b = new int[65537]; // for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++; // for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; // for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i]; // int[] d = f; f = to;to = d; // } // return f; // } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.io.*; public class Main { private static Reader in; private static PrintWriter out; public static void main(String args[]) throws IOException { in = new Reader(); out = new PrintWriter(System.out); long n = in.nextLong(); long s = in.nextLong(); long low = 0, mid = 0, high = n; while (low <= high) { mid = (low + high) / 2; if (func(mid, s)) { high = mid - 1; } else { low = mid + 1; } } out.println(n - low + 1); out.close(); } private static boolean func(long num, long s) { long sum = 0, temp = num; while (temp > 0) { sum += (temp) % 10; temp /= 10; } return ((num - sum) >= s); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == ' ' || c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public String nextLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeMap; public class Main { public static void main(String[] args) { Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(System.out))); while (in.hasNext()) { int n = in.nextInt(), a = in.nextInt(), b = in.nextInt(), c = 0; int[] p = new int[n]; TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int i = 0; i < n; i++) { p[i] = in.nextInt(); map.put(p[i], i); } if (a > b) { int t = b; b = a; a = t; c = 1; } boolean ok = true; int[] cls = new int[n]; while (ok && map.size() > 0) { Entry<Integer, Integer> last = map.lastEntry(); int v = last.getKey(); int idx = last.getValue(); if (map.containsKey(a - v)) { cls[idx] = 0; cls[map.get(a - v)] = 0; map.remove(v); map.remove(a -v); } else if (map.containsKey(b - v)) { cls[idx] = 1; cls[map.get(b - v)] = 1; map.remove(v); map.remove(b -v); } else ok = false; } if (!ok) System.out.println("NO"); else { System.out.println("YES"); for (int j = 0; j < cls.length; j++) { if (j != 0) System.out.print(" "); System.out.print(c ^ cls[j]); } System.out.println(); } out.flush(); } in.close(); } }
linear
468_B. Two Sets
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; public class Main { static public void main(String args[]) throws Exception { Scanner s = new Scanner(System.in); int n = s.nextInt(), m = s.nextInt(), K = s.nextInt(); int[][] p = new int[n][m - 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { p[i][j] = s.nextInt(); } } int[][] v = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { v[i][j] = s.nextInt(); } } if (K % 2 == 1){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print("-1 "); } System.out.println(); } return; } long[][][] dp = new long[K + 1][n][m]; for (int k = 2; k <= K; k += 2) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { long res = Long.MAX_VALUE; if (i + 1 < n) { res = Math.min(res, dp[k - 2][i + 1][j] + v[i][j] * 2); } if (i - 1 >= 0) { res = Math.min(res, dp[k - 2][i - 1][j] + v[i - 1][j] * 2); } if (j + 1 < m) { res = Math.min(res, dp[k - 2][i][j + 1] + p[i][j] * 2); } if (j - 1 >= 0) { res = Math.min(res, dp[k - 2][i][j - 1] + p[i][j - 1] * 2); } dp[k][i][j] = res; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(dp[K][i][j] + " "); } System.out.println(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class A { public static void main(String ar[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s1[]=br.readLine().split(" "); String s2[]=br.readLine().split(" "); int n=Integer.parseInt(s1[0]); int m=Integer.parseInt(s1[1]); int a[]=new int[n]; int b[]=new int[n]; int c[]=new int[n]; int d[]=new int[n]; HashSet<Integer> hs=new HashSet<Integer>(); hs.add(0); hs.add(m); int max=0; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(s2[i]); if(i%2==0) b[i]=1; hs.add(a[i]); } c[0]=a[0]; for(int i=1;i<n;i++) { if(b[i]==0) c[i]=c[i-1]; else c[i]=c[i-1]+a[i]-a[i-1]; } if(b[n-1]==0) d[n-1]=m-a[n-1]; for(int i=n-2;i>=0;i--) { if(b[i]==1) d[i]=d[i+1]; else d[i]=d[i+1]+a[i+1]-a[i]; } max=c[n-1]; if(b[n-1]==0) max+=m-a[n-1]; //System.out.println(max); for(int i=n-1;i>=0;i--) { int u=a[i]-1; int v=a[i]+1; if(!hs.contains(u)) { if(b[i]==0) { int r=1+m-a[i]-d[i]+c[i-1]; max=Math.max(max,r); } else { int l=0; if(i>0) l=a[i-1]; int r=c[i]-1+m-a[i]-d[i]; max=Math.max(max,r); } } if(!hs.contains(v)) { if(b[i]==0) { if(i==n-1) { int r=c[i]+1; max=Math.max(max,r); } else { int r=c[i]+1+m-a[i+1]-d[i+1]; max=Math.max(max,r); } } else { if(i==n-1) { int r=c[i]+m-a[i]-1; max=Math.max(max,r); } else { int r=c[i]+m-a[i+1]-d[i+1]+a[i+1]-1-a[i]; max=Math.max(max,r); } } } } System.out.println(max); } }
linear
1000_B. Light It Up
CODEFORCES
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner scn = new Scanner(new File("input.txt")); BufferedWriter out = new BufferedWriter(new FileWriter("output.txt")); int r = scn.nextInt(); int c = scn.nextInt(); int[][] a = new int[r][c]; for(int[] i: a) Arrays.fill(i, 1<<30); int k = scn.nextInt(); Queue<State> q = new LinkedList<State>(); for(int l = 0; l < k; l++){ int i = scn.nextInt()-1; int j = scn.nextInt()-1; a[i][j] = 0; q.add(new State(i, j, 0)); } while(!q.isEmpty()){ State st = q.poll(); a[st.i][st.j] = st.c; for(int d = 0; d < 4; d++){ int ii = st.i + di[d]; int jj = st.j + dj[d]; if(ii < 0 || ii >= r || jj < 0 || jj >= c)continue; if(a[ii][jj] != 1 << 30)continue; a[ii][jj] = st.c+1; q.add(new State(ii, jj, st.c+1)); } } int max = 0; for(int i = 0; i < r; i++) for(int j = 0; j < c; j++) max = Math.max(max, a[i][j]); for(int i = 0; i < r; i++) for(int j = 0; j < c; j++) if(a[i][j] == max){ // System.out.println(i+1 + " " + (j+1)); out.write((i+1)+" "+(j+1)); out.newLine(); out.close(); return; } } static int[] di = {0, 0, -1, 1}; static int[] dj = {1, -1, 0, 0}; } class State{ int i, j, c; public State(int ii, int ji, int ci){ i = ii; j = ji; c = ci; } }
cubic
35_C. Fire Again
CODEFORCES
import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class PlayingPiano { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); List<Integer> as = new LinkedList<>(); int[] as2 = new int[n]; for (int i = 0; i < n; i++) { int a = scanner.nextInt(); as.add(a); as2[i] = a; } //System.out.println(solve(as)); System.out.println(solve2(as2)); scanner.close(); } public static String solve(List<Integer> as) { List<Integer> fingers = new LinkedList<>(); fingers.add(1); fingers.add(2); fingers.add(3); fingers.add(4); fingers.add(5); List<Integer> solution = assign(as, fingers, fingers); if (solution == null) { return "-1"; } else { StringBuilder sb = new StringBuilder(); for (int b : solution) { sb.append(b); sb.append(" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } } private static List<Integer> assign(List<Integer> as, List<Integer> fingers, List<Integer> allFingers) { // if fingers is empty return null if (fingers.isEmpty()) { return null; } // if as size is one then return first element in fingers if (as.size() == 1) { List<Integer> ret = new LinkedList<>(); ret.add(fingers.get(0)); return ret; } // get sublist List<Integer> subList = as.subList(1, as.size()); for (int i = 0; i < fingers.size(); i++) { // recursively call with sublist and limited list of fingers List<Integer> subFingers = new LinkedList<>(); final int j = i; if (as.get(0) < as.get(1)) { subFingers = allFingers.stream() .filter(p -> p > fingers.get(j)).collect(Collectors.toList()); } else if (as.get(0) > as.get(1)) { subFingers = allFingers.stream() .filter(p -> p < fingers.get(j)).collect(Collectors.toList()); } else { subFingers = allFingers.stream() .filter(p -> p != fingers.get(j)).collect(Collectors.toList()); } List<Integer> ret = assign(subList, subFingers, allFingers); if (ret != null) { List<Integer> solution = new LinkedList<>(); solution.add(fingers.get(i)); solution.addAll(ret); return solution; } // if return is null, then return null, else return an array } return null; } public static String solve2(int[] as) { int[] ret = new int[as.length]; if (as.length == 1) return "1"; if (as[0] < as[1]) ret[0] = 1; else if (as[0] == as[1]) ret[0] = 3; else ret[0] = 5; for (int i = 1; i < as.length - 1; i++) { if (as[i-1] < as[i] && ret[i-1] == 5) return "-1"; if (as[i-1] > as[i] && ret[i-1] == 1) return "-1"; if (as[i-1] < as[i] && as[i] < as[i+1]) { ret[i] = ret[i-1] + 1; } else if (as[i-1] == as[i] && as[i] < as[i+1]) { ret[i] = ret[i-1] == 1 ? 2 : 1; } else if (as[i-1] > as[i] && as[i] < as[i+1]) { ret[i] = 1; } else if (as[i-1] < as[i] && as[i] == as[i+1]) { ret[i] = ret[i-1] + 1; } else if (as[i-1] == as[i] && as[i] == as[i+1]) { ret[i] = ret[i-1] == 4 ? 2 : 4; } else if (as[i-1] > as[i] && as[i] == as[i+1]) { ret[i] = ret[i-1] == 2 ? 1 : 2; } else if (as[i-1] < as[i] && as[i] > as[i+1]) { ret[i] = 5; } else if (as[i-1] == as[i] && as[i] > as[i+1]) { ret[i] = ret[i-1] == 5 ? 4 : 5; } else if (as[i-1] > as[i] && as[i] > as[i+1]) { ret[i] = ret[i-1] - 1; } } if (as.length > 1) { if (as[as.length - 1] > as[as.length - 2]) { if (ret[as.length - 2] == 5) return "-1"; ret[as.length - 1] = 5; } else if (as[as.length - 1] == as[as.length - 2]) { ret[as.length - 1] = ret[as.length - 2] == 5 ? 4 : 5; } else { if (ret[as.length - 2] == 1) return "-1"; ret[as.length - 1] = 1; } } StringBuilder sb = new StringBuilder(); for (int b : ret) { sb.append(b); sb.append(" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } }
linear
1032_C. Playing Piano
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ int t=in.nextInt(); for(int i=0;i<t;i++) { out.println(work()); } out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } int work() { int n=in.nextInt(); int m=in.nextInt(); int[][] A=new int[n][m]; int[][] B=new int[n][m]; int[][] R=new int[m][2]; for(int i=0;i<m;i++)R[i][1]=i; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { A[i][j]=in.nextInt(); R[j][0]=Math.max(R[j][0], A[i][j]); } } Arrays.sort(R,new Comparator<int[]>() { public int compare(int[] arr1,int[] arr2) { return arr2[0]-arr1[0]; } }); for(int j=0;j<m;j++) { int index=R[j][1]; for(int i=0;i<n;i++) { B[i][j]=A[i][index]; } } m=Math.min(n, m); int[][] dp=new int[m][1<<n]; int[][] rec=new int[m][1<<n]; for(int j=0;j<m;j++) { for(int s=0;s<n;s++) {//转 for(int i=1;i<1<<n;i++) { int sum=0; for(int b=0;b<n;b++) { if(((1<<b)&i)>0) { sum+=B[(b+s)%n][j]; } } rec[j][i]=Math.max(sum, rec[j][i]); } } } for(int j=0;j<m;j++) { for(int i=0;i<1<<n;i++) { if(j==0) { dp[j][i]=rec[j][i]; }else { for(int p=i+1;;p++) { if(p>=1<<n)break; p=p|i; dp[j][p]=Math.max(dp[j][p], rec[j][i]+dp[j-1][p^i]); } } } } return dp[m-1][(1<<n)-1]; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.util.*; import java.io.*; public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(); int T = sc.nextInt(); StringBuilder sb = new StringBuilder(); while(T-->0) { int n = sc.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } int[] p = new int[n]; int[] base = new int[n]; p[0] = -1; base[0] = -1; boolean[] used = new boolean[n]; for(int i = 1; i < n; i++) { if(arr[i] == 1) { p[i] = i-1; base[i] = i-1; } else { for(int j = i-1; j >= 0; j--) { if(used[j]) continue; if(arr[j] == arr[i]-1) { p[i] = j; used[j] = true; base[i] = base[j]; break; } else used[j] = true; } } } StringBuilder[] res = new StringBuilder[n]; res[0] = new StringBuilder("1"); sb.append("1\n"); for(int i = 1; i < n; i++) { if(base[i] == -1) { res[i] = new StringBuilder(); } else { res[i] = new StringBuilder(res[base[i]]); res[i].append("."); } res[i].append(arr[i]+""); sb.append(res[i]); sb.append("\n"); } } PrintWriter pw = new PrintWriter(System.out); pw.println(sb.toString().trim()); pw.flush(); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 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) { throw new RuntimeException(e); } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; 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 */ 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(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), d = in.nextInt(); long a[] = in.parseLong1D(n); int cnt = 0; HashSet<Long> ans = new HashSet<>(); for (long v : a) { long c = v - d; if (isPos(a, c, d)) ans.add(c); c = v + d; if (isPos(a, c, d)) ans.add(c); } out.println(ans.size()); } private boolean isPos(long a[], long c, long d) { for (long v : a) { if (Math.abs(v - c) < d) return false; } return true; } } 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); } } 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 readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int nextInt() { return readInt(); } public long[] parseLong1D(int n) { long r[] = new long[n]; for (int i = 0; i < n; i++) { r[i] = readLong(); } return r; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.*; import java.util.Scanner; public class abc{ public static int check(StringBuilder s) { int countRemove=0; if(!s.toString().contains("xxx")) return countRemove; else{ for(int i=1;i<s.length()-1;i++) { if(s.charAt(i-1)=='x' && s.charAt(i)=='x' && s.charAt(i+1)=='x') { countRemove++; } } return countRemove; } } public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); //sc= new Scanner(System.in); String s = sc.next(); StringBuilder sb = new StringBuilder(""); sb.append(s); System.out.println(check(sb)); } }
linear
978_B. File Name
CODEFORCES
import java.util.*; import java.io.*; public class C1523 { public static void print(Stack<Integer> st, PrintWriter pw) { for (int i = 0; i < st.size(); i++) { pw.print(st.get(i)); if (i != st.size() - 1) { pw.print("."); } } pw.println(); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] arr = sc.nextIntArr(n); Stack<Integer> st = new Stack<Integer>(); st.add(arr[0]); print(st, pw); for (int i = 1; i < n; i++) { if (arr[i] == 1) { st.add(arr[i]); } else { while (st.peek() != arr[i] - 1) { st.pop(); } st.pop(); st.add(arr[i]); } print(st, pw); } } pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.util.Random; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion(); int testCount = in.scanInt(); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class E2RotateColumnsHardVersion { int[][] dp; int[] cur; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int m = in.scanInt(); int[][] ar = new int[n][m]; int[][] max = new int[m][2]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) ar[i][j] = in.scanInt(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) max[i][0] = Math.max(max[i][0], ar[j][i]); max[i][1] = i; } CodeHash.shuffle(max); Arrays.sort(max, (o1, o2) -> -o1[0] + o2[0]); dp = new int[2][1 << n]; cur = new int[1 << n]; for (int i = 0; i < Math.min(m, n); i++) { Arrays.fill(dp[i & 1], 0); for (int k = 0; k < n; k++) { System.arraycopy(dp[(i - 1) & 1], 0, cur, 0, 1 << n); for (int l = 0; l < n; l++) { for (int j = 0; j < 1 << n; j++) { if ((j & (1 << l)) == 0) { cur[j ^ (1 << l)] = Math.max(cur[j ^ (1 << l)], cur[j] + ar[(k + l) % n][max[i][1]]); } } } for (int j = 0; j < 1 << n; j++) dp[i & 1][j] = Math.max(dp[i & 1][j], cur[j]); } } out.println(dp[Math.min(n, m) & 1 ^ 1][(1 << n) - 1]); } } static class CodeHash { public static void shuffle(int[][] ar) { Random rd = new Random(new Random().nextInt()); for (int i = 0; i < ar.length; i++) { int index = rd.nextInt(ar.length); int[] temp = ar[i]; ar[i] = ar[index]; ar[index] = temp; } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.*; public class E1180D { public static void main(String args[]) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); // Move from both ends, Time limit exceeded on test 6 for (int i= 1; i<= m/2; i++) { // String s = ""; int i2 = m -i + 1; // the other end of i // i is left row, i2 is right row for (int j = 1; j <= n ; j++) { int j2 = n - j + 1; // start with (i,j), then go thru all the cell with (,i) and (,i2) pw.println(j + " " + i); pw.println(j2+ " " + i2); // s += j + " " + i + "\n" + j2+ " " + i2 + "\n"; } // out.print(s); } // if n is odd, there is one line in the middle if (m % 2 == 1) { int i2 = m /2 + 1; // this is the middle column for (int j = 1; j <= n/2 ; j++) { int j2 = n - j + 1; // start with (i,j), then go thru all the cell with (,i) and (,i2) pw.println(j + " " + i2); pw.println(j2+ " " + i2); } if (n %2 == 1) { int j = n /2 + 1; pw.println(j + " " + i2); } } pw.flush(); pw.close(); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
import java.util.*; import java.io.*; /* spar5h */ public class codeforces implements Runnable { final static long mod = (long)1e9 + 7; public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = s.nextInt(); char[] c = new char[n]; for(int i = 0; i < n; i++) c[i] = s.next().charAt(0); //index + depth/indentation long[][] dp = new long[n][n]; dp[0][0] = 1; for(int i = 0; i < n - 1; i++) { //c[i] = f implies that indentation will always be increased by one in i + 1 if(c[i] == 'f') { for(int j = 1; j < n; j++) dp[i + 1][j] = dp[i][j - 1]; } //c[i] = s implies that value of i + 1 can include any previous value of equal or higher indentation else { dp[i + 1][n - 1] = dp[i][n - 1]; for(int j = n - 2; j >= 0; j--) dp[i + 1][j] = (dp[i + 1][j + 1] + dp[i][j]) % mod; } } long res = 0; for(int i = 0; i < n; i++) res = (res + dp[n - 1][i]) % mod; w.println(res); w.close(); } 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 String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new codeforces(),"codeforces",1<<26).start(); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class E { static double[] dp; static int[] oneCount; static int end; static int n; static double[][] prob; public static double solve(int mask) { if(mask==end) return 1; int oneC=0,zeroC=0; for(int i=0;i<n;i++) { if((mask|(1<<i))==mask) oneC++; else zeroC++; } double res=0; for(int i=0;i<n;i++) { if((mask|(1<<i))!=mask) continue; for(int j=0;j<n;j++) { // if((mask|(1<<j))==mask) continue; //System.out.println(i+" "+j+" "+prob[i][j]+" "+Integer.toBinaryString(mask)+" "+oneC+" "+zeroC); res+=(1.0/((oneC*(oneC+1))/2))*prob[i][j]*solve(mask|(1<<j)); } } return dp[mask]=res; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); n=sc.nextInt(); prob=new double[n][n]; for(int i=0;i<n;i++) for(int j=0;j<n;j++) prob[i][j]=sc.nextDouble(); dp=new double[1<<n]; oneCount=new int[1<<n]; int c; for(int i=0;i<dp.length;i++) { c=0; for(int j=0;j<n;j++) { if((i|(1<<j))==i) c++; } oneCount[i]=c; } end=(1<<n)-1; double res,rad; int count; for(int k=end;k>0;k--) { if(k==end) dp[k]=1; else { res=0; count=oneCount[k]; count=count*(count+1); count>>=1; rad=1.0/count; //System.out.println(rad+" "+count); for(int i=0;i<n;i++) { if((k|(1<<i))!=k) continue; for(int j=0;j<n;j++) { // if((k|(1<<j))==k) continue; //System.out.println(i+" "+j+" "+prob[i][j]+" "+Integer.toBinaryString(mask)+" "+oneC+" "+zeroC); res+=rad*prob[i][j]*dp[k|(1<<j)]; } } dp[k]=res; } } //Arrays.fill(dp, -1); for(int i=0;i<n;i++) System.out.print(dp[1<<i]+" "); //System.out.print(solve(1<<i)+" "); // for(int i=0;i<18;i++){ // for(int k=0;k<18;k++) // System.out.print(Math.random()+" "); // System.out.println(); // } } }
np
16_E. Fish
CODEFORCES
import java.lang.*; import java.io.*; import java.util.*; public class Main { public void solve() throws IOException { int n = nextInt(), r = nextInt(); int x[] = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt(); } double res[] = new double[n]; res[0] = r; for (int i = 1; i < n; i++) { double max = r; for (int j = 0; j < i; j++) { int d = Math.abs(x[i] - x[j]); if(d <= 2 * r){ double yy = Math.sqrt(4 * r * r - d * d); max = Math.max(max, yy + res[j]); } } res[i] = max; } for (int i = 0; i < n; i++) { out.print(res[i] + " "); } } BufferedReader br; StringTokenizer sc; PrintWriter out; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Main().run(); } void run() throws IOException { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // br = new BufferedReader(new FileReader("pnumbers.in")); // out = new PrintWriter(new File("out.txt")); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } String nextToken() throws IOException { while (sc == null || !sc.hasMoreTokens()) { try { sc = new StringTokenizer(br.readLine()); } catch (Exception e) { return null; } } return sc.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Stack; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 0; tc < t; ++tc) { int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < a.length; ++i) { a[i] = sc.nextInt(); } System.out.println(solve(a)); } sc.close(); } static String solve(int[] a) { List<String> result = new ArrayList<>(); Stack<Integer> stack = new Stack<>(); for (int ai : a) { if (ai != 1) { while (stack.peek() + 1 != ai) { stack.pop(); } stack.pop(); } stack.push(ai); result.add(stack.stream().map(String::valueOf).collect(Collectors.joining("."))); } return String.join("\n", result); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.OutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.FileInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("input.txt"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("output.txt"); } catch (IOException e) { throw new RuntimeException(e); } FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { private final static int[] dx = {-1, 0, +1, 0}; private final static int[] dy = {0, +1, 0, -1}; private final static int WHITE = 123456789; public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int m = in.nextInt(); int[][] map = new int[n][m]; for (int i = 0; i < n; i++) { Arrays.fill(map[i], WHITE); } int k = in.nextInt(); int qh = 0; int qt = 0; int[] q = new int[((int) 7e6)]; for (int i = 0; i < k; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; map[x][y] = 0; q[qh++] = x * m + y; } int d = 0; int X = q[0] / m; int Y = q[0] % m; while (qt < qh) { int pos = q[qt++]; int x = pos / m; int y = pos % m; for (int i = 0; i < 4; i++) { int xx = x + dx[i]; int yy = y + dy[i]; if (isValid(xx, n) && isValid(yy, m) && map[xx][yy] == WHITE) { map[xx][yy] = map[x][y] + 1; q[qh++] = (xx * m) + yy; if (d < map[xx][yy]) { d = map[xx][yy]; X = xx; Y = yy; } } } } // for (int i = 0; i < n; i++) // { // for (int j = 0; j < m; j++) // { // out.print(map[i][j] + " "); // } // out.println(); // } out.println((X + 1) + " " + (Y + 1)); } private boolean isValid(int x, int X) { return x >= 0 && x < X; } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringTokenizer; public class D { static int n, KA, A; static int[] b; static int[] l; static double ans = 0; public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); n = in.nextInt(); KA = in.nextInt(); A = in.nextInt(); b = new int[n]; l = new int[n]; for (int i = 0; i < l.length; i++) { b[i] = in.nextInt(); l[i] = in.nextInt(); } dp = new double[n + 2][n + 2][n * 9999 + 2]; go(0, KA); System.out.printf("%.6f\n", ans); } public static void go(int at, int k) { if (at == n) { ans = Math.max(ans, solve(0, 0, 0)); return; } for (int i = 0; i <= k; i++) { if (l[at] + i * 10 <= 100) { l[at] += i * 10; go(at + 1, k - i); l[at] -= i * 10; } } } static double dp[][][]; public static double solve(int at, int ok, int B) { if (at == n) { if (ok > n / 2) { return 1; } else { return (A * 1.0) / (A * 1.0 + B); } } double ret = ((l[at]) / 100.0) * solve(at + 1, ok + 1, B) + (1.0 - ((l[at]) / 100.0)) * solve(at + 1, ok, B + b[at]); return ret; } // 3 0 31 // 10 60 // 12 60 // 15 0 static class InputReader { BufferedReader in; StringTokenizer st; public InputReader() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(in.readLine()); } public String next() throws IOException { while (!st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Random; import java.util.TreeSet; public final class CF_599_D1_C { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static class Composite implements Comparable<Composite>{ int idx; int v; public int compareTo(Composite X) { if (v!=X.v) return v-X.v; return idx-X.idx; } public Composite(int idx, int v) { this.idx = idx; this.v = v; } } static void test() { log("testing"); log("done"); } static void explore(ArrayList<Integer>[] components,ArrayList<Integer> bob,int[][] move,ArrayList<int[]>[] howto,int[][] list) { for (int x:bob) { if (components[x].size()==1) { int tm[]=howto[x].get(0); int L=howto[x].size(); howto[x].add(tm); for (int i=0;i<L;i++) { int[] cur=howto[x].get(i); int[] nx=howto[x].get(i+1); int a=cur[0]; int a2=nx[0]; int b2=nx[1]; move[a2][0]=list[a2][b2]; move[a2][1]=a; } } else { explore(components,components[x],move,howto,list); } } } static void process() throws Exception { //arrayTest(); out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); int k=reader.readInt(); int[][] list=new int[k][]; long[] sum=new long[k]; int[] L=new int[k]; HashMap<Integer,int[]> target=new HashMap<Integer,int[]>(); long tot=0; for (int i=0;i<k;i++) { L[i]=reader.readInt(); list[i]=new int[L[i]]; for (int j=0;j<L[i];j++) { list[i][j]=reader.readInt(); sum[i]+=list[i][j]; target.put(list[i][j],new int[] {i,j}); } tot+=sum[i]; } int MX=1<<k; int AX=1000000001; ArrayList<int[]>[] howto=new ArrayList[MX]; log("ok with the data"); if (tot%k!=0) { output("No"); } else { tot/=k; for (int i=0;i<k;i++) { if (sum[i]==tot) { //log("nothing to do for i:"+i); // nothing to do int mask=1<<i; ArrayList<int[]> cand=new ArrayList<int[]>(); cand.add(new int[] {i,0}); howto[mask]=cand; } else for (int j=0;j<L[i];j++) { int u=i; int v=j; boolean ok=true; int src_u=u; int src_v=v; int mask=0; boolean goon=true; ArrayList<int[]> cand=new ArrayList<int[]>(); //log("start loop"); while (goon) { cand.add(new int[] {u,v}); //log("u:"+u+" v:"+v); ok=false; goon=false; long need=tot-((long)sum[u]-(long)list[u][v]); if (Math.abs(need)<=AX) { //log("need:"+need); int nd=(int)need; int[] tm=target.get(nd); //log("tm:"+tm); if (tm!=null) { //log("can find successor"); int nxu=tm[0]; int nxv=tm[1]; if ((mask&(1<<nxu))==0) { mask|=1<<nxu; if (nxu==src_u) { // looping back to source if (nxv==src_v) ok=true; } else { u=nxu; v=nxv; ok=true; goon=true; } } } } } if (ok) { if (howto[mask]==null) { howto[mask]=cand; } } } } log("step 1 done"); // now mask ArrayList<Integer> msk=new ArrayList<Integer>(); ArrayList[] components=new ArrayList[MX]; for (int m=0;m<MX;m++) { if (howto[m]!=null) { //String s=Integer.toBinaryString(m); //while (s.length()<k) // s="0"+s; //log("found mask:"+s); components[m]=new ArrayList<Integer>(); components[m].add(m); } } int[] visited=new int[MX]; for (int a=0;a<MX;a++) { if (howto[a]!=null) { ArrayList<Integer> add=new ArrayList<Integer>(); for (int b:msk) { if ((b&a)==0) { int c=b|a; log("creating c:"+c+" "); if (components[c]==null) { components[c]=new ArrayList<Integer>(); components[c].add(a); components[c].add(b); add.add(c); } } } msk.add(a); for (int c:add) { msk.add(c); } } } //log("msk:"+msk); //log(components[MX-1]); if (components[MX-1]!=null) { output("Yes"); int[][] move=new int[k][2]; explore(components,components[MX-1],move,howto,list); for (int i=0;i<k;i++) { output(move[i][0]+" "+(move[i][1]+1)); } } else { output("No"); } } try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
np
1242_C. Sum Balance
CODEFORCES
import java.util.Scanner; public class Main3 { public static void main(String[] args) { Scanner s = new Scanner(System.in); long l = s.nextLong(); long r = s.nextLong(); String a = Long.toBinaryString(l); String b = Long.toBinaryString(r); while(a.length() < b.length()) a = "0" + a; while(b.length() < a.length()) b = "0" + b; String ans = ""; int ix = -1; for (int i = 0; i < a.length(); i++) { if(a.charAt(i) != b.charAt(i)){ break; } ans += a.charAt(i); ix++; } // System.out.println(a); // System.out.println(b); for (int i = ix + 1; i < a.length(); i++) { int c1 = a.charAt(i) - '0'; int c2 = b.charAt(i) - '0'; if(c1 == 0 && c2 == 0) ans += "1"; else if(c1 == 1 && c2 == 1) ans += "0"; else ans += (char)(c1 + '0'); } long a1 = Long.parseLong(ans, 2); long a2 = Long.parseLong(b,2); // System.out.println(ans); // System.out.println(b); // System.out.println(); long xor = a1 ^ a2; System.out.println(xor); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Stack; public class ProblemD { public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] data = s.readLine().split(" "); double a = Double.valueOf(data[0]); double v = Double.valueOf(data[1]); String[] line = s.readLine().split(" "); double l = Double.valueOf(line[0]); double d = Double.valueOf(line[1]); double w = Double.valueOf(line[2]); double ans = solve(a, v, l, d, w); out.println(String.format("%.07f", ans)); out.flush(); } private static double solve(double a, double v, double l, double d, double w) { double maxSpeedAtD = Math.sqrt(2 * d / a) * a; if (v <= w || maxSpeedAtD <= w) { // okay. just go double maxSpeedAtL = Math.sqrt(2 * l / a) * a; if (maxSpeedAtL <= v) { return Math.sqrt(2 * l / a); } else { double timeToMaxSpeed = v / a; double leftDist = l - 0.5 * a * timeToMaxSpeed * timeToMaxSpeed; return timeToMaxSpeed + leftDist / v; } } double time = 0.0d; double maxSpeedTime = Math.sqrt((d / a) + (w * w / (2 * a * a))); double maxSpeed = maxSpeedTime * a; if (maxSpeed <= v) { time = maxSpeedTime + (a * maxSpeedTime - w) / a; } else { double vtime = (2 * a * d + w * w - 2 * v * v) / (2 * a * v); time = v / a + vtime + (v - w) / a; } // after that, just go. double timeToV = (v - w) / a; double timeToVLen = timeToV * w + 0.5 * timeToV * (v - w); if (timeToVLen <= l - d) { double leftLen = l - d - timeToVLen; time += timeToV + leftLen / v; } else { time += (-w + Math.sqrt(w*w + a * (2 * l - 2 * d))) / a; } return time; } public static void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(sc.hasNext()) { int n=sc.nextInt(); String s=sc.next(); int sum=0; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') { sum++; } if(s.charAt(i)=='-'&&sum!=0) { sum--; } } System.out.println(sum); } } }
linear
1159_A. A pile of stones
CODEFORCES
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class A { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int a = scan.nextInt(); Queue<Integer> q = new LinkedList<Integer>(); q.add(4); q.add(7); boolean luck = false; while(!q.isEmpty() && !luck) { int f = q.poll(); if(a%f == 0) { luck = true; break; } if(f<a) { int t = (f+"").length(); int tt = (int)Math.pow(10, t); q.add(tt*4+f); q.add(tt*7+f); } } if(luck) System.out.println("YES"); else System.out.println("NO"); } }
constant
122_A. Lucky Division
CODEFORCES
import java.util.*; import java.io.*; public class A { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out, false); int n = scanner.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } Arrays.sort(arr); int[] cols = new int[n]; Arrays.fill(cols, -1); int ans = 0; for(int i = 0; i < n; i++) { if (cols[i] == -1) { cols[i] = ans++; for(int j = i + 1; j < n; j++) { if (arr[j] % arr[i] == 0) cols[j] = cols[i]; } } } out.println(ans); out.flush(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.StringTokenizer; import java.util.HashMap; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); F2BlokiRavnoiSummiUslozhnennayaRedakciya solver = new F2BlokiRavnoiSummiUslozhnennayaRedakciya(); solver.solve(1, in, out); out.close(); } static class F2BlokiRavnoiSummiUslozhnennayaRedakciya { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] sum = new int[n]; int prev = 0; for (int i = 0; i < n; i++) { sum[i] = in.nextInt() + prev; prev = sum[i]; } HashMap<Integer, List<Pair<Integer, Integer>>> blocks = new HashMap<>(); int max = 0; int maxS = 0; for (int i = 0; i < n; i++) { for (int h = i; h >= 0; h--) { int s = sum[i]; if (h > 0) { s -= sum[h - 1]; } blocks.putIfAbsent(s, new ArrayList<>()); List<Pair<Integer, Integer>> l = blocks.get(s); if (l.isEmpty() || l.get(l.size() - 1).sc < h) { l.add(new Pair<>(h, i)); } if (l.size() > max) { max = l.size(); maxS = s; } } } out.println(max); for (int i = 0; i < max; i++) { out.println(String.format("%d %d", blocks.get(maxS).get(i).fs + 1, blocks.get(maxS).get(i).sc + 1)); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class Pair<T, K> { T fs; K sc; public Pair(T fs, K sc) { this.fs = fs; this.sc = sc; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class CF125D2A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("0 0 " + sc.nextInt()); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.StringTokenizer; public class solver { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { new solver().solve(); } public void solve() { int n = in.nextInt(); int[]tab = new int[n]; int sum = 0; for (int i = 0; i < n; i++) { tab[i] = in.nextInt(); sum += tab[i]; } Arrays.sort(tab); int v1 = 0; int count = 0; for (int i = tab.length - 1; i >= 0; i--) { v1 += tab[i]; count++; if (v1 > getSum(i, tab)) { break; } } out.println(count); in.close(); out.close(); } public int getSum(int index, int[]tab) { int sum = 0; for (int i = 0; i < index; i++) sum += tab[i]; return sum; } public int max(int a, int b) { if (a > b) return a; else return b; } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { System.err.println(e); return ""; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } BigInteger nextBigInt() { return new BigInteger(next()); } void close() { try { br.close(); } catch (IOException e) { } } }
nlogn
160_A. Twins
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; public class C { public static void main(String[] args) throws Exception { BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int t = Integer.parseInt(buffer.readLine()); while (t-- > 0) { int n = Integer.parseInt(buffer.readLine()); ArrayList<Integer>list = new ArrayList<>(); for (int i = 0; i < n; i++) { int a = Integer.parseInt(buffer.readLine()); if (a == 1) list.add(1); else { for (int j = list.size()-1; j >= 0; j--) { if (list.get(j)+1 == a) break; list.remove(list.size()-1); } list.remove(list.size()-1); list.add(a); } for (int j = 0; j < list.size(); j++) { sb.append(list.get(j)); if (j == list.size()-1) sb.append("\n"); else sb.append("."); } } } System.out.println(sb); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
// package com.company.codeforces; import java.util.*; public class Solution { static int n,m,h[][],v[][]; public static void main(String[] args) { Scanner input=new Scanner(System.in); n=input.nextInt(); m=input.nextInt(); int k=input.nextInt(); h=new int[n][m-1]; for (int i = 0; i <n ; i++) { for (int j = 0; j <m-1 ; j++) { h[i][j]=input.nextInt(); } } v=new int[n][m]; for (int i = 0; i <n-1 ; i++) { for (int j = 0; j <m ; j++) { v[i][j]=input.nextInt(); } } int ans[][]=new int[n][m]; dp=new int[501][501][11]; for (int aa[]:ans ) { Arrays.fill(aa,-1); } if (k%2==0) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ans[i][j] = dfs(i, j, k / 2) * 2; } } } for (int i = 0; i <n ; i++) { for (int j = 0; j <m ; j++) { System.out.print(ans[i][j]+" "); } System.out.println(); } } static int dp[][][]; private static int dfs(int i, int j, int k) { if (k==0) return 0; if (dp[i][j][k]!=0){ // System.out.println("hit"); return dp[i][j][k]; } //left int ans=Integer.MAX_VALUE; if (j-1>=0) ans=dfs(i, j-1, k-1)+h[i][j-1]; if (i<n-1) ans=Math.min(ans,dfs(i+1, j, k-1)+v[i][j]); if (i>0) ans=Math.min(ans,dfs(i-1, j, k-1)+v[i-1][j]); if (j<m-1) ans=Math.min(ans,dfs(i, j+1, k-1)+h[i][j]); return dp[i][j][k]= ans; } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Stack; public class C { private static PrintWriter out = new PrintWriter(System.out); public static void solve() { In in = new In(); int tests = in.ni(); while (tests-- > 0) { int n = in.ni(); int[] a = in.nia(n); Stack<Integer> st = new Stack<>(); StringBuilder sb = new StringBuilder(); for (int num : a) { // System.out.println("Checking " + num); if (st.isEmpty()) { st.push(num); sb.append(num); } else { // increment current level if (num == st.peek() + 1) { st.pop(); st.push(num); while (sb.length() > 0 && sb.charAt(sb.length() - 1) != '.') { sb.deleteCharAt(sb.length() - 1); } sb.append(num); } // expand current level by 1 else if (num == 1) { st.push(num); sb.append("."); sb.append(num); } // increment higher level else { // search which higher level is the previous of the current number while (!st.isEmpty() && st.peek() + 1 != num) { st.pop(); while (sb.length() > 0 && sb.charAt(sb.length() - 1) != '.') { sb.deleteCharAt(sb.length() - 1); } if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1); } // System.out.println(" " + st.toString() + " " + sb.toString()); if (!st.isEmpty() && st.peek() + 1 == num) { st.pop(); st.add(num); while (sb.length() > 0 && sb.charAt(sb.length() - 1) != '.') { sb.deleteCharAt(sb.length() - 1); } sb.append(num); } } } // System.out.println(">>" + st.toString()); out.println(sb); } } } public static void main(String[] args) throws IOException { // long start = System.nanoTime(); solve(); // System.out.println("Elapsed: " + (System.nanoTime() - start) / 1000000 + // "ns"); out.flush(); } @SuppressWarnings("unused") private static class In { final private static int BUFFER_SIZE = 1024; private byte[] buf; private InputStream is; private int buflen; private int bufptr; public In() { is = System.in; buf = new byte[BUFFER_SIZE]; buflen = bufptr = 0; } public In(String input) { is = new ByteArrayInputStream(input.getBytes()); buf = new byte[BUFFER_SIZE]; buflen = bufptr = 0; } public int readByte() { if (bufptr >= buflen) { try { buflen = is.read(buf); } catch (IOException ioe) { throw new InputMismatchException(); } bufptr = 0; } if (buflen <= 0) return -1; return buf[bufptr++]; } public boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } /* Next character */ public char nc() { return (char) skip(); } /* Next double */ public double nd() { return Double.parseDouble(ns()); } /* Next string */ public String ns() { final StringBuilder sb = new StringBuilder(); int b = skip(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } /* Next integer */ public int ni() { boolean minus = false; int num = 0; int b; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); b = readByte(); } return minus ? -num : num; } /* Next long */ public long nl() { boolean minus = false; long num = 0; int b; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); b = readByte(); } return minus ? -num : num; } /* Next integer 1D array */ public int[] nia(int n) { final int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = ni(); return arr; } /* Next long 1D array */ public long[] nla(int n) { final long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nl(); return arr; } /* Next string 1D array */ public String[] nsa(int n) { final String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = ns(); return arr; } /* Next char 1D array */ public char[] nca(int n) { final char[] arr = new char[n]; for (int i = 0; i < n; i++) arr[i] = nc(); return arr; } /* Next double 1D array */ public double[] nda(int n) { final double[] arr = new double[n]; for (int i = 0; i < n; i++) arr[i] = nc(); return arr; } /* Next integer matrix */ public int[][] nim(int n, int m) { final int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = ni(); return arr; } /* Next long matrix */ public long[][] nlm(int n, int m) { final long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nl(); return arr; } /* Next string matrix */ public String[][] nsm(int n, int m) { final String[][] arr = new String[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = ns(); return arr; } /* Next char matrix */ public char[][] ncm(int n, int m) { final char[][] arr = new char[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nc(); return arr; } /* Next double matrix */ public double[][] ndm(int n, int m) { final double[][] arr = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nd(); return arr; } public static void log(Object... o) { System.out.println(Arrays.deepToString(o)); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; // Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail public class Ideone { public static void main(String args[] ) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n,i,j,k,temp ; n = ni(br.readLine()); int[] a = nia(br); Arrays.sort(a); int c = 0; for( i = 0; i< n ; i++) { if(a[i] > 0) { c++; temp = a[i]; for(j = i+1; j< n; j++) { if(a[j] % temp == 0) a[j] = 0; } } } System.out.println(c); } static Integer[] nIa(BufferedReader br) throws Exception{ String sa[]=br.readLine().split(" "); Integer [] a = new Integer [sa.length]; for(int i = 0; i< sa.length; i++){ a[i]= ni(sa[i]); } return a; } static int[] nia(BufferedReader br) throws Exception{ String sa[]=br.readLine().split(" "); int [] a = new int [sa.length]; for(int i = 0; i< sa.length; i++){ a[i]= ni(sa[i]); } return a; } static int ni(String s){ return Integer.parseInt(s); } static float nf(String s){ return Float.parseFloat(s); } static double nd(String s){ return Double.parseDouble(s); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import org.omg.CORBA.UNKNOWN; public class HelloWorld { InputReader input; PrintWriter output; BufferedReader inp; void run(){ output = new PrintWriter(new OutputStreamWriter(System.out)); input = new InputReader(System.in); inp = new BufferedReader(new InputStreamReader(System.in)); solve(); output.flush(); } public static void main(String[] args){ new HelloWorld().run(); } long stps; long gcd(long a, long b) { if(b == 0 || a == 0) { return 0; } return a/b + gcd(b, a%b); } void solve() { long a = input.readLong(); long b = input.readLong(); stps = gcd(a, b); output.println(stps); } class node implements Comparable<node>{ int destination; int direction; int distance; public node(int destination, int distance, int direction) { this.direction = direction; this.distance = distance; this.destination = destination; } public int compareTo(node b) { return this.distance - b.distance; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public Long readLong() { return Long.parseLong(readString()); } public Double readDouble() { return Double.parseDouble(readString()); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
constant
343_A. Rational Resistance
CODEFORCES
//app.は全部けす import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; //流す前にfinalにする public final class EcRound35DApplication { public static void main(String[] args) { Input input = new Input(); input = SystemInput(); List<String> resultList = run(input); for(String result:resultList){ System.out.println(result); } } //流す前にstaticにする private static void tester(Integer no,List<Integer> inputList,List<String> answer) { Input input = new Input(); input.setInput(inputList); List<String> result = run(input); if(result.equals(answer)) { System.out.println("No." + no + ":OK"); } else { System.out.println("No." + no + ":failed"); System.out.println("result:" + result); System.out.println("answer:" + answer); } } //流す前にstaticにする private static Input SystemInput() { Input input = new Input(); Scanner sc = new Scanner(System.in); List<Integer> inputList = new ArrayList<Integer>(); while(sc.hasNextInt()) { inputList.add(sc.nextInt()); } input.setInput(inputList); sc.close(); return input; } //流す前にstaticにする private static List<String> run(Input input) { List<String> result = new ArrayList<String>(); List<Integer> permutation = input.getPermutationList(); Integer count; count = inversion(permutation); for(Integer i = 0;i < input.getQueryNum();i++) { count = count + change(input.getQuery(i)); result.add(evenOdd(count)); } return result; } //カウントする private static Integer inversion(List<Integer>permutation) { String result = new String(); Integer inversionCount = 0; for(Integer i = 0; i < permutation.size(); i++) { for(Integer j = i + 1; j < permutation.size(); j++) { if(permutation.get(i) > permutation.get(j)) { inversionCount++; } } } return inversionCount; } //交換時追加分カウント private static Integer change(Query query) { Integer result; result = query.getLength() * (query.getLength() - 1) / 2; return result; } //判定する private static String evenOdd(Integer i) { if(i % 2 == 0) { return "even"; } else { return "odd"; } } private static class Query{ private Integer l; private Integer r; public void setQuery(Integer l,Integer r) { this.l = l; this.r = r; } public Integer getL() { return l; } public void setL(Integer l) { this.l = l; } public Integer getR() { return r; } public void setR(Integer r) { this.r = r; } public Integer getLength(){ return r - l + 1; } } //流す前にstaticにする private static class Input{ private Integer length; private List<Integer> permutationList = new ArrayList<Integer>(); private Integer queryNum; private List<Query> queryList = new ArrayList<Query>(); public void setInput(List<Integer> inputList) { this.length = inputList.get(0); setPermutationList(inputList.subList(1, length+1)); this.queryNum = inputList.get(length+1); for(Integer j = length+2; j < inputList.size()-1; j = j + 2) { addQueryList(inputList.get(j),inputList.get(j+1)); } // checkInput(); } public void checkInput() { System.out.println("permutation length:" + permutationList.size()); System.out.println("permutation:" + permutationList); System.out.println("query length:" + queryList.size()); System.out.println("queries:"); for(Integer i = 0;i < queryList.size();i++) { System.out.println(this.getQueryL(i) + " " + this.getQueryR(i)); } } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public List<Integer> getPermutationList() { return permutationList; } public void setPermutationList(List<Integer> permutationList) { this.permutationList = permutationList; } public Integer getPermutation(Integer i) { return permutationList.get(i); } public void addPermutationList(Integer newPermutation) { this.permutationList.add(newPermutation); } public Integer getQueryNum() { return queryNum; } public void setQueryNum(Integer queryNum) { this.queryNum = queryNum; } public Query getQuery(Integer i) { return queryList.get(i); } public Integer getQueryL(Integer i) { return queryList.get(i).getL(); } public Integer getQueryR(Integer i) { return queryList.get(i).getR(); } public List<Query> getQueryList() { return queryList; } public void setQueryList(List<Query> queryList) { this.queryList = queryList; } public void addQueryList(Query newQuery) { this.queryList.add(newQuery); } public void addQueryList(Integer l,Integer r) { Query newQuery = new Query(); newQuery.setQuery(l, r); addQueryList(newQuery); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class A { static int[] parent; public static int find(int x) { if (x == parent[x]) return x; return parent[x] = find(parent[x]); } public static void union(int x, int y) { int px = find(x); int py = find(y); if (px != py) { parent[py] = px; } } public static void main(String[] args) throws Exception { int numCnt = (int) nextLong(); long k = nextLong(); parent = new int[numCnt]; for (int i = 0; i < parent.length; i++) { parent[i] = i; } Long[] ar=new Long[numCnt]; for (int i = 0; i < numCnt; i++) { ar[i] = nextLong(); } Arrays.sort(ar); for (int i = 0; i < ar.length; i++) { long req = ar[i] * k; int l=0,h=ar.length,mid; while(l<h){ mid=l+(h-l)/2; if(ar[mid]<req){ l=mid+1; }else{ h=mid; } } if(l<ar.length&&ar[l]==req){ union(i,l); } } int[] count = new int[numCnt]; for (int i = 0; i < parent.length; i++) { count[find(i)]++; } int res = 0; for (int i = 0; i < numCnt; i++) { res += (int) ((count[i] + 1) / 2.0); } System.out.println(res); } static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer tokenizer = new StringTokenizer(""); static long nextLong() throws Exception { return Long.parseLong(next()); } static double nextDouble() throws Exception { return Double.parseDouble(next()); } static String next() throws Exception { while (true) { if (tokenizer.hasMoreTokens()) { return tokenizer.nextToken(); } String s = br.readLine(); if (s == null) { return null; } tokenizer = new StringTokenizer(s); } } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.io.BufferedOutputStream; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Aeroui */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Kattio in = new Kattio(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, Kattio in, PrintWriter out) { int n = in.nextInt(); int r = in.nextInt(); double[] xs = new double[n]; double[] ys = new double[n]; TreeSet<TaskC.Pair> set = new TreeSet<>(); for (int i = 0; i < n; ++i) { xs[i] = in.nextDouble(); ys[i] = (double) Integer.MIN_VALUE; if (i == 0) { // the first one out.printf("%f", (double) r); ys[i] = (double) r; set.add(new TaskC.Pair(xs[i], ys[i])); } else { for (TaskC.Pair p : set) { double maximum = p.x; double diffX = (xs[i] - maximum) * (xs[i] - maximum); if (diffX <= r * r * 4.0) { ys[i] = Math.max(ys[i], p.y + Math.sqrt(r * r * 4.0 - diffX)); continue; } } if (ys[i] < 0) ys[i] = (double) r; set.add(new TaskC.Pair(xs[i], ys[i])); out.printf(" %f", ys[i]); } } } private static class Pair implements Comparable<TaskC.Pair> { double x; double y; public Pair(double x, double y) { this.x = x; this.y = y; } public int compareTo(TaskC.Pair p) { if (this.y - p.y < 0) return 1; return -1; } } } static class Kattio extends PrintWriter { private BufferedReader r; private String line; private StringTokenizer st; private String token; public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class C { public static final long MAX = 1000000000L; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok1 = new StringTokenizer(br.readLine()); final int n = Integer.parseInt(tok1.nextToken()); final long k = Integer.parseInt(tok1.nextToken()); StringTokenizer tok2 = new StringTokenizer(br.readLine()); int[] array = new int[n]; for(int i = 0; i < n; i++){ array[i] = Integer.parseInt(tok2.nextToken()); } int size = n; Arrays.sort(array); boolean[] skip = new boolean[n]; for(int i = 0; i < n; i++){ if(skip[i]){ size--; continue; } long input = array[i]; input *= k; if(input > MAX){ continue; } final int pos = Arrays.binarySearch(array, (int)(input)); if(pos >= 0 && !skip[pos]){ skip[pos] = true; } } System.out.println(size); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; /* spar5h */ public class cf3 implements Runnable{ final static long mod = (long)1e9 + 7; static long modExp(long x, long pow) { x = x % mod; long res = 1; while (pow > 0) { if (pow % 2 == 1) res = res * x % mod; pow = pow / 2; x = x * x % mod; } return res; } public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int t = 1; while(t-- > 0) { long x = s.nextLong(), k = s.nextLong(); if(x == 0) { w.println(0); continue; } x = x % mod; long res = (modExp(2, k + 1) * x % mod + 1) % mod; res = (res + mod - modExp(2, k)) % mod; w.println(res); } w.close(); } 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 String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new cf3(),"cf3",1<<26).start(); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.*; import java.io.*; import java.text.*; import java.math.*; import static java.lang.Integer.*; import static java.lang.Double.*; import java.lang.Math.*; public class two_squares { public static void main(String[] args) throws Exception { new two_squares().run(); } public void run() throws Exception { FastIO file = new FastIO(); double x1 = file.nextInt(); double y1 = file.nextInt(); double x2 = file.nextInt(); double y2 = file.nextInt(); double x3 = file.nextInt(); double y3 = file.nextInt(); double x4 = file.nextInt(); double y4 = file.nextInt(); double minx1, maxx1, miny1, maxy1; minx1 = Math.min(x1, Math.min(x2, Math.min(x3, x4))); maxx1 = Math.max(x1, Math.max(x2, Math.max(x3, x4))); miny1 = Math.min(y1, Math.min(y2, Math.min(y3, y4))); maxy1 = Math.max(y1, Math.max(y2, Math.max(y3, y4))); double x5 = file.nextInt(); double y5 = file.nextInt(); double x6 = file.nextInt(); double y6 = file.nextInt(); double x7 = file.nextInt(); double y7 = file.nextInt(); double x8 = file.nextInt(); double y8 = file.nextInt(); double minx2, maxx2, miny2, maxy2; minx2 = Math.min(x5, Math.min(x6, Math.min(x7, x8))); maxx2 = Math.max(x5, Math.max(x6, Math.max(x7, x8))); miny2 = Math.min(y5, Math.min(y6, Math.min(y7, y8))); maxy2 = Math.max(y5, Math.max(y6, Math.max(y7, y8))); Point _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16; _1 = new Point(x1, y1); _2 = new Point(x2, y2); _3 = new Point(x3, y3); _4 = new Point(x4, y4); _5 = new Point(x5, y5); _6 = new Point(x6, y6); _7 = new Point(x7, y7); _8 = new Point(x8, y8); _9 = new Point(minx1, maxy1); _10 = new Point(minx1, miny1); _11 = new Point(maxx1, maxy1); _12 = new Point(maxx1, miny1); double m1 = (minx2 + maxx2) / 2; double m2 = (miny2 + maxy2) / 2; _13 = new Point(minx2, m2); _14 = new Point(m1, miny2); _15 = new Point(maxx2, m2); _16 = new Point(m1, maxy2); Point[] a = {_1, _2, _3, _4}; Point[] b = {_5, _6, _7, _8}; boolean works = false; Line[] aa = {new Line(_9,_10), new Line(_10, _12), new Line(_12, _11), new Line(_11, _9)}; Line[] bb = {new Line(_13, _14), new Line(_14, _15), new Line(_15, _16), new Line(_16, _13)}; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (aa[i].intersection(bb[i]) != null) { works = true; } } } for (Point p : b) { if (p.x >= minx1 && p.x <= maxx1 && p.y >= miny1 && p.y <= maxy1) { works = true; } } for (Point p : a) { boolean result = false; for (int i = 0, j = b.length - 1; i < b.length; j = i++) { if ((b[i].y > p.y) != (b[j].y > p.y) && (p.x < (b[j].x - b[i].x) * (p.y - b[i].y) / (b[j].y-b[i].y) + b[i].x)) { result = !result; } } if (result) works = true; } System.out.println(works ? "YES" : "NO"); } public static class Point { double x, y; public Point(double a, double b) { x = a; y = b; } } public static class Line { Point a, b; public Line(Point x, Point y) { a = x; b = y; } public Point intersection(Line o) { double x1 = a.x; double y1 = a.y; double x2 = b.x; double y2 = b.y; double x3 = o.a.x; double y3 = o.a.y; double x4 = o.b.x; double y4 = o.b.y; double denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))/denom; double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))/denom; if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) { return new Point((int) (x1 + ua*(x2 - x1)), (int) (y1 + ua*(y2 - y1))); } return null; } } public static class FastIO { BufferedReader br; StringTokenizer st; public FastIO() { 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; } } public static long pow(long n, long p, long mod) { if (p == 0) return 1; if (p == 1) return n % mod; if (p % 2 == 0) { long temp = pow(n, p / 2, mod); return (temp * temp) % mod; } else { long temp = pow(n, p / 2, mod); temp = (temp * temp) % mod; return (temp * n) % mod; } } public static long pow(long n, long p) { if (p == 0) return 1; if (p == 1) return n; if (p % 2 == 0) { long temp = pow(n, p / 2); return (temp * temp); } else { long temp = pow(n, p / 2); temp = (temp * temp); return (temp * n); } } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } }
constant
994_C. Two Squares
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class CF495A { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); long d = s.nextLong(); long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextLong(); } Arrays.sort(arr); long ans = 2; for (int i = 0; i < n - 1; i++) { if(arr[i + 1] - arr[i] > 2 * d){ ans += 2; }else if(arr[i + 1] - arr[i] == 2 * d){ ans += 1; } } System.out.println(ans); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.util.concurrent.*; public final class py_indent { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static int maxn=(int)(5e3+5); static long mod=(long)(1e9+7); static int add(long a,long b) { long ret=(a+b); if(ret>=mod) { ret%=mod; } return (int)ret; } public static void main(String args[]) throws Exception { int n=sc.nextInt();char[] a=new char[n+1];a[0]='s'; for(int i=1;i<=n;i++) { a[i]=sc.next().charAt(0); } int[][] dp=new int[n+1][maxn],sum=new int[n+1][maxn];dp[0][0]=1; sum[0][0]=1; for(int i=1;i<maxn;i++) { sum[0][i]=add(sum[0][i],sum[0][i-1]); } for(int i=1;i<=n;i++) { if(a[i]=='f') { continue; } int curr=0,idx=0; for(int j=i-1;j>=0;j--) { if(a[j]=='s') { idx=j;break; } else { curr++; } } for(int j=0;j<maxn;j++) { int up=Math.max(0,j-curr); long now=(sum[idx][maxn-1]-(up==0?0:sum[idx][up-1])); now=add(now,mod); dp[i][j]=add(dp[i][j],now); } sum[i][0]=dp[i][0]; for(int j=1;j<maxn;j++) { sum[i][j]=add(dp[i][j],sum[i][j-1]); } } //out.println(dp[2][0]+" "+dp[2][1]+" "+dp[2][2]); out.println(dp[n][0]);out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Locale; import java.io.OutputStream; import java.util.RandomAccess; import java.io.PrintWriter; import java.util.AbstractList; import java.io.Writer; import java.util.List; import java.util.Map; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.InputMismatchException; import java.util.TreeMap; 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(); long k = in.nextInt(); if (k == 1) { out.println(n); return; } long[] a = in.nextLongArray(n); ArrayUtils.safeSort(a); Map<Long, Integer> map = new TreeMap<Long, Integer>(); for (int i = 0; i < n; i++) { map.put(a[i], i); } int answer = 0; boolean[] visited = new boolean[n]; for (int i = 0; i < n; i++) { if (!visited[i]) { visited[i] = true; int count = 1; long cur = a[i]; while (true) { cur *= k; Integer index = map.get(cur); if (index == null) break; visited[index] = true; count++; } answer += NumberUtils.upDiv(count, 2); } } out.println(answer); } } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long[] nextLongArray(int count) { long[] result = new long[count]; for (int i = 0; i < count; i++) { result[i] = nextLong(); } 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(int i) { writer.println(i); } public void close() { writer.close(); } } class ArrayUtils { public static List<Long> asList(long[] array) { return new LongList(array); } private static class LongList extends AbstractList<Long> implements RandomAccess { long[] array; private LongList(long[] array) { this.array = array; } public Long set(int index, Long element) { long result = array[index]; array[index] = element; return result; } public Long get(int index) { return array[index]; } public int size() { return array.length; } } public static void safeSort(long[] array) { Collections.shuffle(asList(array)); Arrays.sort(array); } } class NumberUtils { public static int upDiv(int a, int b) { return a % b == 0 ? (a / b) : (a / b + 1); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.util.*; import java.util.Scanner; public class Def { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int t = s.nextInt(); while (t-->0) { int n = s.nextInt(); int[] arr = new int[n]; for (int i=0; i<n; i++) { arr[i] = s.nextInt(); } // int deep = 0; // System.out.println(n+" n"); List<Integer> al = new ArrayList<>(); al.add(1); System.out.println(1); for(int i=1; i<n;i++) { int len = al.size(); // for (int d =0; d<len; d++) { // System.out.print(al.get(d)+" "); // } // System.out.println(); if (arr[i] == 1) { for(int j=0; j<len; j++) { System.out.print(al.get(j)+"."); } System.out.println(1); al.add(1); }else if (arr[i] == arr[i-1] && arr[i]==1) { for(int j=0; j<len; j++) { System.out.print(al.get(j)+"."); } System.out.println(1); al.add(1); }else { for (int j=len-1; j>-1; j--) { if (al.get(j)+1 == arr[i]) { for(int k=0; k<j; k++) { System.out.print(al.get(k)+"."); } System.out.println(arr[i]); al.set(j, al.get(j)+1); al.subList(j+1, len).clear(); break; } } } } } s.close(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; /** * Created by hama_du on 15/09/10. */ public class A { private static final long MOD = 1000000009; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); long n = in.nextInt(); long correct = in.nextInt(); long k = in.nextInt(); long wrong = n - correct; long set = wrong * k + k - 1; if (set >= n) { out.println(correct); } else { long needExtraCorrect = n - (wrong * k + k - 1); long firstSet = needExtraCorrect + k - 1; long otherSet = correct - firstSet; long firstDouble = firstSet / k; otherSet += firstSet % k; long[][] mat = new long[][]{ {2, 2*k}, {0, 1}}; long[][] A = pow(mat, firstDouble, MOD); long score = (A[0][1] + otherSet) % MOD; out.println(score); } out.flush(); } public static long[][] pow(long[][] a, long n, long mod) { long i = 1; long[][] res = E(a.length); long[][] ap = mul(E(a.length), a, mod); while (i <= n) { if ((n & i) >= 1) { res = mul(res, ap, mod); } i *= 2; ap = mul(ap, ap, mod); } return res; } public static long[][] E(int n) { long[][] a = new long[n][n]; for (int i = 0 ; i < n ; i++) { a[i][i] = 1; } return a; } public static long[][] mul(long[][] a, long[][] b, long mod) { long[][] c = new long[a.length][b[0].length]; if (a[0].length != b.length) { System.err.print("err"); } for (int i = 0 ; i < a.length ; i++) { for (int j = 0 ; j < b[0].length ; j++) { long sum = 0; for (int k = 0 ; k < a[0].length ; k++) { sum = (sum + a[i][k] * b[k][j]) % mod; } c[i][j] = sum; } } return c; } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int next() { 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 char nextChar() { int c = next(); while (isSpaceChar(c)) c = next(); if ('a' <= c && c <= 'z') { return (char) c; } if ('A' <= c && c <= 'Z') { return (char) c; } throw new InputMismatchException(); } public String nextToken() { int c = next(); while (isSpaceChar(c)) c = next(); StringBuilder res = new StringBuilder(); do { res.append((char) c); c = next(); } while (!isSpaceChar(c)); return res.toString(); } public int nextInt() { int c = next(); while (isSpaceChar(c)) c = next(); int sgn = 1; if (c == '-') { sgn = -1; c = next(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c-'0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = next(); while (isSpaceChar(c)) c = next(); long sgn = 1; if (c == '-') { sgn = -1; c = next(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c-'0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
logn
338_A. Quiz
CODEFORCES
import java.util.*; public class helloWorld { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] ar = new int[200]; String str = in.next(); for(int i = 0; i < str.length(); i++) ar[ str.charAt(i) ]++; int ans = 100000; for(int i = 'A'; i < 'A' + m; i++) ans = Math.min(ans, ar[i]); ans *= m; System.out.println(ans); in.close(); } }
linear
1038_A. Equality
CODEFORCES
import java.util.*; public class B { public static void main(String[] args) { new B(new FastScanner()); } int hash(int i, int[] cc) { int res = i; for (int ii : cc) { res *= 8; res += ii; } return res; } int N, K, A; int[] lvl; int[] vs; // loyalty double calc(int i, int[] cc) { // Find the probability of winning double res = 0; int cnt = 0; for (int m=0; m<1<<N; m++) { double pt = 1.0; boolean passed = true; int nG = 0; int lvlcnt = 0; for (int j=0; j<N; j++) { int p = 10*cc[j]+vs[j]; int u = m&(1<<j); boolean votesGood = (u > 0); if (votesGood) nG++; else lvlcnt += lvl[j]; if ((p == 0)&&(votesGood)) passed = false; if ((p == 100)&&(!votesGood)) passed = false; if (!passed) break; if (votesGood) pt *= (p/100.0); else pt *= ((100-p)/100.0); } if (passed == false) continue; if (2*nG <= N) { // Calculate if we kill all senators double p1 = A/(1.0*(A+lvlcnt)); // Add in the probability of losing res += (1-p1)*pt; } } return 1.0-res; } HashMap<Integer, Double> memo; double go(int i, int[] cc) { if (i == -1) return calc(i, cc); int hv = hash(i, cc); Double rr = memo.get(hv); if (rr != null) return rr; double res = go(i-1, cc); for (int j=0; j<N; j++) { int cv = vs[j]+cc[j]*10; if (cv == 100) continue; cc[j]++; double rrr = go(i-1, cc); cc[j]--; if (rrr > res) res = rrr; } memo.put(hv, res); return res; } public B(FastScanner in) { N = in.nextInt(); K = in.nextInt(); A = in.nextInt(); memo = new HashMap<Integer, Double>(); lvl = new int[N]; vs = new int[N]; for (int i=0; i<N; i++) { lvl[i] = in.nextInt(); vs[i] = in.nextInt(); } int[] cs = new int[8]; double res = go(K-1, cs); System.out.printf("%.10f%n", res); } } class FastScanner{ int nextInt(){ try{ int c=System.in.read(); if(c==-1) return c; while(c!='-'&&(c<'0'||'9'<c)){ c=System.in.read(); if(c==-1) return c; } if(c=='-') return -nextInt(); int res=0; do{ res*=10; res+=c-'0'; c=System.in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c=System.in.read(); if(c==-1) return -1; while(c!='-'&&(c<'0'||'9'<c)){ c=System.in.read(); if(c==-1) return -1; } if(c=='-') return -nextLong(); long res=0; do{ res*=10; res+=c-'0'; c=System.in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res=new StringBuilder(""); int c=System.in.read(); while(Character.isWhitespace(c)) c=System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res=new StringBuilder(""); int c=System.in.read(); while(c=='\r'||c=='\n') c=System.in.read(); do{ res.append((char)c); c=System.in.read(); }while(c!='\r'&&c!='\n'); return res.toString(); }catch(Exception e){ return null; } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author Antonio "Teo" Alurralde */ public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer tok = new StringTokenizer(br.readLine()); int ax = Integer.parseInt(tok.nextToken()); int ay = Integer.parseInt(tok.nextToken()); tok = new StringTokenizer(br.readLine()); int bx = Integer.parseInt(tok.nextToken()); int by = Integer.parseInt(tok.nextToken()); tok = new StringTokenizer(br.readLine()); int cx = Integer.parseInt(tok.nextToken()); int cy = Integer.parseInt(tok.nextToken()); boolean ans = (bx < ax && cx < ax && by < ay && cy < ay) || (bx < ax && cx < ax && by > ay && cy > ay) || (bx > ax && cx > ax && by < ay && cy < ay) || (bx > ax && cx > ax && by > ay && cy > ay); System.out.print(ans?"YES":"NO"); } }
constant
1033_A. King Escape
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; import java.io.*; 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); solve(in, out); out.close(); } static String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { ar.add(p); } } } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static int findMax(int a[], int n, int vis[], int i, int d){ if(i>=n) return 0; if(vis[i]==1) return findMax(a, n, vis, i+1, d); int max = 0; for(int j=i+1;j<n;j++){ if(Math.abs(a[i]-a[j])>d||vis[j]==1) continue; vis[j] = 1; max = Math.max(max, 1 + findMax(a, n, vis, i+1, d)); vis[j] = 0; } return max; } public static void solve(InputReader sc, PrintWriter pw){ int i, j = 0; // int t = 1; int t = sc.nextInt(); u: while (t-- > 0) { int n = sc.nextInt(); int a[] = new int[n]; ArrayList<Integer> ar = new ArrayList<>(); ar.add(0); for(i=0;i<1000;i++){ ar.add(0); } int m = 1; for(i=0;i<n;i++){ a[i] = sc.nextInt(); if(a[i]==1){ ar.set(m,1); m++; } else{ while(m>0&&ar.get(m-1)!=a[i]-1){ m--; } ar.set(m-1,a[i]); } pw.print(ar.get(1)); for(j=2;j<m;j++){ pw.print("."+ar.get(j)); } pw.println(); } } } static long findOne(int n, int sz[], ArrayList<Integer> ar){ long paths = n-1; long till = 0; for(int v:ar){ paths += till*sz[v]; till += sz[v]; } return paths; } static void assignAnc(ArrayList<Integer> ar[],int sz[], int pa[] ,int curr, int par){ sz[curr] = 1; pa[curr] = par; for(int v:ar[curr]){ if(par==v) continue; assignAnc(ar, sz, pa, v, curr); sz[curr] += sz[v]; } } static int findLCA(int a, int b, int par[][], int depth[]){ if(depth[a]>depth[b]){ a = a^b; b = a^b; a = a^b; } int diff = depth[b] - depth[a]; for(int i=19;i>=0;i--){ if((diff&(1<<i))>0){ b = par[b][i]; } } if(a==b) return a; for(int i=19;i>=0;i--){ if(par[b][i]!=par[a][i]){ b = par[b][i]; a = par[a][i]; } } return par[a][0]; } static void formArrayForBinaryLifting(int n, int par[][]){ for(int j=1;j<20;j++){ for(int i=0;i<n;i++){ if(par[i][j-1]==-1) continue; par[i][j] = par[par[i][j-1]][j-1]; } } } static long lcm(int a, int b){ return a*b/gcd(a,b); } static class Pair1 { long a; long b; Pair1(long a, long b) { this.a = a; this.b = b; } } static class Pair implements Comparable<Pair> { int a; int b; int c; Pair(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int compareTo(Pair p) { // if(a!=p.a) // return a-p.a; // return b-p.b; return p.c - c; } } // static boolean isPrime(long n) { // if (n <= 1) // return false; // if (n <= 999) // return true; // if (n % 2 == 0 || n % 999 == 0) // return false; // for (int i = 5; i * i <= n; i = i + 6) // if (n % i == 0 || n % (i + 2) == 0) // return false; // return true; // } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 9992768); 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()); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class Quiz { public static int mod = 1000000009; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); long n = Long.parseLong(st.nextToken()); long m = Long.parseLong(st.nextToken()); long k = Long.parseLong(st.nextToken()); long d = n-m; n -= d*k; if (n <= 0) { System.out.println(m); return; } long sum = (n%k) + d*(k-1); sum += 2*k*(pow(2,n/k)-1); sum %= mod; System.out.println(sum); } public static long pow(long a, long n) { if (n == 0) return 1; long pow = pow(a,n/2); pow = pow*pow % mod; if (n % 2 == 1) pow = pow*a % mod; return pow; } }
logn
338_A. Quiz
CODEFORCES
import java.util.*; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count = sc.nextInt(); HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < count; i++) { set.add(sc.nextInt()); } ArrayList<Integer> list = new ArrayList<>(set); Collections.sort(list); for (int i = 0; i < list.size(); i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(i) % list.get(j) == 0 || list.get(j) % list.get(i) == 0) { list.remove(j); j--; } } } System.out.println(list.size()); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); String a=buffer.readLine(); int b=Integer.parseInt(a); if(b%4==0 || b%7==0 || b%44==0 || b%47==0 || b%74==0 || b%77==0 || b%444==0 || b%447==0 || b%474==0 || b%477==0 || b%744==0 || b%747==0 || b%774==0 || b%777==0) System.out.println("YES"); else System.out.println("NO"); }}
constant
122_A. Lucky Division
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Main { public static void main(String[] args) throws IOException { new Main().run(); } private void run() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); int[] arr = new int[n]; String[] line = reader.readLine().split("\\s"); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(line[i]); } Arrays.sort(arr); Set<Integer> numbers = new HashSet<>(); for (int i = 0; i < arr.length; i++) { Iterator<Integer> iter = numbers.iterator(); boolean contains = false; while (iter.hasNext()){ int elem = iter.next(); if(gcd(elem, arr[i]) == elem){ contains = true; } } if(!contains) numbers.add(arr[i]); } System.out.println(numbers.size()); } private int gcd(int a, int b){ while (a != b){ if(a > b) a -= b; else b -= a; } return a; } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ankur */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int ar[] = in.nextIntArray(n); long dp[][] = new long[n][n]; long ct = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (ar[i] > ar[j]) { dp[i][j]++; ct++; } } } for (int i = n - 2; i >= 0; i--) { for (int j = i + 1; j < n; j++) { dp[i][j] += dp[i + 1][j]; } } int m = in.nextInt(); for (int i = 0; i < m; i++) { int l = in.nextInt() - 1; int r = in.nextInt() - 1; long val = (r - l + 1); long estimated = (val * (val - 1)) / 2; long change = estimated - dp[l][r]; //System.out.println(ct); ct = ct - dp[l][r]; dp[l][r] = change; ct += dp[l][r]; if (ct % 2 == 0) { out.println("even"); } else { out.println("odd"); } // System.out.println(ct); } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar; private int snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { //*-*------clare------ 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 int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { long n=nl(); if(n%2==0) { long a1=(long)Math.sqrt(n); long a2=(long)Math.sqrt(n/2); if(a1*a1==n || a2*a2*2==n) {pn("YES");return;} } pn("NO"); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; t=ni(); while(t-- > 0) {process();} out.flush();out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
//package round156; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class B { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), x = ni(), y = ni(); long c = nl(); int l = x-1, r = n-x; int u = y-1, d = n-y; long low = -1, high = 2*n+3; while(high - low > 1){ long t = (high + low) / 2; long num = diag(t, l, u) + diag(t, r, u) + diag(t, l, d) + diag(t, r, d) + hor(t, l) + hor(t, r) + hor(t, u) + hor(t, d) + 1; if(num >= c){ high = t; }else{ low = t; } } out.println(high); } long hor(long t, int n) { return Math.min(t, n); } long diag(long t, long r, long u) { if(t > 2+r+u-2){ return r*u; } long ret = t*(t-1)/2; if(t > r)ret -= (t-r)*(t-r-1)/2; if(t > u)ret -= (t-u)*(t-u-1)/2; return ret; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new B().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.PrintStream; import java.util.Scanner; /** * @author Roman Elizarov */ public class Round_146_A { public static void main(String[] args) { new Round_146_A().go(); } void go() { // read input Scanner in = new Scanner(System.in); int n = in.nextInt(); // solve long result = solve(n); // write result PrintStream out = System.out; out.println(result); } static long solve(int n) { if (n == 1) return 1; if (n == 2) return 2; if (n % 2 == 0) { if (n % 3 == 0) return (long)(n - 1) * (n - 2) * (n - 3); else return (long)n * (n - 1) * (n - 3); } else return (long)n * (n - 1) * (n - 2); } }
constant
235_A. LCM Challenge
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { static PrintWriter out = new PrintWriter(System.out); static FS in; static int N; static final boolean debug = false; static int inp[] = new int[] {1,2,3,2,1,0}; public static void main(String[] args) { in = new FS(); if(!debug) N = in.nextInt(); else N = inp.length; int x = solve(0, N/2-1, N/2, N-1); out.println("! "+(x+1)); out.flush(); out.close(); } static int solve(int l1, int r1, int l2, int r2) { int sz = r1-l1+1; if(sz <= 0) return -2; int a1 = query(l1); int a2 = query(l2); if(a1 == a2) return l1; if(sz == 1) return -2; int b1 = query(l1+sz/2); int b2 = query(l2+sz/2); if(b1 == b2) return l1 + sz/2; if(sz == 2) return -2; int d1 = a2-a1; int d2 = b2-b1; if((d1 < 0 && d2 > 0) || (d1 > 0 && d2 < 0)) { return solve(l1+1, l1 + sz/2 - 1, l2+1, l2 + sz/2 - 1); } else { return solve(l1 + sz/2 + 1, r1, l2 + sz/2 + 1, r2); } } static int query(int a) { out.println("? "+(a+1)); out.flush(); if(debug) return inp[a]; else return in.nextInt(); } static class FS{ BufferedReader br; StringTokenizer st; public FS() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch(Exception e) { throw null;} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());} double nextDouble() { return Double.parseDouble(next());} long nextLong() { return Long.parseLong(next());} int[] NIA(int n) { int r[] = new int[n]; for(int i = 0; i < n; i++) r[i] = nextInt(); return r; } long[] NLA(int n) { long r[] = new long[n]; for(int i = 0; i < n; i++) r[i] = nextLong(); return r; } char[][] grid(int r, int c){ char res[][] = new char[r][c]; for(int i = 0; i < r; i++) { char l[] = next().toCharArray(); for(int j = 0; j < c; j++) { res[i][j] = l[j]; } } return res; } } }
logn
1019_B. The hat
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class GeorgeAndInterestingGraph { public static void main(String[] args) { MyScanner sc = new MyScanner(); int N = sc.nextInt(); int M = sc.nextInt(); int[] edgeFrom = new int[M]; int[] edgeTo = new int[M]; for (int i = 0; i < M; i++) { edgeFrom[i] = sc.nextInt(); edgeTo[i] = sc.nextInt(); } int best = Integer.MAX_VALUE; boolean[][] adjMat = makeAdjMat(N, edgeFrom, edgeTo); for (int i = 0; i < N; i++) { boolean[][] mat = copyOfArray2d(adjMat); best = Math.min(best, count(mat, M, i)); } System.out.println(best); } public static boolean[][] copyOfArray2d(boolean[][] arr) { int N = arr.length; int M = arr[0].length; boolean[][] copy = new boolean[N][M]; for (int i = 0; i < N; i++) { System.arraycopy(arr[i], 0, copy[i], 0, M); } return copy; } public static int count(boolean[][] mat, int M, int center) { int N = mat.length; int centerCount = (mat[center][center]) ? 1 : 0; for (int i = 0; i < N; i++) { if (i != center) { if (mat[i][center]) { centerCount++; } if (mat[center][i]) { centerCount++; } } mat[i][center] = false; mat[center][i] = false; } int other = M - centerCount; int matches = bipartiteMatching(mat); return (2 * N - 1 - centerCount + other - matches + N - 1 - matches); } public static boolean[][] makeAdjMat(int N, int[] edgeFrom, int[] edgeTo) { boolean[][] mat = new boolean[N][N]; for (int i = 0; i < edgeFrom.length; i++) { int from = edgeFrom[i] - 1; int to = edgeTo[i] - 1; mat[from][to] = true; } return mat; } /** * Returns true if a matching for vertex 'u' is possible. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static boolean bipartiteMatchingHelper(boolean[][] bpGraph, int u, boolean[] seen, int[] matchR) { int N = bpGraph[0].length; for (int v = 0; v < N; v++) { if (bpGraph[u][v] && !seen[v]) { seen[v] = true; if (matchR[v] < 0 || bipartiteMatchingHelper(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchIJ, int[] matchJI) { int ans = bipartiteMatching(bpGraph, matchJI); for (int i = 0; i < matchJI.length; i++) { matchIJ[i] = -1; } for (int j = 0; j < matchJI.length; j++) { int i = matchJI[j]; if (i >= 0) { matchIJ[i] = j; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchJI) { int M = bpGraph.length; int N = bpGraph[0].length; for (int i = 0; i < N; i++) { matchJI[i] = -1; } int ans = 0; for (int u = 0; u < M; u++) { boolean[] seen = new boolean[N]; if (bipartiteMatchingHelper(bpGraph, u, seen, matchJI)) { ans++; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Overload of the bipartiteMatching function without output parameters. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph) { int N = bpGraph[0].length; int[] matchJI = new int[N]; return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. */ public static int bipartiteMatching(int[][] intGraph) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchIJ, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchIJ, matchJI); } /** * Converts an integer adjacency matrix of 1's and 0's to a boolean adjacency matrix. * Useful with bipartiteMatching, which takes adjancency matrix of boolean[][] as input (instead of int[][]). */ public static boolean[][] intToBooleanAdjMat(int[][] mat) { int M = mat.length; int N = mat[0].length; boolean[][] bMat = new boolean[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { bMat[i][j] = (mat[i][j] != 0); } } return bMat; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } 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; } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import javax.print.Doc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class taskB { public static void main(String[] args) throws IOException { new taskB().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; static String TASK = ""; void run() throws IOException { try { // reader = new BufferedReader(new FileReader(TASK + ".in")); reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); // writer = new PrintWriter(TASK + ".out"); tokenizer = null; solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int b[]; int l[]; int add[]; int n, k, A; double ans = 0; void solve() throws IOException { n = nextInt(); k = nextInt(); A = nextInt(); b = new int[n]; l = new int[n]; add = new int[n]; for (int i = 0; i < n; ++i) { b[i] = nextInt(); l[i] = nextInt(); } brute(0, k); writer.printf("%.10f", ans); } private void brute(int pos, int yet) { if (pos == n) { /*double prob[][] = new double[n + 1][n + 1]; prob[0][0] = 1; for (int i = 1; i <= n; ++i) { for (int sayYes = 1; sayYes <= i; ++sayYes) { prob[i][sayYes] = p[i - 1] * prob[i - 1][sayYes - 1]; } for (int sayYes = 0; sayYes <= i; ++sayYes) { prob[i][sayYes] = (1 - p[i - 1]) * prob[i - 1][sayYes]; } } double nowYes = 0; for (int i = 0; i <= n; ++i) { if (i >= (n + 2) / 2 ) nowYes += prob[n][i]; } */ double p[] = new double[n]; for (int i = 0; i < n; ++i) { p[i] = (l[i] + add[i]) / 100.0; } double r = 0; for (int i =0; i < (1 << n); ++i) { double pr =1 ; int sm = 0; for (int j =0 ; j < n; ++j) { if ((i & (1 << j)) > 0) { pr *= p[j]; } else { pr *= (1 - p[j]); sm += b[j]; } } int c = Integer.bitCount(i); if (c >= (n + 2) / 2) { r += pr; } else { r += pr * (1.0 * A / (A + sm)); } } ans = Math.max(ans, r); } else { for (int i = 0; i <= yet; ++i) { if (l[pos] + 10 * i > 100) continue; add[pos] = 10 * i; brute(pos + 1, yet - i); } } } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.BufferedWriter; import java.io.PrintWriter; import java.io.Writer; import java.io.OutputStream; import java.io.OutputStreamWriter; /** * 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { out.printLine(25); } } static class InputReader { private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } } 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); } } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; public class Main { static double max = 0.0; public static void main(String[] args) { Scanner r = new Scanner(System.in); int n = r.nextInt(); int k = r.nextInt(); int A = r.nextInt(); Person[] p = new Person[n]; for(int i = 0; i < n; i++){ int l = r.nextInt(); int prob = r.nextInt(); p[i] = new Person(l, prob); } int[] add = new int[n]; double res = dfs(0, k, p, add, n, A); System.out.println(res); } private static double dfs(int ptr, int k, Person[] p, int[] add, int n, int A) { if(k < 0)return 0; double res1 = 0; for(int m = 0; m < 1<<n; m++){ double win = 1; int cnt = 0; for(int i = 0; i < n; i++){ if((m & (1 << i)) == 0){ win *= (100-(p[i].p+add[i]))*1.0/100; }else{ win *= (add[i]+p[i].p)*1.0/100; cnt++; } } if(cnt > n/2){ res1 += win; }else{ int B = 0; for(int i = 0; i < n; i++){ if((m & (1 << i)) == 0){ B += p[i].l; } } win *= A*1.0/(A+B); res1 += win; } } double res2 = 0, res3 = 0; if(add[ptr]+p[ptr].p < 100){ add[ptr] += 10; res2 = dfs(ptr, k-1, p, add, n, A); add[ptr] -= 10; } if(ptr+1 < n){ res3 = dfs(ptr+1, k, p, add, n, A); } return Math.max(res1, Math.max(res2, res3)); } } class Person{ int l, p; public Person(int li, int pi){ l = li; p = pi; } public String toString(){ return String.format("[%d, %d]", l, p); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class LightItUp { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int previous = 0; int array[] = new int[n+1]; int answer = 0; StringTokenizer st1 = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++){ array[i] = Integer.parseInt(st1.nextToken()); if(i % 2 == 0){ answer += (array[i] - previous); } previous = array[i]; } if(n % 2 == 0){ answer += (m - previous); } previous = m; int max = Integer.MAX_VALUE; while(n-- != 0){ int temp = array[n]; if(n%2 == 0){ array[n] = array[n+1] - (previous - array[n]); } else{ array[n] = array[n+1] + (previous - array[n]); } previous = temp; max = Math.min(max, array[n]); } if(max>=-1){ System.out.println(answer); } else{ System.out.println(answer - (max+1)); } } }
linear
1000_B. Light It Up
CODEFORCES
import java.io.*; import java.util.*; public class G{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.flush();out.close(); } static class TaskE { class MinCostMaxFlow{ ArrayList<Edge> al[]; Edge ja[][]; int d[]; // shortest distances int N , S , T , maxFlow ; int minCost; final int gmax = Integer.MAX_VALUE / 100; int edges = 0; class Edge{ int u , flow, rid, cost; Edge(int a, int b, int c, int d){u = a; flow = b; cost = c; rid = d;} } void addEdge(int u , int v , int flow , int cost){ int lu = al[u].size(), lv = al[v].size(); al[u].add(new Edge(v, flow, cost, lv)); al[v].add(new Edge(u, 0, -cost, lu)); } void convertToArray(){ ja = new Edge[N][]; for(int i = 0; i < N; i++){ int sz = al[i].size(); ja[i] = new Edge[sz]; for(int j = 0; j < sz; j++){ ja[i][j] = al[i].get(j); } al[i].clear(); } } MinCostMaxFlow(int n , int source , int sink){ N = n; S = source; T = sink; maxFlow = 0; minCost = 0; al = new ArrayList[N]; d = new int[N]; for(int i = 0; i < N; i++){ al[i] = new ArrayList<>(); } } boolean BellmanFord(boolean check){ d[0] = 0; for(int i = 0; i < N - 1; i++){ for(int j = 0; j < N; j++){ for(Edge e : ja[j]){ if(e.flow == 0)continue; // not to consider reverse edges d[e.u] = Math.min(d[e.u] , d[j] + e.cost); } } } if(check){// check for negative cycles for(int j = 0; j < N; j++){ for(Edge e : ja[j]){ if(e.flow == 0)continue; if(d[j] + e.cost < d[e.u]) return false; } } }return true; } int node[]; // present node int visit[]; // 0 -> not added 1 -> not removed 2 -> removed int prv[], prve[]; // previous node for augmentation int dist[]; // min dist boolean simple(){ node = new int[N]; visit = new int[N]; prv = new int[N]; prve = new int[N]; dist = new int[N]; Arrays.fill(dist , gmax); node[0] = S; dist[0] = 0; int front = 1, back = 0; while(front != back){ int u = node[back++]; int distu = dist[u]; if(back == N)back = 0; visit[u] = 2; for(int i = 0; i < ja[u].length; i++){ Edge e = ja[u][i]; if(e.flow == 0)continue; int cdist = distu + e.cost; // no need of reduced cost if(cdist < dist[e.u]){ if(visit[e.u] == 0){ node[front] = e.u; if(++front == N)front = 0; }else if(visit[e.u] == 2){ if(--back == -1)back += N; node[back] = e.u; } visit[e.u] = 1; prve[e.u] = i; prv[e.u] = u; dist[e.u] = cdist; } } } return visit[T] != 0; } class pair{ int F; int S; pair(int a, int b){F = a; S = b;} } boolean dijkstra(){ visit = new int[N]; prv = new int[N]; prve = new int[N]; dist = new int[N]; Arrays.fill(dist, gmax); PriorityQueue<pair> pq = new PriorityQueue<>((A, B) -> Double.compare(A.S , B.S)); pq.add(new pair(S , 0)); dist[0] = 0; o : while(!pq.isEmpty()){ pair p = pq.poll(); while(dist[p.F] < p.S){ if(pq.isEmpty()) break o; // had a better val p = pq.poll(); } visit[p.F] = 2; for(int i = 0; i < ja[p.F].length; i++){ Edge e = ja[p.F][i]; if(e.flow == 0)continue; // important int cdist = p.S + (e.cost + d[p.F] - d[e.u]); // reduced cost if(cdist < dist[e.u]){ if(visit[e.u] == 2) return false; pq.add(new pair(e.u , cdist)); dist[e.u] = cdist; prv[e.u] = p.F; prve[e.u] = i; visit[e.u] = 1; } } } return visit[T] != 0; } int augment(){ int p = T; int min = gmax; while(p != 0){ int pp = prv[p], pe = prve[p]; int val = ja[pp][pe].flow; min = Math.min(min , val); p = pp; } p = T; while(p != 0){ int pp = prv[p], pe = prve[p]; ja[pp][pe].flow -= min; ja[p][ja[pp][pe].rid].flow += min; p = pp; } maxFlow += min; return min; } // if(dist[T] >= 0)return true; // non contributing flow boolean calSimple(){ // uncomment to check for negative cycles /* boolean possible = BellmanFord(true); if(!possible) return false; */ while(simple()){ /*if(dist[T] >= 0)return true;*/ minCost += dist[T] * augment(); } return true; } void updPotential(){ for(int i = 0; i < N; i++){ if(visit[i] != 0){ d[i] += dist[i] - dist[S]; } } } boolean calWithPotential(){ // set true to check for negative cycles // boolean possible = BellmanFord(false); // if(!possible) return false; while(dijkstra()){ int min = dist[T] + d[T] - d[S]; // getting back the original cost /*if(dist[T] >= 0)return true;*/ minCost += min * augment(); updPotential(); } return true; } } int n , m, k, c, d, a[], f[]; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); k = in.nextInt(); c = in.nextInt(); d= in.nextInt(); // S + n int maxl = n + k, T = n * maxl + 1; MinCostMaxFlow ans = new MinCostMaxFlow(T + 1, 0, T); a = new int[k + 1]; f = new int[n + 1]; for(int i = 1; i <= k; i++){ a[i] = in.nextInt(); f[a[i]]++; } for(int i = 1; i <= n; i++){ if(f[i] == 0)continue; ans.addEdge(0 , i , f[i], 0); } for(int i = 2; i <= n; i++){ for(int l = 0; l < maxl - 1; l++){ ans.addEdge(l * n + i , (l + 1) * n + i, k, c); } } for(int i = 1; i <= m; i++){ int a = in.nextInt(), b = in.nextInt(); for(int l = 0; l < maxl - 1; l++){ for(int p = 1; p <= k; p++){ if(a != 1) ans.addEdge(n * l + a, n * (l + 1) + b, 1, d * (2 * p - 1) + c); if(b != 1) ans.addEdge(n * l + b, n * (l + 1) + a, 1, d * (2 * p - 1) + c); } } } for(int l = 1; l < maxl; l++){ ans.addEdge(l * n + 1, T, k, 0); } ans.convertToArray(); ans.calWithPotential(); // ans.calSimple(); if(ans.maxFlow != k){ out.println("BUG"); }else{ out.println((int)ans.minCost); } } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
cubic
1187_G. Gang Up
CODEFORCES
import java.io.*; import java.util.*; public class Main { static int inf = (int) 1e9 + 7; static int n, m, a[][]; static ArrayList<Integer> used; static int num[]; static int ans; static void rec(int id) { if (id == used.size()) { check(); return; } for(int i = 0;i < n;i++) { num[id] = i; rec(id + 1); } } static void check() { int new_ans = 0; for(int i = 0;i < n;i++) { int max = 0; for(int j = 0;j < used.size();j++) { max = Math.max(max, a[(i + num[j]) % n][used.get(j)]); } new_ans += max; } ans = Math.max(ans, new_ans); } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); int test = nextInt(); while(test-- > 0) { n = nextInt(); m = nextInt(); a = new int [n][m]; for(int i = 0;i < n;i++) { for(int j = 0;j < m;j++) a[i][j] = nextInt(); } used = new ArrayList<>(); num = new int [n * m]; ans = 0; pair b[] = new pair[n * m]; for(int i = 0;i < n;i++) { for(int j = 0;j < m;j++) { b[i * m + j] = new pair(a[i][j], j); } } Arrays.sort(b, new pair()); for(int i = b.length - 1;i >= Math.max(0, b.length - 5);i--) { int v = b[i].y; boolean bad = false; for(int j = 0;j < used.size();j++) if (used.get(j) == v) bad = true; if (!bad) used.add(v); } rec(0); pw.println(ans); } pw.close(); } static BufferedReader br; static StringTokenizer st = new StringTokenizer(""); static PrintWriter pw; static String next() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } class pair implements Comparator<pair>{ int x, y; pair(int x, int y) { this.x = x; this.y = y; } pair() {} @Override public int compare(pair o1, pair o2) { return Integer.compare(o1.x, o2.x); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; public class C15A { public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int t=sc.nextInt(); double nm[][]=new double[n][2]; int a=0; int b=0; for(int i=0;i<n;i++){ a=sc.nextInt(); b=sc.nextInt(); nm[i][0]=a-(double)b/2; nm[i][1]=a+(double)b/2; } Arrays.sort(nm, new ArrayColumnComparator(1)); int sum=0; for(int i=0;i<n-1;i++){ if(nm[i+1][0]-nm[i][1]==t) sum++; else if(nm[i+1][0]-nm[i][1]>t){ sum+=2; } } System.out.println(sum+2); } } class ArrayColumnComparator implements Comparator { private int cm = 0; ArrayColumnComparator(int cm) { this.cm = cm; } public int compare(Object o1, Object o2) { double[] row1 = (double[])o1; double[] row2 = (double[])o2; int i; if (row1[cm]>row2[cm]) i=1; else if(row1[cm]<row2[cm]) i=-1; else i=0; return i; } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.*; public class Main { static boolean used[][]; static int n; static int m; public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader("input.txt")); PrintWriter out = new PrintWriter("output.txt"); n = nextInt(); m = nextInt(); int k = nextInt(); used = new boolean[n][m]; Deque<point> deq = new ArrayDeque<>(); for (int i = 0; i < k; i++) { deq.addLast(new point(nextInt() - 1, nextInt() - 1)); used[deq.peekLast().x][deq.peekLast().y] = true; } point last = new point(0, 0); while (!deq.isEmpty()) { point v = deq.pollFirst(); int x = v.x; int y = v.y; if (checker(x, y + 1)) { last = new point(x, y + 1); deq.addLast(new point(x, y + 1)); used[x][y + 1] = true; } if (checker(x, y - 1)) { last = new point(x, y - 1); deq.addLast(new point(x, y - 1)); used[x][y - 1] = true; } if (checker(x + 1, y)) { last = new point(x + 1, y); deq.addLast(new point(x + 1, y)); used[x + 1][y] = true; } if (checker(x - 1, y)) { last = new point(x - 1, y); deq.addLast(new point(x - 1, y)); used[x - 1][y] = true; } } out.println(last.x + 1 + " " + (last.y + 1)); out.close(); } static boolean checker(int x, int y) { if (x < n && y < m && x >= 0 && y >= 0 && !used[x][y]) return true; return false; } static StringTokenizer st = new StringTokenizer(""); static BufferedReader br; static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } class point { int x, y; public point(int x, int y) { this.x = x; this.y = y; } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Solution { BufferedReader in; StringTokenizer st; PrintWriter out; int n, m, k; int[] x, y; char[] qx = new char[4000000], qy = new char[4000000]; int b, e; char[][] d; int[] dx = { -1, 0, 1, 0 }, dy = { 0, -1, 0, 1 }; void bfs() { b = e = 0; for (int i = 0; i < d.length; i++) { Arrays.fill(d[i], (char)(1 << 14)); } for (int i = 0; i < k; ++i) { qx[e] = (char) x[i]; qy[e++] = (char) y[i]; d[x[i]][y[i]] = 0; } for (; b < e; ++b) { int x = qx[b]; int y = qy[b]; for (int i = 0; i < 4; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx >= 0 && nx < n && ny >= 0 && ny < m) if (d[nx][ny] > d[x][y] + 1) { d[nx][ny] = (char) (d[x][y] + 1); qx[e] = (char) nx; qy[e++] = (char) ny; } } } } void solve() throws IOException { n = ni(); m = ni(); k = ni(); x = new int[k]; y = new int[k]; for (int i = 0; i < k; ++i) { x[i] = ni() - 1; y[i] = ni() - 1; } d = new char[n][m]; bfs(); int x = -1, y = -1, last = -1; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) if (d[i][j] > last) { last = d[i][j]; x = i; y = j; } ++x; ++y; out.println(x + " " + y); } public Solution() throws IOException { Locale.setDefault(Locale.US); in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); solve(); in.close(); out.close(); } String nline() throws IOException { return in.readLine(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nline()); } 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 { new Solution(); } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; public class CTask { public static void main(String[] args) throws IOException { MyInputReader in = new MyInputReader(System.in); HashMap<Character, Integer> m = new HashMap<Character, Integer>(); int n = in.nextInt(); char[] s = in.next().toCharArray(); for (int i = 0; i < n; i++) { m.put(s[i], 0); } int mx = m.size(); int start = 0; int end = 0; int min = Integer.MAX_VALUE; int cur = 0; while (end < n) { while (end < n && cur != mx) { int x = m.get(s[end]); if (x == 0) { cur += 1; } m.put(s[end], x + 1); end += 1; } while (start <= end && cur == mx) { int x = m.get(s[start]); m.put(s[start], x - 1); if (x - 1 == 0) { cur -= 1; } start += 1; } min = Math.min(min, end - start + 1); } System.out.println(min); } static class Pair { long x; long y; public Pair(long x, long y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (x != pair.x) return false; return y == pair.y; } @Override public int hashCode() { int result = (int) (x ^ (x >>> 32)); result = 31 * result + (int) (y ^ (y >>> 32)); return result; } } static class MyInputReader { public BufferedReader reader; public StringTokenizer tokenizer; public MyInputReader(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
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastReader fr =new FastReader(); PrintWriter op =new PrintWriter(System.out); long n =fr.nextLong() ,k =fr.nextLong() ,d =(long)Math.sqrt(9l+8l*(n+k)) ; d -= 3l ; d /=2l ;op.println(n-d) ; op.flush(); op.close(); } 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(); } String nextLine() { String str =""; try { str =br.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()) ; } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.*; import java.util.*; public class ModifyLongest { InputStream is; PrintWriter out; String INPUT = ""; //boolean codechef=true; boolean codechef=true; void solve() { /* long l=ni(),r=ni(),x=ni(),y=ni(); long prod=x; prod*=y; int cnt=0; if(l==r && r==x && x==y && x==1) { System.out.println(1); return; } //HashSet<Long> set=new HashSet<>(); for(long i=2;i<=Math.sqrt(prod);i++) { if(prod%i==0) { if(Math.min(i,prod/i)>=l && Math.max(i,prod/i)<=r && gcd(i,prod/i)==x) { //set.add(fnc2(i,prod/i)); //set.add(fnc2(prod/i,i)); if(i!=prod/i)cnt+=2; else cnt++; } } } ArrayList<Long> factors=new ArrayList<>(); while(prod!=1) { long currF=PollardRho(prod); while(prod%currF!=0) { prod/=currF; factors.add(currF); } } if(l==1) { System.out.println((cnt+2)); } else { System.out.println(cnt); } */ long mod=1000000007; long x=nl(),k=nl(); if(x==0) { System.out.println(0); return; } long val=calc((pow(2,k,mod)*(x%mod))%mod); val-=calc(((pow(2,k,mod)*(x%mod))%mod-(pow(2,k,mod)-1)-1+mod)%mod); //val*=2; val=(val+mod)%mod; val=(val*inv(pow(2,k,mod),mod))%mod; System.out.println(val); } static long calc(long a) { long b=(a*(a+1))%1000000007; return b; } /* method to return prime divisor for n */ long PollardRho(long n) { /* initialize random seed */ //srand (time(NULL)); /* no prime divisor for 1 */ if (n==1) return n; /* even number means one of the divisors is 2 */ if (n % 2 == 0) return 2; Random r=new Random(); /* we will pick from the range [2, N) */ long x = (r.nextLong()%(n-2))+2; long y = x; /* the constant in f(x). * Algorithm can be re-run with a different c * if it throws failure for a composite. */ long c = (r.nextLong()%(n-1))+1; /* Initialize candidate divisor (or result) */ long d = 1; /* until the prime factor isn't obtained. If n is prime, return n */ while (d==1) { /* Tortoise Move: x(i+1) = f(x(i)) */ x = (pow(x, 2, n) + c + n)%n; /* Hare Move: y(i+1) = f(f(y(i))) */ y = (pow(y, 2, n) + c + n)%n; y = (pow(y, 2, n) + c + n)%n; /* check gcd of |x-y| and n */ d = gcd(Math.abs(x-y), n); /* retry if the algorithm fails to find prime factor * with chosen x and c */ if (d==n) return PollardRho(n); } return d; } static HashMap<Long,HashSet<Long>> globalSet; static long fnc(int a,int b) { long val=Math.min(a,b)*1000000007; val+=Math.max(a,b); return val; } static long fnc2(long a,long b) { long val=a*1000000007; val+=b; return val; } static class Pair { int a,b; public Pair(int a,int b) { this.a=a; this.b=b; } } static int bit[]; static void add(int x,int d,int n) { for(int i=x;i<=n;i+=i&-i)bit[i]+=d; } static int query(int x) { int ret=0; for(int i=x;i>0;i-=i&-i) ret+=bit[i]; return ret; } static long lcm(int a,int b) { long val=a; val*=b; return (val/gcd(a,b)); } static long gcd(long a,long b) { if(a==0)return b; return gcd(b%a,a); } static long pow(long a, long b, long p) { long ans = 1, base = a; while (b!=0) { if ((b & 1)!=0) { ans *= base; ans%= p; } base *= base; base%= p; b >>= 1; } return ans; } static long inv(long x,long p) { return pow(x, (int)p - 2, p); } void run() throws Exception { if(codechef)oj=true; is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception {new ModifyLongest().run();} private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { File inputFile = new File("entradaC"); if (inputFile.exists()) System.setIn(new FileInputStream(inputFile)); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); String line = ""; while ((line = in.readLine()) != null) { int n = Integer.parseInt(line); char[] p = in.readLine().toCharArray(); HashMap<Character, Integer> dif = new HashMap<>(); for (int i = 0; i < p.length; i++) dif.put(p[i], 0); int ndif = dif.size(); int head = 0, tail = 0, cnt = 0, ans = Integer.MAX_VALUE, cur; while (head < n) { cur = dif.get(p[head]); if (cur == 0) cnt++; dif.put(p[head], cur + 1); head++; if (cnt == ndif) ans = Math.min(ans, head - tail); while (tail < head && cnt == ndif) { cur = dif.get(p[tail]); if (cur == 1) cnt--; dif.put(p[tail], cur - 1); tail++; if (cnt == ndif) ans = Math.min(ans, head - tail); } } if (ndif == 1) ans = 1; out.append(ans + "\n"); } System.out.print(out); } static int[] readInts(String line) { StringTokenizer st = new StringTokenizer(line.trim()); int a[] = new int[st.countTokens()], index = 0; while (st.hasMoreTokens()) a[index++] = Integer.parseInt(st.nextToken()); return a; } static long[] readLongs(String line) { StringTokenizer st = new StringTokenizer(line.trim()); long a[] = new long[st.countTokens()]; int index = 0; while (st.hasMoreTokens()) a[index++] = Long.parseLong(st.nextToken()); return a; } static double[] readDoubles(String line) { StringTokenizer st = new StringTokenizer(line.trim()); double a[] = new double[st.countTokens()]; int index = 0; while (st.hasMoreTokens()) a[index++] = Double.parseDouble(st.nextToken()); return a; } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.Scanner; public class LuckyDivison { public static void main(String[] args) { Scanner in = new Scanner(System.in); int inp = in.nextInt(); if(inp%4==0||inp%7==0||inp%47==0||inp%74==0||inp%447==0||inp%474==0||inp%477==0||inp%747==0||inp%774==0||inp%777==0) { System.out.println("YES"); } else System.out.println("NO"); } }
constant
122_A. Lucky Division
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Map; import java.math.BigInteger; import java.io.BufferedReader; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author darkhan imangaliyev */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyReader in = new MyReader(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, MyReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); } Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; ++i) { if (map.containsKey(a[i])) { map.put(a[i], map.get(a[i]) + 1); } else { map.put(a[i], 1); } } List<Integer> compressed = new ArrayList<>(); compressed.add(-1); compressed.add(Integer.MAX_VALUE); compressed.addAll(map.keySet()); Collections.sort(compressed); // System.out.println(compressed); int N = compressed.size() + 10; BIT count = new BIT(N); BIT sum = new BIT(N); BigInteger ret = BigInteger.ZERO; for (int i = n - 1; i >= 0; --i) { int l = findLeft(compressed, a[i] - 2); int r = findRight(compressed, a[i] + 2); long left = sum.sum(0, l); long countLeft = count.sum(0, l); long right = sum.sum(r, N); long countRight = count.sum(r, N); // System.out.println("b[i] = " + b[i]); // System.out.println("l = " + l + ", r = " + r); // System.out.println("left = " + left + ", right = " + right); // System.out.println("countLeft = " + countLeft + ", countRight = " + countRight); // System.out.println(); long t = (left - countLeft * a[i]) + (right - a[i] * countRight); ret = ret.add(BigInteger.valueOf(t)); int x = Collections.binarySearch(compressed, a[i]); sum.update(x, a[i]); count.update(x, 1); } out.println(ret); } private int findLeft(List<Integer> a, int t) { int lo = -1, hi = a.size(); while (hi - lo > 1) { int m = lo + (hi - lo) / 2; if (a.get(m) <= t) { lo = m; } else { hi = m; } } return lo; } private int findRight(List<Integer> a, int t) { int lo = -1, hi = a.size(); while (hi - lo > 1) { int m = lo + (hi - lo) / 2; if (a.get(m) < t) { lo = m; } else { hi = m; } } return hi; } class BIT { long[] tree; public BIT(int n) { tree = new long[n + 1]; } public void update(int x, long d) { while (x < tree.length) { tree[x] += d; x += x & -x; } } public long sum(int l, int r) { return sum(r) - sum(l - 1); } public long sum(int x) { long sum = 0; while (x > 0) { sum += tree[x]; x -= x & -x; } return sum; } } } static class MyReader { public BufferedReader reader; public StringTokenizer tokenizer; public MyReader(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()); } } }
nlogn
903_D. Almost Difference
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; // InputStream inputStream = new FileInputStream("dijkstra.in"); OutputStream outputStream = System.out; // OutputStream outputStream = new FileOutputStream("dijkstra.out"); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Answer solver = new Answer(); solver.solve(in, out); out.close(); } } class Answer { private int sumd(long x) { int sum = 0; while (x != 0) { sum += x % 10; x /= 10; } return sum; } private long bin(long l, long r, long s) { if (l > r) { return -1; } long x = (l + r) >> 1; int sum = sumd(x); if (x - sum < s) { return bin(x + 1, r, s); } long t = bin(l, x - 1, s); if (t != -1) { return t; } return x; } public void solve(InputReader in, PrintWriter out) throws IOException { long n = in.nextLong(); long s = in.nextLong(); long t = bin(1, n, s); if (t == -1) { out.print("0"); } else { long ans = n - t + 1; out.print(ans); } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
logn
817_C. Really Big Numbers
CODEFORCES
// @author Sanzhar import java.io.*; import java.util.*; import java.awt.Point; public class Template { BufferedReader in; PrintWriter out; StringTokenizer st; String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } public void run() throws Exception { //in = new BufferedReader(new FileReader("input.txt")); //out = new PrintWriter(new FileWriter("output.txt")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); in.close(); } public void solve() throws Exception { int n = nextInt(); int k = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } boolean[] ok = new boolean[n]; Arrays.fill(ok, true); Arrays.sort(a); if (k != 1) { for (int i = 0; i < n; i++) { if (a[i] % k == 0) { int x = a[i] / k; int ind = Arrays.binarySearch(a, x); if (ind >= 0 && ok[ind]) { ok[i] = false; } } } } int ans = 0; for (int i = 0; i < n; i++) { if (ok[i]) { ans++; } } out.println(ans); } public static void main(String[] args) throws Exception { new Template().run(); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class A { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = null; private void solve() throws IOException { int n = nextInt(); int k = nextInt(); int p[] = new int[n]; int t[] = new int[n]; for(int i = 0; i < n; i++) { p[i] = nextInt(); t[i] = nextInt(); } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { if(p[i] < p[j] || (p[i] == p[j] && t[i] > t[j])) { int tmp = p[i]; p[i] = p[j]; p[j] = tmp; tmp = t[i]; t[i] = t[j]; t[j] = tmp; } } } int pN = p[k - 1]; int tN = t[k - 1]; int counter = 0; for(int i = 0; i < n; i++) { if(p[i] == pN && t[i] == tN) { counter++; } } System.out.println(counter); } String nextToken() throws IOException { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(bf.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public static void main(String args[]) throws IOException { new A().solve(); } }
nlogn
166_A. Rank List
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class CE35D { public static void main(String[] args) throws NumberFormatException, IOException { //Scanner sc = new Scanner(System.in); BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(sc.readLine()); String[] t = sc.readLine().split(" "); int[] list = new int[n]; for(int x=0; x<n; x++){ list[x] = Integer.parseInt(t[x]); } boolean even = true; int[] indList = new int[n+1]; for(int x=0; x<n; x++){ indList[list[x]] = x; } for(int x=1; x<=n; x++){ int theIndex = indList[x]; int other = list[x-1]; if(theIndex != x-1){ even = !even; list[x-1] = x; list[theIndex] = other; indList[x] = x-1; indList[other] = theIndex; } } //System.out.println(even); int numQ = Integer.parseInt(sc.readLine()); for(int x=0; x<numQ; x++){ String[] dir = sc.readLine().split(" "); int l = Integer.parseInt(dir[0]); int r = Integer.parseInt(dir[1]); int diff = r - l + 1; if(diff%4 > 1){ even = !even; } if(even){ System.out.println("even"); } else{ System.out.println("odd"); } } } } /* int n = Integer.parseInt(sc.nextLine()); String[] t = sc.nextLine().split(" "); int[] list = new int[n]; for(int x=0; x<n; x++){ list[x] = Integer.parseInt(t[x]); } String[] dir = sc.nextLine().split(" "); int a = Integer.parseInt(dir[0]); int b = Integer.parseInt(dir[1]); int c = Integer.parseInt(dir[2]); int d = Integer.parseInt(dir[3]); int e = Integer.parseInt(dir[4]); int n = Integer.parseInt(sc.nextLine()); */
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.*; import java.util.StringTokenizer; /** * Created by Darren on 14-10-21. */ public class D { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { new D().run(); } int n, m; boolean[][] adjacency; void run() throws IOException { n = in.nextInt(); m = in.nextInt(); adjacency = new boolean[n+1][n]; for (int i = 0; i < m; i++) { int u = in.nextInt(), v = in.nextInt(); adjacency[u-1][v-1] = adjacency[v-1][u-1] = true; } final int MAX_MASK = (1 << n) - 1; long[][] dp = new long[MAX_MASK+1][n]; for (int i = 0; i < n; i++) dp[1<<i][i] = 1; long sum = 0; for (int mask = 1; mask <= MAX_MASK; mask++) { int lowestBit = first(mask); for (int i = 0; i < n; i++) { if (bit(i, mask) && i != lowestBit) { for (int j = 0; j < n; j++) { if (adjacency[j][i]) { dp[mask][i] += dp[mask^(1<<i)][j]; } } if (count(mask) >= 3 && adjacency[lowestBit][i]) sum += dp[mask][i]; } else { // dp[mask][i] = 0 } } } out.println(sum / 2); out.flush(); } int count(int mask) { int count = 0; while (mask > 0) { if ((mask & 1) == 1) count++; mask >>= 1; } return count; } int first(int mask) { int index = 0; while (mask > 0) { if ((mask & 1) == 1) return index; mask >>= 1; index++; } return -1; } boolean bit(int index, int mask) { return ((1 << index) & mask) > 0; } static class Reader { BufferedReader reader; StringTokenizer tokenizer; public Reader(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** get next word */ String nextToken() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } String readLine() throws IOException { return reader.readLine(); } int nextInt() throws IOException { return Integer.parseInt( nextToken() ); } long nextLong() throws IOException { return Long.parseLong( nextToken() ); } double nextDouble() throws IOException { return Double.parseDouble( nextToken() ); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class CF { BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=null; private void solution() throws IOException{ int n=nextInt(); if((n % 4==0 && n>=4)||(n % 7==0 && n>=7) || (n % 44==0 && n>=44) || (n % 47==0 && n>=47) || (n % 77==0 && n>=77) || (n % 74==0 && n>=74) || (n % 444==0 && n>=444) || (n % 447==0 && n>=447) || (n % 474==0 && n>=74) || (n % 477==0 && n>=477) || (n % 744==0 && n>=744) || (n % 747==0 && n>=747) || (n % 777==0 && n>=777)){ System.out.println("YES"); }else{ System.out.println("NO");} } String nextToken()throws IOException { if(st==null || !st.hasMoreTokens()){ st = new StringTokenizer(bf.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public static void main(String args[]) throws IOException { new CF().solution(); } }
constant
122_A. Lucky Division
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; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BSportMafia solver = new BSportMafia(); solver.solve(1, in, out); out.close(); } static class BSportMafia { public long findsqrt(long a) { long b = (long) Math.sqrt(a); for (long tt = Math.max(0, b - 10); tt <= b + 10; tt++) if (tt * tt == a) return tt; return -1; } public void solve(int testNumber, ScanReader in, PrintWriter out) { long n = in.scanInt(); long k = in.scanInt(); out.println(n - (-3 + findsqrt(9 + 8 * (k + n))) / 2); } } 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; } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class PlayingPiano { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); List<Integer> as = new LinkedList<>(); int[] as2 = new int[n]; for (int i = 0; i < n; i++) { int a = scanner.nextInt(); as.add(a); as2[i] = a; } //System.out.println(solve(as)); System.out.println(solve2(as2)); scanner.close(); } public static String solve(List<Integer> as) { List<Integer> fingers = new LinkedList<>(); fingers.add(1); fingers.add(2); fingers.add(3); fingers.add(4); fingers.add(5); List<Integer> solution = assign(as, fingers, fingers); if (solution == null) { return "-1"; } else { StringBuilder sb = new StringBuilder(); for (int b : solution) { sb.append(b); sb.append(" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } } private static List<Integer> assign(List<Integer> as, List<Integer> fingers, List<Integer> allFingers) { // if fingers is empty return null if (fingers.isEmpty()) { return null; } // if as size is one then return first element in fingers if (as.size() == 1) { List<Integer> ret = new LinkedList<>(); ret.add(fingers.get(0)); return ret; } // get sublist List<Integer> subList = as.subList(1, as.size()); for (int i = 0; i < fingers.size(); i++) { // recursively call with sublist and limited list of fingers List<Integer> subFingers = new LinkedList<>(); final int j = i; if (as.get(0) < as.get(1)) { subFingers = allFingers.stream() .filter(p -> p > fingers.get(j)).collect(Collectors.toList()); } else if (as.get(0) > as.get(1)) { subFingers = allFingers.stream() .filter(p -> p < fingers.get(j)).collect(Collectors.toList()); } else { subFingers = allFingers.stream() .filter(p -> p != fingers.get(j)).collect(Collectors.toList()); } List<Integer> ret = assign(subList, subFingers, allFingers); if (ret != null) { List<Integer> solution = new LinkedList<>(); solution.add(fingers.get(i)); solution.addAll(ret); return solution; } // if return is null, then return null, else return an array } return null; } public static String solve2(int[] as) { int[] ret = new int[as.length]; if (as.length == 1) return "1"; if (as[0] < as[1]) ret[0] = 1; else if (as[0] == as[1]) ret[0] = 3; else ret[0] = 5; for (int i = 1; i < as.length - 1; i++) { if (as[i-1] < as[i] && ret[i-1] == 5) return "-1"; if (as[i-1] > as[i] && ret[i-1] == 1) return "-1"; if (as[i-1] < as[i] && as[i] < as[i+1]) { ret[i] = ret[i-1] + 1; } else if (as[i-1] == as[i] && as[i] < as[i+1]) { ret[i] = ret[i-1] == 1 ? 2 : 1; } else if (as[i-1] > as[i] && as[i] < as[i+1]) { ret[i] = 1; } else if (as[i-1] < as[i] && as[i] == as[i+1]) { ret[i] = ret[i-1] + 1; } else if (as[i-1] == as[i] && as[i] == as[i+1]) { ret[i] = ret[i-1] == 4 ? 2 : 4; } else if (as[i-1] > as[i] && as[i] == as[i+1]) { ret[i] = ret[i-1] == 2 ? 1 : 2; } else if (as[i-1] < as[i] && as[i] > as[i+1]) { ret[i] = 5; } else if (as[i-1] == as[i] && as[i] > as[i+1]) { ret[i] = ret[i-1] == 5 ? 4 : 5; } else if (as[i-1] > as[i] && as[i] > as[i+1]) { ret[i] = ret[i-1] - 1; } } if (as.length > 1) { if (as[as.length - 1] > as[as.length - 2]) { if (ret[as.length - 2] == 5) return "-1"; ret[as.length - 1] = 5; } else if (as[as.length - 1] == as[as.length - 2]) { ret[as.length - 1] = ret[as.length - 2] == 5 ? 4 : 5; } else { if (ret[as.length - 2] == 1) return "-1"; ret[as.length - 1] = 1; } } StringBuilder sb = new StringBuilder(); for (int b : ret) { sb.append(b); sb.append(" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } }
linear
1032_C. Playing Piano
CODEFORCES
import java.util.*; import java.io.*; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextInt(), k = sc.nextInt(); long start = 1, end = n; while(start <= end) { long mid = (start + end) >> 1; if(calc(mid) - (n - mid) == k) { System.out.println(n - mid); return; } else if (calc(mid) - (n - mid) > k) { end = mid - 1; } else { start = mid + 1; } } } public static long calc(long n) { return (n * n + n) / 2; } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.Locale; import java.util.Scanner; public class A { public static void main(String[] args) { Locale.setDefault(Locale.US); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] number = new String[n]; sc.nextLine(); String l = sc.nextLine(); number = l.split(" "); int oe = 1; if((Integer.valueOf(number[0])%2 + Integer.valueOf(number[1])%2 + Integer.valueOf(number[2])%2) > 1) { oe = 0; } for(int i=0;i<n;i++) { if((Integer.valueOf(number[i])%2)==oe) { System.out.println(i+1); break; } } } }
linear
25_A. IQ test
CODEFORCES
import java.io.*; import java.util.*; public class A{ public static BufferedReader k; public static BufferedWriter z; public static void main(String [] args)throws IOException{ k = new BufferedReader(new InputStreamReader(System.in)); z = new BufferedWriter(new OutputStreamWriter(System.out)); String[] dat = k.readLine().split(" "); long l = Long.parseLong(dat[0]); long r = Long.parseLong(dat[1]); if(r-l<=1){ z.write(-1+"\n"); } else if(r-l == 2){ if((l&1)!=0){ z.write(-1+"\n"); } else{ z.write(l+" "+(l+1)+" "+r+"\n"); } } else{ if((l&1)==0){ z.write(l+" "+(l+1)+" "+(l+2)+"\n"); } else{ z.write((l+1)+" "+(l+2)+" "+(l+3)+"\n"); } } z.flush(); } }
constant
483_A. Counterexample
CODEFORCES
import java.util.Arrays; import java.util.Scanner; /** * * @author oleksiys */ public class A { public static void main(String [] args){ try(Scanner s = new Scanner(System.in)){ final int n = s.nextInt(); final int m = s.nextInt(); final int k = s.nextInt(); final int [] a = new int [n]; for (int i = 0; i < a.length; ++i){ a[i] = s.nextInt(); } Arrays.sort(a); int i = a.length - 1; int available = k; int filters = 0; while (available < m && i >= 0){ available -= 1; available += a[i]; filters++; i--; } if (available < m){ System.out.println(-1); }else{ System.out.println(filters); } } } }
nlogn
257_A. Sockets
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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.readIntArray(n); long count = 0; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (a[j] > a[i]) count++; } } boolean even = count % 2 == 0 ? true : false; int m = in.nextInt(); for (int i = 0; i < m; i++) { int left = in.nextInt(); int right = in.nextInt(); int diff = right - left; if ((diff % 4 == 1) || (diff % 4 == 2)) { even = !even; } if (even) { out.println("even"); } else { out.println("odd"); } } } } static class InputReader { private static BufferedReader in; private static StringTokenizer tok; public InputReader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public int[] readIntArray(int n) { int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = nextInt(); } return ar; } 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(); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; import java.io.*; public class MinimumDiameterTree{ public static void main(String[] args) { InputReader in = new InputReader (System.in); PrintWriter out = new PrintWriter (System.out); int n = in.nextInt(); int s = in.nextInt(); int deg[] = new int [n]; for (int i = 1; i < n; ++i) { deg[in.nextInt() - 1] ++; deg[in.nextInt() - 1] ++; } int l = 0; for (int i = 0; i < n; ++i) if (deg[i] == 1) l ++; out.println((double) 2 * s / l); out.close(); } public 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
1086_B. Minimum Diameter Tree
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; public class A { static int[] parent; public static int find(int x) { if (x == parent[x]) return x; return parent[x] = find(parent[x]); } public static void union(int x, int y) { int px = find(x); int py = find(y); if (px != py) { parent[py] = px; } } public static void main(String[] args) throws Exception { int numCnt = (int) nextLong(); long k = nextLong(); parent = new int[numCnt]; for (int i = 0; i < parent.length; i++) { parent[i] = i; } HashMap<Long, Integer> map = new HashMap<Long, Integer>(); long[] ar = new long[numCnt]; for (int i = 0; i < numCnt; i++) { ar[i] = nextLong(); map.put(ar[i] * 10007 + ar[i] / 13, i); } for (int i = 0; i < ar.length; i++) { long req = ar[i] * k; Integer idx=map.get(req * 10007 + req / 13); if (idx!=null) { union(i, idx); } } int[] count = new int[numCnt]; for (int i = 0; i < parent.length; i++) { count[find(i)]++; } int res = 0; for (int i = 0; i < numCnt; i++) { res += (int) ((count[i] + 1) / 2.0); } System.out.println(res); } static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer tokenizer = new StringTokenizer(""); static long nextLong() throws Exception { return Long.parseLong(next()); } static double nextDouble() throws Exception { return Double.parseDouble(next()); } static String next() throws Exception { while (true) { if (tokenizer.hasMoreTokens()) { return tokenizer.nextToken(); } String s = br.readLine(); if (s == null) { return null; } tokenizer = new StringTokenizer(s); } } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES