src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.util.Scanner; public class Problem_8C { private static int dis(int x1, int y1, int x2, int y2) { return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int ox = sc.nextInt(); int oy = sc.nextInt(); int n = sc.nextInt(); int[] ix = new int[n]; int[] iy = new int[n]; int[] single = new int[n]; int[][] pair = new int[n][n]; for (int i = 0; i < n; i++) { ix[i] = sc.nextInt(); iy[i] = sc.nextInt(); single[i] = dis(ox, oy, ix[i], iy[i]) * 2; for (int j = 0; j < i; j++) { pair[i][j] = pair[j][i] = dis(ix[i], iy[i], ix[j], iy[j]) + (single[i] + single[j]) / 2; } } int[] min = new int[1 << n]; int[] pre = new int[1 << n]; for (int set = 1; set < 1 << n; set++) { int i; for (i = 0; i < n; i++) { if ((set & (1 << i)) != 0) { break; } } min[set] = min[set ^ (1 << i)] + single[i]; pre[set] = set ^ (1 << i); for (int j = 0; j < n; j++) { if ((set & (1 << j)) == 0) { continue; } if (min[set] > min[set ^ (1 << i) ^ (1 << j)] + pair[i][j]) { min[set] = min[set ^ (1 << i) ^ (1 << j)] + pair[i][j]; pre[set] = set ^ (1 << i) ^ (1 << j); } } } System.out.println(min[(1 << n) - 1]); for (int set = (1 << n) - 1; set != 0; set = pre[set]) { System.out.print("0 "); for (int i = 0; i < n; i++) { if (((set ^ pre[set]) & (1 << i)) != 0) { System.out.print((i + 1) + " "); } } } System.out.println("0"); sc.close(); } }
np
8_C. Looking for Order
CODEFORCES
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static MyScanner scan; static PrintWriter pw; static long MOD = 1_000_000_007; static long INF = 1_000_000_000_000_000_000L; static long inf = 2_000_000_000; public static void main(String[] args) { new Thread(null, null, "BaZ", 1 << 27) { public void run() { try { solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static int n,m,need,a[][],dp[][][],real[][]; static void solve() throws IOException { //initIo(true); initIo(false); StringBuilder sb = new StringBuilder(); int t = ni(); while(t-->0) { n = ni(); m = ni(); a = new int[n][m]; for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { a[i][j] = ni(); } } need = min(n,m); Pair max_in_cols[] = new Pair[m]; for(int COL=0;COL<m;++COL) { int max = 0; for(int i=0;i<n;++i) { max = max(max, a[i][COL]); } max_in_cols[COL] = new Pair(max, COL); } real = new int[n][need]; Arrays.sort(max_in_cols); for(int i=0;i<need;++i) { int COL = max_in_cols[m-1-i].y; for(int j=0;j<n;++j) { real[j][i] = a[j][COL]; } } // pl("need : "+need); // pa("Real", real); dp = new int[need][n+1][(1<<n)]; for(int i=0;i<need;++i) { for(int j=0;j<=n;++j) { for(int k=0;k<(1<<n);++k) { dp[i][j][k] = -1; } } } pl(f(0, n, 0)); } pw.flush(); pw.close(); } static int f(int idx, int bias, int mask) { //pl("idx: "+idx+" bias : "+bias + " mask : "+mask); if(idx==need) { return 0; } if(dp[idx][bias][mask]!=-1) { return dp[idx][bias][mask]; } //didn't fix bias yet if(bias==n) { int max = 0; for(int b=0;b<n;++b) { max = max(max, f(idx, b, mask)); } //pl("maxxxxxxx : "+max); dp[idx][bias][mask] = max; return max; } else { int max = f(idx+1, n, mask); for(int i=0;i<n;++i) { if((mask&(1<<i))==0) { max = max(max, real[(i-bias+n)%n][idx] + f(idx, bias, mask | (1<<i))); } } //pl("max : "+max); dp[idx][bias][mask] = max; return max; } } static class Pair implements Comparable<Pair> { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(Pair other) { if(this.x!=other.x) return this.x-other.x; return this.y-other.y; } public String toString() { return "("+x+","+y+")"; } } static void initIo(boolean isFileIO) throws IOException { scan = new MyScanner(isFileIO); if(isFileIO) { pw = new PrintWriter("/Users/amandeep/Desktop/output.txt"); } else { pw = new PrintWriter(System.out, true); } } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static String ne() throws IOException { return scan.next(); } static String nel() throws IOException { return scan.nextLine(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(boolean readingFromFile) throws IOException { if(readingFromFile) { br = new BufferedReader(new FileReader("/Users/amandeep/Desktop/input.txt")); } else { br = new BufferedReader(new InputStreamReader(System.in)); } } String nextLine()throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Main { public static void main(final String[] args) throws IOException { try(Scanner scan = new Scanner(System.in); PrintWriter print = new PrintWriter(System.out)) { final int n = scan.nextInt(); final int m = scan.nextInt(); final Pair<Integer, Integer>[] arcs = new Pair[m]; for(int k = 0; k < m; ++k) { int i = scan.nextInt(); int j = scan.nextInt(); --i; --j; arcs[k] = new Pair(i, j); } print.println(calcMinNumStepsToCenterPermGraph(new DirectedGraph(n, arcs))); } } public static int calcMinNumStepsToCenterPermGraph(final DirectedGraph graph) { int result = Integer.MAX_VALUE; for(DirectedGraph.Vertex center : graph.vertices) { int num = 2 * graph.vertices.length - 1 - graph.getOutcomingArcs(center).size() - graph.getIncomingArcs(center).size() + (graph.containsArc(center, center) ? 1 : 0); final int n = graph.vertices.length - 1; final List<Pair<Integer, Integer>> edges = CollectionFactory.createArrayList(); for(DirectedGraph.Arc arc : graph.arcs) { if(!center.equals(arc.from) && !(center.equals(arc.to))) { int i = arc.from.index; int j = arc.to.index; if(i > center.index) { --i; } if(j > center.index) { --j; } edges.add(new Pair(i, j)); } } final int matching = GraphUtils.calcNumMatchingBipartite(n, n, edges); num += edges.size() - matching; num += n - matching; result = Math.min(result, num); } return result; } public static class GraphUtils { public static int calcNumMatchingBipartite(final int n, final int m, final List<Pair<Integer, Integer>> edges) { final MatchingBipartiteSolver solver = new MatchingBipartiteSolver(n, m, edges); return solver.solve(); } private static class MatchingBipartiteSolver { private final int n; private final int m; private final List<Integer>[] edges; private final Integer[] match; private final boolean[] visited; public MatchingBipartiteSolver (final int n, final int m, final List<Pair<Integer, Integer>> edges) { this.n = n; this.m = m; this.edges = new List[n]; for(int i = 0; i < n; ++i) { this.edges[i] = CollectionFactory.createArrayList(); } for(final Pair<Integer, Integer> edge: edges) { this.edges[edge.first].add(edge.second); } match = new Integer[n + m]; visited = new boolean[n + m]; } public int solve() { int result = 0; for(;;) { Arrays.fill(visited, false); int gain = 0; for(int i = 0; i < n; ++i) { if(match[i] == null && !visited[i] && tryMatch(i)) { ++gain; } } if(gain > 0) { result += gain; } else { break; } } return result; } private boolean tryMatch(final int i) { visited[i] = true; for(int j : edges[i]) { if(!visited[j + n]) { visited[j + n] = true; final Integer k = match[j + n]; if(k == null || (!visited[k] && tryMatch(k))) { match[j + n] = i; match[i] = j + n; return true; } } } return false; } } } public static class DirectedGraph { public static class Vertex { public final int index; public Vertex(int index) { this.index = index; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Vertex vertex = (Vertex) o; if (index != vertex.index) return false; return true; } @Override public int hashCode() { return index; } } public static class Arc { public final Vertex from; public final Vertex to; public Arc(Vertex from, Vertex to) { this.from = from; this.to = to; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Arc arc = (Arc) o; if (!from.equals(arc.from)) return false; if (!to.equals(arc.to)) return false; return true; } @Override public int hashCode() { int result = from.hashCode(); result = 31 * result + to.hashCode(); return result; } } final public Vertex[] vertices; final public Arc[] arcs; public DirectedGraph(final int n, final Pair<Integer, Integer>[] arcs) { vertices = new Vertex[n]; this.arcs = new Arc[arcs.length]; for(int i = 0; i < n; ++i) { vertices[i] = new Vertex(i); } for(int i = 0; i < arcs.length; ++i) { this.arcs[i] = new Arc(vertices[arcs[i].first], vertices[arcs[i].second]); } } public List<Arc> getOutcomingArcs(final Vertex v) { final List<Arc> result = CollectionFactory.createArrayList(); for(Arc arc : arcs) { if(arc.from.equals(v)) { result.add(arc); } } return result; } public List<Arc> getIncomingArcs(final Vertex v) { final List<Arc> result = CollectionFactory.createArrayList(); for(Arc arc : arcs) { if(arc.to.equals(v)) { result.add(arc); } } return result; } public boolean containsArc(final Vertex from, final Vertex to) { for(Arc arc : arcs) { if(arc.from.equals(from) && arc.to.equals(to)) { return true; } } return false; } } public static class MatrixIntMod { final int mod; final int[][] data; public MatrixIntMod(final int n, final int m, final int mod) { this.mod = mod; this.data = new int[n][m]; for(int i = 0; i < n; ++i) { Arrays.fill(data[i], 0); } } public MatrixIntMod(final int[][] data, final int mod) { this(data.length, data[0].length, mod); for(int i = 0; i < data.length; ++i) { for(int j = 0; j < data[i].length; ++j) { this.data[i][j] = ModNumberUtils.norm(mod, data[i][j]); } } } public MatrixIntMod(final int[] data, final int mod) { this(data.length, 1, mod); for(int i = 0; i < data.length; ++i) { this.data[i][0] = ModNumberUtils.norm(mod, data[i]); } } public int[] all() { int n = data.length; int m = data[0].length; final int[] res = new int[n * m]; int k = 0; for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { res[k++] = data[i][j]; } } return res; } public MatrixIntMod mult(final MatrixIntMod val) { if(data[0].length != val.data.length) throw new RuntimeException("dimensions for mult are wrong"); final int n = data.length; final int m = data[0].length; final int l = val.data[0].length; final MatrixIntMod res = new MatrixIntMod(n, l, mod); for(int i = 0; i < n; ++i) { for(int j = 0; j < l; ++j) { for(int k = 0; k < m; ++k) { res.data[i][j] = ModNumberUtils.add(mod, res.data[i][j], ModNumberUtils.mult(mod, data[i][k], val.data[k][j])); } } } return res; } public int[] mult(final int[] ar) { return mult(new MatrixIntMod(ar, mod)).all(); } public MatrixIntMod power(final long t) { if(t == 0) return eye(data.length, mod); MatrixIntMod res = power(t >> 1); res = res.mult(res); if((t & 1) == 1) { res = res.mult(this); } return res; } public static MatrixIntMod eye(final int n, final int mod) { final MatrixIntMod res = new MatrixIntMod(n, n, mod); if(mod > 1) { for(int i = 0; i < n; ++i) { res.data[i][i] = 1; } } return res; } } public static class ModNumberUtils { public static int add(int mod, int a, int b) { a += b; if(a >= mod) { a -= mod; } return a; } public static int norm(int mod, int a) { a %= mod; if(a < 0) { a += mod; } return a; } public static int mult(int mod, int a, int b) { return (int)((long)a * b % mod); } } public static class Pair<X, Y>{ public X first; public Y second; public Pair(final X first, final Y second) { this.first = first; this.second = second; } } public static class NumberUtils { public static interface Factorizer { List<Integer> factorize(int number); } /** * thread safe Factorizer */ public static Factorizer createSmallNumberFactorizer(final int upperBound) { return new SmallNumberFactorizer(upperBound); } /** * thread safe */ private static class SmallNumberFactorizer implements Factorizer { private int[] divisors; private final int upperBound; private boolean prepared = false; /** * lazy * time complexity O(n * log(n) * log(log(n)) * memory complexity O(n) */ public SmallNumberFactorizer(final int upperBound) { this.upperBound = upperBound; } private synchronized void prepare() { divisors = new int[upperBound]; Arrays.fill(divisors, 0); for(int i = 2; i * i < upperBound; ++i) { if(divisors[i] == 0) { for(int j = i * i; j < upperBound; j += i) { if(divisors[j] == 0) { divisors[j] = i; } } } } prepared = true; } /** * complexity O(result) */ public List<Integer> factorize(int number) { synchronized (this) { if(!prepared) { prepare(); } } final List<Integer> result = CollectionFactory.createArrayList(); if(number < 2) return result; if(number >= upperBound) throw new RuntimeException("number should be less than upper bound"); while(divisors[number] > 0) { result.add(divisors[number]); number /= divisors[number]; } result.add(number); return result; } } } public static class CollectionFactory { public static<T> List<T> createArrayList() { return new ArrayList<>(); } public static<T> List<T> createArrayList(final int capacity) { return new ArrayList<>(capacity); } } public static class CollectionUtils { public static<T> List<T> unique(final List<T> list) { final List<T> result = CollectionFactory.createArrayList(); T p = null; for(T elem : list) { if(!elem.equals(p)) { result.add(elem); p = elem; } } return result; } public static<T extends Comparable<T>> T max(final List<T> list, final T lowerBound) { T result = lowerBound; for(T elem : list) { if(elem.compareTo(result) > 0) { result = elem; } } return result; } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.*; import java.util.*; public class B { final String filename = new String("B").toLowerCase(); int n; int r, c; void solve() throws Exception { n = nextInt(); r = nextInt() - 1; c = nextInt() - 1; long count = nextLong(); long left = -1, right = n * 2L; while (left < right - 1) { long mid = (left + right) / 2; if (getSq(n, r, c, mid) >= count) { right = mid; } else { left = mid; } } // for (int i = 0; i <= 10; i++) { // System.err.println(getSq(n, r, c, i)); // } out.println(right); } long getSq(int n, int x, int y, long size) { long cur = (size + 1) * (size + 1) + size * size; cur -= get(x + size - (n - 1)); cur -= get(y + size - (n - 1)); cur -= get(-(x - size)); cur -= get(-(y - size)); cur += getCorner((x + 1) + (y + 1) - (size + 1)); cur += getCorner((x + 1) + (n - y) - (size + 1)); cur += getCorner((n - x) + (y + 1) - (size + 1)); cur += getCorner((n - x) + (n - y) - (size + 1)); return cur; } private long getCorner(long min) { if (min >= 0) { return 0; } min = -min; return min * (min + 1) / 2; } long get(long a) { if (a <= 0) { return 0; } return a * a; } void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // in = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } BufferedReader in; StringTokenizer st; PrintWriter out; String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(nextToken()); } long nextLong() throws Exception { return Long.parseLong(nextToken()); } double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } public static void main(String[] args) { new B().run(); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.util.Scanner; public class codef8 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int beacon[] = new int[1000001]; int pos[] = new int[num]; for (int i = 0; i < num; i++) { int position = sc.nextInt(); beacon[position] = sc.nextInt(); pos[i] = position; } int dp[] = new int[1000001]; int max = 1; if (beacon[0] != 0) dp[0] = 1; for (int i = 1; i <= 1000000; i++) { if (beacon[i] == 0) { dp[i] = dp[i-1]; } else { int j = i - beacon[i] - 1; if (j < 0) { dp[i] = 1; } else { dp[i] = dp[j] + 1; } } max = Math.max(max, dp[i]); } System.out.println(num-max); } }
linear
608_C. Chain Reaction
CODEFORCES
// package contest; import java.io.*; import java.util.Stack; import java.util.StringTokenizer; public class teama { static int mod = 2_000_000_007; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int T = Integer.parseInt(br.readLine()); for (int t = 0; t < T; t++) { int N = Integer.parseInt(br.readLine()); Stack<Integer> stack = new Stack(); for (int i = 0; i < N; i++) { int a = Integer.parseInt(br.readLine()); if (a != 1) { while (stack.peek() + 1 != a) { stack.pop(); } stack.pop(); } stack.push(a); boolean dummy = false; for (int j : stack) { if (dummy) { pw.print("."); } pw.print(j); dummy = true; } pw.println(); } } pw.close(); br.close(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; import java.util.Map.*; public class codeforces { static int count =0; static boolean f=false; static int [] arr; static PrintWriter pw=new PrintWriter(System.out); static void solve(int index , int mask) { if(index==arr.length) { int sum1=0; int sum2=0; for(int i=0;i<arr.length;i++) { if((mask & 1<<i)!=0) sum1+=arr[i]; } return; } solve(index+1, mask | 1<<index); solve(index+1, mask); } public static void main(String [] args) throws IOException, InterruptedException { Scanner sc=new Scanner(System.in); int x=sc.nextInt(); int y=sc.nextInt(); pair [] arr=new pair[x]; for(int i=0;i<x;i++) arr[i]=new pair(i, sc.nextInt(),0); for(int i=0;i<x;i++) arr[i].y=sc.nextInt(); Arrays.sort(arr); PriorityQueue<Integer> qq=new PriorityQueue<>(); //pw.println(Arrays.toString(arr)); Long [] list=new Long [x]; long sum=0; for(int i=0;i<x;i++) { pair w=arr[i]; if(qq.size()<y) { qq.add(w.y); sum+=w.y; list[w.i]=sum; }else if(!qq.isEmpty()) { sum+=w.y; list[w.i]=sum; int first=qq.poll(); if(w.y>first) { sum-=first; qq.add(w.y); }else { qq.add(first); sum-=w.y; } } else list[w.i]=(long) w.y; //pw.println(qq); } for(Long w:list) pw.print(w+" "); pw.flush(); pw.close(); } static class pair implements Comparable<pair>{ String name; int x,y,i ; public pair(String name , int x) { this.name=name; this.x=x; } public pair (int i,int x,int y) { this.i=i; this.x=x; this.y=y; } public int compareTo(pair o) { return x-o.x; } public int compareTo1(pair o) { if(!name.equals(o.name)) return name.compareTo(o.name); return x-o.x; } public String toString() { return i+" "+x+" "+y; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
nlogn
994_B. Knights of a Polygonal Table
CODEFORCES
import java.util.*; import java.io.*; public class b { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); int n = input.nextInt(), a = input.nextInt(), b = input.nextInt(); Num[] data = new Num[n]; for(int i = 0; i<n; i++) data[i] = new Num(input.nextInt(), i); int[] res = new int[n]; Arrays.fill(res,-1); Arrays.sort(data); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i<n; i++) map.put(data[i].x, data[i].i); boolean good = true; for(int i = 0; i<n; i++) { if(res[data[i].i] != -1) continue; int val = data[i].x; if(!map.containsKey(a-val) && !map.containsKey(b-val)) { good = false; break; } if(!map.containsKey(a-val)) { int other = map.get(b-val); if(res[other] == 0) { good = false; break; } res[other] = res[data[i].i] = 1; } else if(!map.containsKey(b-val)) { int other = map.get(a-val); if(res[other] == 1) { good = false; break; } res[other] = res[data[i].i] = 0; } else { int cur = data[i].i; int otherB = map.get(b-val), otherA = map.get(a-val); if(b > a && res[otherB] != 0) { res[cur] = res[otherB] = 1; } else if(a>b && res[otherA] != 1) { res[cur] = res[otherA] = 0; } else if(b > a && res[otherA] != 1) { res[cur] = res[otherA] = 0; } else if(a > b && res[otherB] != 0) { res[cur] = res[otherB] = 1; } else if(b == a) { res[cur] = res[otherA] = 0; } else { good = false; break; } } } if(good) { out.println("YES"); for(int x: res) out.print(x+" "); } else out.println("NO"); out.close(); } static class Num implements Comparable<Num> { int x, i; public Num(int xx, int ii) { x = xx; i = ii; } @Override public int compareTo(Num o) { // TODO Auto-generated method stub return x - o.x; } } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } } }
linear
468_B. Two Sets
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class A { static MyScanner sc; static PrintWriter pw; public static void main(String[] args) throws Throwable { sc = new MyScanner(); pw = new PrintWriter(System.out); n = sc.nextInt(); int m = sc.nextInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = sc.nextInt(); val = new int[n][n]; for (int i = 0; i < n; i++) Arrays.fill(val[i], Integer.MAX_VALUE); for (int i = 0; i < n; i++) for (int j = i; j < n; j++) { for (int k = 0; k < m; k++) val[i][j] = val[j][i] = Math.min(val[i][j], Math.abs(a[i][k] - a[j][k])); } val2 = new int[n][n]; for (int i = 0; i < n; i++) Arrays.fill(val2[i], Integer.MAX_VALUE); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { for (int k = 0; k < m - 1; k++) val2[i][j] = Math.min(val2[i][j], Math.abs(a[i][k] - a[j][k + 1])); } mem = new Integer[n][n][1 << n]; int ans = 0; for (int i = 0; i < n; i++) { ans = Math.max(ans, dp(i, i, 1 << i)); } if (n == 1) pw.println(val2[0][0]); else pw.println(ans); pw.flush(); pw.close(); } static int n; static int[][] val, val2; static Integer[][][] mem; static int dp(int st, int lst, int msk) { int bits = Integer.bitCount(msk); if (mem[st][lst][msk] != null) return mem[st][lst][msk]; int ans = 0; for (int i = 0; i < n; i++) if ((msk & (1 << i)) == 0) { int newMsk = (msk | (1 << i)); if (bits < n - 1) ans = Math.max(ans, Math.min(val[lst][i], dp(st, i, newMsk))); else ans = Math.max(ans, Math.min(val[lst][i], val2[i][st])); } return mem[st][lst][msk] = ans; } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main { public static void main(String args[]) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); System.out.println((n%4==0||n%7==0||n%47==0||n%74==0||n%447==0||n%474==0||n%477==0||n%744==0||n%747==0||n%774==0)?"YES":"NO"); } }
constant
122_A. Lucky Division
CODEFORCES
import java.io.*; import java.util.*; /** * @author def * @version 1.0 */ public class B { public static void main(String[] args) throws IOException { new B().solve(); } void solve() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()); while (n-- > 0) { String s = in.readLine(); int pr = s.indexOf('R'); int pc = s.indexOf('C'); if (pr == 0 && pc > 1 && Character.isDigit(s.charAt(1))) { int r = Integer.parseInt(s.substring(1, pc)); int c = Integer.parseInt(s.substring(pc + 1, s.length())); out.println(i2s(c) + r); } else { int i = 0; while (!Character.isDigit(s.charAt(i))) ++i; out.println("R" + Integer.parseInt(s.substring(i, s.length())) + "C" + s2i(s.substring(0, i))); } } out.close(); } int s2i(String s) { int r = 0; for (int i = 0; i < s.length(); ++i) { r = r * 26 + (s.charAt(i) - 'A' + 1); } return r; } String i2s(int i) { StringBuffer s = new StringBuffer(); while (i > 0) { i -= 1; s.append((char)('A' + (i % 26))); i /= 26; } return s.reverse().toString(); } BufferedReader in; PrintWriter out; }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; /* * Author : joney_000[jaswantsinghyada007@gmail.com] * Algorithm : N/A * Platform : Codeforces * Ref : */ public class A{ private InputStream inputStream ; private OutputStream outputStream ; private FastReader in ; private PrintWriter out ; private final int BUFFER = 100005; private final long mod = 1000000000+7; private final int INF = Integer.MAX_VALUE; private final long INF_L = Long.MAX_VALUE / 10; public A(){} public A(boolean stdIO)throws FileNotFoundException{ // stdIO = false; if(stdIO){ inputStream = System.in; outputStream = System.out; }else{ inputStream = new FileInputStream("input.txt"); outputStream = new FileOutputStream("output.txt"); } in = new FastReader(inputStream); out = new PrintWriter(outputStream); } void run()throws Exception{ long x = l(); long k = l(); if(x == 0){ out.write("0"); return; } x %= mod; long a = (x * pow(2L, k, mod) + mod)%mod; long b = (a - pow(2L, k, mod) + 1 + mod)%mod; long res = (a + b + mod )%mod; out.write(""+res+"\n"); } long gcd(long a, long b){ if(b == 0)return a; return gcd(b, a % b); } long lcm(long a, long b){ if(a == 0 || b == 0)return 0; return (a * b)/gcd(a, b); } long mulMod(long a, long b, long mod){ if(a == 0 || b == 0)return 0; if(b == 1)return a; long ans = mulMod(a, b/2, mod); ans = (ans * 2) % mod; if(b % 2 == 1)ans = (a + ans)% mod; return ans; } long pow(long a, long b, long mod){ if(b == 0)return 1; if(b == 1)return a; long ans = pow(a, b/2, mod); ans = (ans * ans); if(ans >= mod)ans %= mod; if(b % 2 == 1)ans = (a * ans); if(ans >= mod)ans %= mod; return ans; } // 20*20 nCr Pascal Table long[][] ncrTable(){ long ncr[][] = new long[21][21]; for(int i = 0; i <= 20; i++){ ncr[i][0] = ncr[i][i] = 1L; } for(int j = 0; j <= 20; j++){ for(int i = j + 1; i <= 20; i++){ ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; } } return ncr; } int i()throws Exception{ return in.nextInt(); } long l()throws Exception{ return in.nextLong(); } double d()throws Exception{ return in.nextDouble(); } char c()throws Exception{ return in.nextCharacter(); } String s()throws Exception{ return in.nextLine(); } BigInteger bi()throws Exception{ return in.nextBigInteger(); } private void closeResources(){ out.flush(); out.close(); return; } // IMP: roundoff upto 2 digits // double roundOff = Math.round(a * 100.0) / 100.0; // or // System.out.printf("%.2f", val); // print upto 2 digits after decimal // val = ((long)(val * 100.0))/100.0; public static void main(String[] args) throws java.lang.Exception{ A driver = new A(true); driver.run(); driver.closeResources(); } } class FastReader{ private boolean finished = false; private InputStream stream; private byte[] buf = new byte[4 * 1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream){ this.stream = stream; } public int read(){ if (numChars == -1){ throw new InputMismatchException (); } if (curChar >= numChars){ curChar = 0; try{ numChars = stream.read (buf); } catch (IOException e){ throw new InputMismatchException (); } if (numChars <= 0){ return -1; } } return buf[curChar++]; } public int peek(){ if (numChars == -1){ return -1; } if (curChar >= numChars){ curChar = 0; try{ numChars = stream.read (buf); } catch (IOException e){ return -1; } if (numChars <= 0){ return -1; } } return buf[curChar]; } public int nextInt(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } int res = 0; do{ if(c==','){ c = read(); } 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 String nextString(){ int c = read (); while (isSpaceChar (c)) c = read (); StringBuilder res = new StringBuilder (); do{ res.appendCodePoint (c); c = read (); } while (!isSpaceChar (c)); return res.toString (); } public 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; } private String readLine0(){ StringBuilder buf = new StringBuilder (); int c = read (); while (c != '\n' && c != -1){ if (c != '\r'){ buf.appendCodePoint (c); } c = read (); } return buf.toString (); } public String nextLine(){ String s = readLine0 (); while (s.trim ().length () == 0) s = readLine0 (); return s; } public String nextLine(boolean ignoreEmptyLines){ if (ignoreEmptyLines){ return nextLine (); }else{ return readLine0 (); } } public BigInteger nextBigInteger(){ try{ return new BigInteger (nextString ()); } catch (NumberFormatException e){ throw new InputMismatchException (); } } public char nextCharacter(){ int c = read (); while (isSpaceChar (c)) c = read (); return (char) c; } 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 boolean isExhausted(){ int value; while (isSpaceChar (value = peek ()) && value != -1) read (); return value == -1; } public String next(){ return nextString (); } public SpaceCharFilter getFilter(){ return filter; } public void setFilter(SpaceCharFilter filter){ this.filter = filter; } public interface SpaceCharFilter{ public boolean isSpaceChar(int ch); } } class Pair implements Comparable<Pair>{ public int a; public int b; public int c; public Pair(){ this.a = 0; this.b = 0; this.c = 0; } public Pair(int a,int b, int c){ this.a = a; this.b = b; this.c = c; } public int compareTo(Pair p){ return this.c - p.c; } @Override public String toString(){ return "a = " + this.a + " b = " + this.b + " c = "+this.c; } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class MAIN { public static void main(String args[]) { Scanner sn=new Scanner(System.in); int n,n1,n2,n3; int arr[]={0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170}; n=sn.nextInt(); if(n==2) { n1=n2=1; n3=0; } else if(n==1) { n3=n2=0; n1=1; } else if(n==0) { n1=n2=n3=0; } else if(n==3) { n1=n2=n3=1; } else { int index=bsearch(arr,0,arr.length-1,n); n1=arr[index-1]; n2=arr[index-3]; n3=arr[index-4]; } System.out.println(n3+" "+n2+" "+n1); } static int bsearch(int arr[],int l,int h,int n) { if(l>h) return -1; int mid=(l+h)/2; if(n==arr[mid]) return mid; else if(n>arr[mid]) return(bsearch(arr,mid+1,h,n)); else return(bsearch(arr,l,mid-1,n)); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.util.*; import java.io.*; import java.awt.Point; import java.math.BigInteger; import static java.lang.Math.*; // Solution is at the bottom of code public class ProblemC_008 implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; OutputWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new ProblemC_008(), "", 128 * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeBegin = System.currentTimeMillis(); Locale.setDefault(Locale.US); init(); solve(); out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// String delim = " "; String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(delim); } String readLine() throws IOException{ return in.readLine(); } ///////////////////////////////////////////////////////////////// final char NOT_A_SYMBOL = '\0'; char readChar() throws IOException{ int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } char[] readCharArray() throws IOException{ return readLine().toCharArray(); } ///////////////////////////////////////////////////////////////// int readInt() throws IOException{ return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException{ int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } /////////////////////////////////////////////////////////////////// long readLong() throws IOException{ return Long.parseLong(readString()); } long[] readLongArray(int size) throws IOException{ long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// double readDouble() throws IOException{ return Double.parseDouble(readString()); } double[] readDoubleArray(int size) throws IOException{ double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } ///////////////////////////////////////////////////////////////////// Point readPoint() throws IOException{ return new Point(readInt(), readInt()); } Point[] readPointArray(int size) throws IOException{ Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// class OutputWriter extends PrintWriter{ final int DEFAULT_PRECISION = 12; int precision; String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } public OutputWriter(OutputStream out) { super(out); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public int getPrecision() { return precision; } public void setPrecision(int precision) { this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } private String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } public void printWithSpace(double d){ printf(formatWithSpace, d); } public void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } public void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; boolean check(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// void solve() throws IOException{ Point bag = readPoint(); int n = readInt(); Point[] points = new Point[n]; for (int i = 0; i < n; ++i){ points[i] = readPoint(); } int[] dist = new int[n]; for (int i = 0; i < n; ++i){ int dx = points[i].x - bag.x; int dy = points[i].y - bag.y; dist[i] = dx * dx + dy * dy; } int[][] d = new int[n][n]; for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ int dx = points[i].x - points[j].x; int dy = points[i].y - points[j].y; d[i][j] = dx * dx + dy * dy; d[i][j] += dist[i] + dist[j]; } } int[] singleMasks = new int[n]; for (int i = 0; i < n; ++i){ singleMasks[i] = (1 << i); } int[][] doubleMasks = new int[n][n]; for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ doubleMasks[i][j] = (singleMasks[i] | singleMasks[j]); } } int lim = (1 << n); int[] dp = new int[lim]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; int[] p = new int[lim]; Arrays.fill(p, -1); for (int mask = 0; mask < lim; ++mask){ if (dp[mask] == Integer.MAX_VALUE){ continue; } int minBit = -1; for (int bit = 0; bit < n; ++bit){ if (checkBit(mask, bit)) continue; if (minBit == -1 || (dist[minBit] > dist[bit])){ minBit = bit; } } if (minBit == -1){ continue; } for (int bit = 0; bit < n; ++bit){ if (checkBit(mask, bit)) continue; int newMask = (mask | (1 << minBit) | (1 << bit)); if (dp[newMask] > dp[mask] + d[minBit][bit]){ dp[newMask] = dp[mask] + d[minBit][bit]; p[newMask] = minBit * n + bit; } } } out.println(dp[lim-1]); int curMask = lim - 1; while (p[curMask] != -1){ out.print("0 "); int first = p[curMask] / n; int second = p[curMask] % n; out.print((first + 1) + " "); curMask ^= (1 << first); if (first != second){ out.print((second + 1) + " "); curMask ^= (1 << second); } } out.println("0"); } private boolean checkBit(int mask, int bitNumber) { return (mask & (1 << bitNumber)) != 0; } boolean checkMask(int mask, int innerMask){ return (mask & innerMask) == innerMask; } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; //basically tried to understand ping's greedy alg public class kMultRedo { static int n; static int k; public static void main(String[] args){ Set<Integer> set = new TreeSet<Integer>(); FastScanner s = new FastScanner(); n = s.nextInt(); k = s.nextInt(); int[] a = new int[n]; for(int i=0; i<n; i++){ a[i] = s.nextInt(); } Arrays.sort(a); for(int i=0; i<n; i++){ if(a[i]%k !=0){ set.add(a[i]); }else{ if(!set.contains(a[i]/k)){ set.add(a[i]); } } } System.out.println(set.size()); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
/* bts songs to dance to: I need U Run ON Filter I'm fine */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class x1515E { static long MOD; public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); MOD = Long.parseLong(st.nextToken()); fac = new long[401]; invfac = new long[401]; fac[0] = invfac[0] = 1L; for(int i=1; i <= 400; i++) { fac[i] = (fac[i-1]*i)%MOD; invfac[i] = power(fac[i], MOD-2, MOD); } long[] pow2 = new long[401]; for(int i=0; i <= 400; i++) pow2[i] = power(2, i, MOD); long[][] dp = new long[N+1][N+1]; for(int v=1; v <= N; v++) { dp[v][v] = pow2[v-1]; for(int k=1; k <= v; k++) for(int block=1; block <= k; block++) { if(block == v) continue; long temp = (dp[v-block-1][k-block]*calc(k-block, block))%MOD; temp = (temp*pow2[block-1])%MOD; dp[v][k] += temp; if(dp[v][k] >= MOD) dp[v][k] -= MOD; } } long res = 0L; for(int v=1; v <= N; v++) { res += dp[N][v]; if(res >= MOD) res -= MOD; } System.out.println(res); } static long[] fac, invfac; public static long calc(int a, int b) { long res = (fac[a+b]*invfac[a])%MOD; return (res*invfac[b])%MOD; } public static long power(long x, long y, long p) { //0^0 = 1 long res = 1L; x = x%p; while(y > 0) { if((y&1)==1) res = (res*x)%p; y >>= 1; x = (x*x)%p; } return res; } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
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 C { static int MOD = 1_000_000_007; public static void main(String[] args) { MyScanner in = new MyScanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); char prev = ' '; // index, maxNumOfIntents -> count int[][] dp = new int[n+1][n+2]; dp[0][0] = 1; for(int i=0;i<n;++i){ char ch = in.next().charAt(0); if(prev == 's'){ int sum = 0; for(int j=n;j>=0;--j){ sum = (sum + dp[i-1][j]) % MOD; dp[i][j] = sum; } }else if(prev == 'f'){ for(int j=0;j<n;++j){ dp[i][j+1] = dp[i-1][j]; } } prev = ch; } int result = 0; for(int i=0;i<=n;++i){ result = (result + dp[n-1][i]) % MOD; } out.println(result); out.close(); } // -----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // -------------------------------------------------------- }
quadratic
909_C. Python Indentation
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; import java.math.*; public class Main implements Runnable { BufferedReader in; PrintStream out; StringTokenizer st = new StringTokenizer(""); static boolean local = false; public static void main(String [] args) throws Exception { if (args.length > 0) local = true; new Thread(new Main()).start(); } void printExit(String s) { out.println(s); System.exit(0); } public void run() { try { Locale.setDefault(Locale.US); in = local ? new BufferedReader(new FileReader("input.txt")) : new BufferedReader(new InputStreamReader(System.in)); out = local ? new PrintStream(new File("output.txt")) : new PrintStream(System.out); int n = nextInt(); char [] c = in.readLine().toCharArray(); int t = 0; for (int i = 0; i < n; i++) if (c[i] == 'T') t++; int ans = n; for (int i = 0; i < n; i++) { int cnt = 0; for (int j = 0; j < t; j++) if (c[(i + j) % n] == 'H') cnt++; ans = min(ans, cnt); } out.println(ans); } catch (Exception e) { e.printStackTrace(); } } boolean seekForToken() { try { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return false; } st = new StringTokenizer(s); } return true; } catch (IOException e) { e.printStackTrace(); return false; } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() { return new BigInteger(nextToken()); } String nextToken() { seekForToken(); return st.nextToken(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class incendio { void dbg(Object...os) { System.err.println(Arrays.deepToString(os)); } static StringTokenizer _stk; static BufferedReader input; static PrintWriter output; static String next(){return _stk.nextToken();} static int nextInt(){return Integer.parseInt(next());} static String readln()throws IOException {String l=input.readLine();_stk=l==null?null:new StringTokenizer(l," ");return l;} public static void main(String[] args) throws IOException { input = new BufferedReader(new FileReader("input.txt")); output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); new incendio(); output.close(); } incendio() throws IOException { readln(); M = nextInt(); N = nextInt(); readln(); final int K = nextInt(); int xf[]=new int[K], yf[]=new int[K]; readln(); for(int i=0; i<K; i++) { xf[i]=nextInt(); yf[i]=nextInt(); } int best=-1, xbest=0, ybest=0; for(int i=1; i<=M; i++) { for(int j=1; j<=N; j++) { int dist=Integer.MAX_VALUE; for(int k=0; k<K; k++) { dist = Math.min(dist, Math.abs(i-xf[k])+Math.abs(j-yf[k])); } if(dist>best) { best=dist; xbest=i; ybest=j; } } } output.println(xbest+" "+ybest); } int M, N; }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.InputMismatchException; import java.util.function.Function; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { long startTime = System.currentTimeMillis(); InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); EKeyboardPurchase solver = new EKeyboardPurchase(); solver.solve(1, in, out); out.close(); System.err.println(System.currentTimeMillis()-startTime+"ms"); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28); thread.start(); thread.join(); } static class EKeyboardPurchase { private final int iinf = 1_000_000_000; public EKeyboardPurchase() { } public void solve(int kase, InputReader in, Output pw) { int n = in.nextInt(), m = in.nextInt(); int[] arr = in.nextIntChar(o -> o-'a'); int[][] sum = new int[m][1<<m]; { int[][] cnt = new int[m][m]; for(int i = 0; i<n-1; i++) { int a = arr[i], b = arr[i+1]; cnt[a][b]++; cnt[b][a]++; } for(int i = 0; i<m; i++) { for(int j = 1; j<1<<m; j++) { int x = j&-j; sum[i][j] = sum[i][j^x]+cnt[i][31-Integer.numberOfLeadingZeros(x)]; } } } int[] mbit = new int[1<<m]; for(int i = 1; i<1<<m; i++) { mbit[i] = Integer.numberOfTrailingZeros(i&-i); } int[] dp = new int[1<<m]; for(int i = 1; i<1<<m; i++) { int ans = iinf, ci = i; for(int j = mbit[ci]; ci>0; ci -= (1<<j), j = mbit[ci]) { int cur = dp[i^(1<<j)]+sum[j][i^(1<<j)]; int x = ((1<<m)-1)^i; int cm = i; for(int k = mbit[cm]; cm>0; cm -= (1<<k), k = mbit[cm]) { cur += sum[k][x]; } cur -= sum[j][x]; ans = Math.min(ans, cur); } dp[i] = ans; } // dbg(dp); pw.println(dp[dp.length-1]); } } static interface InputReader { String next(); int nextInt(); default int[] nextIntChar(Function<Character, Integer> f) { String s = next(); int[] ret = new int[s.length()]; for(int i = 0; i<s.length(); i++) { ret[i] = f.apply(s.charAt(i)); } return ret; } } static class FastReader implements InputReader { final private int BUFFER_SIZE = 1<<16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public FastReader(InputStream is) { din = new DataInputStream(is); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { StringBuilder ret = new StringBuilder(64); byte c = skip(); while(c!=-1&&!isSpaceChar(c)) { ret.appendCodePoint(c); c = read(); } return ret.toString(); } public int nextInt() { int ret = 0; byte c = skipToDigit(); 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; } private boolean isSpaceChar(byte b) { return b==' '||b=='\r'||b=='\n'||b=='\t'||b=='\f'; } private byte skip() { byte ret; while(isSpaceChar((ret = read()))) ; return ret; } private boolean isDigit(byte b) { return b>='0'&&b<='9'; } private byte skipToDigit() { byte ret; while(!isDigit(ret = read())&&ret!='-') ; return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); throw new InputMismatchException(); } if(bytesRead==-1) { buffer[0] = -1; } } private byte read() { if(bytesRead==-1) { throw new InputMismatchException(); }else if(bufferPointer==bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public String lineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); lineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); } public void println() { sb.append(lineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.util.Scanner; public class A122 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); if (n % 4 == 0 || n % 7 == 0 || n % 44 == 0 || n % 47 == 0 || n % 74 == 0 || n % 77 == 0 || n % 444 == 0 || n % 447 == 0 || n % 474 == 0 || n % 477 == 0 || n % 744 == 0 || n % 747 == 0 || n % 774 == 0 || n % 777 == 0) System.out.println("YES"); else System.out.println("NO"); } }
constant
122_A. Lucky Division
CODEFORCES
import java.io.*; import java.util.*; public class a{ static int a; static Scanner sc = new Scanner(System.in); public static void main(String[] args) throws IOException{ int n = sc.nextInt(); int p = n; int m = sc.nextInt(); int k = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt() - 1; } Arrays.sort(a); int j =0; for(int i=0; i<n; i++){ if(m > k){ k = k + a[n-i-1]; j++; } } if(m > k) System.out.println(-1); else System.out.println(j); } }
nlogn
257_A. Sockets
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; public class Solution { private static int n; private static PrintWriter writer; private static int maxstep; private static void g(int src, int step) { if (step != 0 && n % src == 0) { writer.print("YES"); writer.close(); System.exit(0); } if (step == maxstep) return; int p = (int)Math.pow(10, step); g(src + 4 * p, step + 1); g(src + 7 * p, step + 1); } public static void main(String[] args) throws Exception { //Scanner reader = new Scanner(new File("input.txt")); //PrintWriter writer = new PrintWriter("output.txt"); Scanner reader = new Scanner(System.in); writer = new PrintWriter(System.out); n = reader.nextInt(); maxstep = String.valueOf(n).length() + 1; g(0, 0); writer.print("NO"); writer.close(); } }
constant
122_A. Lucky Division
CODEFORCES
import java.util.*; public class TaskB { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = s.nextInt(); int[] nums = new int[100000 + 10]; int first = -1, last = -1; Set<Integer> dif = new TreeSet<Integer>(); s.nextLine(); for (int i = 0; i < n; i++) { nums[i] = s.nextInt(); dif.add(nums[i]); if (dif.size() == k) { last = i; break; } } dif.clear(); for (int i = last; i >= 0; i--) { dif.add(nums[i]); if (dif.size() == k) { first = i; break; } } if (last == -1) System.out.print("-1 -1"); else System.out.print(Integer.toString(first + 1) + " " + Integer.toString(last + 1)); } }
linear
224_B. Array
CODEFORCES
import java.io.*; import java.lang.*; import java.util.*; public class alex { public static void main(String[] args)throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt();int sum=1; for(int i=1;i<=n;i++) { sum=sum+(4*(i-1)); } System.out.println(sum); } }
linear
1180_A. Alex and a Rhombus
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args){ Scanner in = new Scanner(System.in); long n = in.nextLong(); System.out.println(25); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; public class Main{ static long MOD = 1_000_000_007L; //static long MOD = 998_244_353L; //static long MOD = 1_000_000_033L; static long inv2 = (MOD + 1) / 2; static int[][] dir = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static long lMax = 0x3f3f3f3f3f3f3f3fL; static int iMax = 0x3f3f3f3f; static HashMap <Long, Long> memo = new HashMap(); static MyScanner sc = new MyScanner(); //static ArrayList <Integer> primes; static int nn = 300000; static long[] pow2; static long [] fac; static long [] pow; static long [] inv; static long [] facInv; static int[] base; static int[] numOfDiffDiv; static int[] numOfDiv; static ArrayList <Integer> primes; //static int[] primes; static int ptr = 0; static boolean[] isPrime; //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); // Start writing your solution here. ------------------------------------- /*fac = new long[nn + 1]; fac[1] = 1; for(int i = 2; i <= nn; i++) fac[i] = fac[i - 1] * i % MOD;*/ /*pow2 = new long[nn + 1]; pow2[0] = 1L; for(int i = 1; i <= nn; i++) pow2[i] = pow2[i - 1] * 2L;*/ /*inv = new long[nn + 1]; inv[1] = 1; for (int i = 2; i <= nn; ++i) inv[i] = (MOD - MOD / i) * inv[(int)(MOD % i)] % MOD;*/ /*facInv = new long[nn + 1]; facInv[0] = facInv[1] = 1; for (int i = 2; i <= nn; ++i) facInv[i] = facInv[i - 1] * inv[i] % MOD;*/ /*numOfDiffDiv = new int[nn + 1]; for(int i = 2; i <= nn; i++) if(numOfDiffDiv[i] == 0) for(int j = i; j <= nn; j += i) numOfDiv[j] ++;*/ /*numOfDiv = new int[nn + 1]; numOfDiv[1] = 1; for(int i = 2; i <= nn; i++) { for(int j = 2; j * j <= i; j++) { if(i % j == 0) { numOfDiv[i] = numOfDiv[i / j] + 1; break; } } }*/ //primes = sieveOfEratosthenes(100001); /* int t = 1; //t = sc.ni(); while(t-- > 0) { //boolean res = solve(); //out.println(res ? "YES" : "NO"); long res = solve(); out.println(res); }*/ int t = 1, tt = 0; t = sc.ni(); for(int i = 1; i <40000; i++) squares.add(i * i); while(tt++ < t) { boolean res = solve(); //out.println("Case #" + tt + ": " + res); out.println(res ? "YES" : "NO"); } out.close(); } static HashSet <Integer> squares = new HashSet(); static boolean solve() { /*String s = sc.nextLine(); char[] c = s.toCharArray(); int n = c.length;*/ //int n = sc.ni(); //long[] a = new long[n]; //for(int i = 0; i < n; i++) a[i] = sc.nl(); long res = 0; int n = sc.ni(); if(n % 2 == 0 && squares.contains(n / 2)) return true; if(n % 4 == 0 && squares.contains(n / 4)) return true; return false; } // edges to adjacency list by uwi public static int[][] packU(int n, int[] from, int[] to) { return packU(n, from, to, from.length); } public static int[][] packU(int n, int[] from, int[] to, int sup) { int[][] g = new int[n][]; int[] p = new int[n]; for (int i = 0; i < sup; i++) p[from[i]]++; for (int i = 0; i < sup; i++) p[to[i]]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < sup; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } // tree diameter by uwi public static int[] diameter(int[][] g) { int n = g.length; int f0 = -1, f1 = -1, d01 = -1; int[] q = new int[n]; boolean[] ved = new boolean[n]; { int qp = 0; q[qp++] = 0; ved[0] = true; for(int i = 0;i < qp;i++){ int cur = q[i]; for(int e : g[cur]){ if(!ved[e]){ ved[e] = true; q[qp++] = e; continue; } } } f0 = q[n-1]; } { int[] d = new int[n]; int qp = 0; Arrays.fill(ved, false); q[qp++] = f0; ved[f0] = true; for(int i = 0;i < qp;i++){ int cur = q[i]; for(int e : g[cur]){ if(!ved[e]){ ved[e] = true; q[qp++] = e; d[e] = d[cur] + 1; continue; } } } f1 = q[n-1]; d01 = d[f1]; } return new int[]{d01, f0, f1}; } public static long c(int n, int k) { return (fac[n] * facInv[k] % MOD) * facInv[n - k] % MOD; } // SegmentTree range min/max query by uwi public static class SegmentTreeRMQ { public int M, H, N; public int[] st; public SegmentTreeRMQ(int n) { N = n; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; st = new int[M]; Arrays.fill(st, 0, M, Integer.MAX_VALUE); } public SegmentTreeRMQ(int[] a) { N = a.length; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; st = new int[M]; for(int i = 0;i < N;i++){ st[H+i] = a[i]; } Arrays.fill(st, H+N, M, Integer.MAX_VALUE); for(int i = H-1;i >= 1;i--)propagate(i); } public void update(int pos, int x) { st[H+pos] = x; for(int i = (H+pos)>>>1;i >= 1;i >>>= 1)propagate(i); } private void propagate(int i) { st[i] = Math.min(st[2*i], st[2*i+1]); } public int minx(int l, int r){ int min = Integer.MAX_VALUE; if(l >= r)return min; while(l != 0){ int f = l&-l; if(l+f > r)break; int v = st[(H+l)/f]; if(v < min)min = v; l += f; } while(l < r){ int f = r&-r; int v = st[(H+r)/f-1]; if(v < min)min = v; r -= f; } return min; } public int min(int l, int r){ return l >= r ? 0 : min(l, r, 0, H, 1);} private int min(int l, int r, int cl, int cr, int cur) { if(l <= cl && cr <= r){ return st[cur]; }else{ int mid = cl+cr>>>1; int ret = Integer.MAX_VALUE; if(cl < r && l < mid){ ret = Math.min(ret, min(l, r, cl, mid, 2*cur)); } if(mid < r && l < cr){ ret = Math.min(ret, min(l, r, mid, cr, 2*cur+1)); } return ret; } } } public static char[] rev(char[] a){char[] b = new char[a.length];for(int i = 0;i < a.length;i++)b[a.length-1-i] = a[i];return b;} public static double dist(double a, double b){ return Math.sqrt(a * a + b * b); } public static long inv(long a){ return quickPOW(a, MOD - 2); } public class Interval { int start; int end; public Interval(int start, int end) { this.start = start; this.end = end; } } public static ArrayList<Integer> sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * 2; i <= n; i += p) { prime[i] = false; } } } ArrayList<Integer> primeNumbers = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (prime[i]) { primeNumbers.add(i); } } return primeNumbers; } public static int lowerBound(int[] a, int v){ return lowerBound(a, 0, a.length, v); } public static int lowerBound(int[] a, int l, int r, int v) { if(l > r || l < 0 || r > a.length)throw new IllegalArgumentException(); int low = l-1, high = r; while(high-low > 1){ int h = high+low>>>1; if(a[h] >= v){ high = h; }else{ low = h; } } return high; } public static int rlowerBound(int[] a, int v){ return lowerBound(a, 0, a.length, v); } public static int rlowerBound(int[] a, int l, int r, int v) { if(l > r || l < 0 || r > a.length)throw new IllegalArgumentException(); int low = l-1, high = r; while(high-low > 1){ int h = high+low>>>1; if(a[h] <= v){ high = h; }else{ low = h; } } return high; } public static long C(int n, int m) { if(m == 0 || m == n) return 1l; if(m > n || m < 0) return 0l; long res = fac[n] * quickPOW((fac[m] * fac[n - m]) % MOD, MOD - 2) % MOD; return res; } public static long quickPOW(long n, long m) { long ans = 1l; while(m > 0) { if(m % 2 == 1) ans = (ans * n) % MOD; n = (n * n) % MOD; m >>= 1; } return ans; } public static long quickPOW(long n, long m, long mod) { long ans = 1l; while(m > 0) { if(m % 2 == 1) ans = (ans * n) % mod; n = (n * n) % mod; m >>= 1; } return ans; } public static int gcd(int a, int b) { if(a % b == 0) return b; return gcd(b, a % b); } public static long gcd(long a, long b) { if(a % b == 0) return b; return gcd(b, a % b); } static class Randomized { public static void shuffle(int[] data) { shuffle(data, 0, data.length - 1); } public static void shuffle(int[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); int tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static void shuffle(long[] data) { shuffle(data, 0, data.length - 1); } public static void shuffle(long[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); long tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static int nextInt(int l, int r) { return RandomWrapper.INSTANCE.nextInt(l, r); } } static class RandomWrapper { private Random random; public static final RandomWrapper INSTANCE = new RandomWrapper(new Random()); public RandomWrapper() { this(new Random()); } public RandomWrapper(Random random) { this.random = random; } public int nextInt(int l, int r) { return random.nextInt(r - l + 1) + l; } } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.awt.Point; import java.io.*; import java.lang.Integer; import java.math.BigInteger; import java.util.*; public class Main { final boolean ONLINE_JUDGE = !new File("input.txt").exists(); BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } public static void main(String[] args) { new Main().run(); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } class LOL implements Comparable<LOL> { int x; int y; public LOL(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(LOL o) { if (o.x != x) return (int) (o.x - x); // ----> return (int) (y - o.y); // <---- } } long modulo = 1000 * 1000 * 1000 + 7; long binPow (long a, long b) { if(b == 0) return 1; long c = binPow(a, b / 2); long ans = (c * c) % modulo; if(b % 2 == 1) ans = (ans * a) % modulo; return ans; } int[] gcd (int a, int b) { int[] res = new int[3]; if (a == 0) { res[0] = b; res[1] = 0; res[2] = -1; return res; } res = gcd (b%a, a); int x = -(res[2] + (b / a) * res[1]); int y = - res[1]; res[1] = x; res[2] = y; return res; } public void solve() throws IOException { int n = readInt(); HashMap<Character,Integer> mapa = new HashMap<>(); char[] s = readString().toCharArray(); for(int i = 0; i < n; i++) { if(mapa.containsKey(s[i])) { int x = mapa.get(s[i]); mapa.replace(s[i], x + 1); } else mapa.put(s[i], 1); } int sz = mapa.size(); mapa = new HashMap<>(); int i = 0; while (mapa.size() < sz) { if(mapa.containsKey(s[i])) { int x = mapa.get(s[i]); mapa.replace(s[i], x + 1); } else mapa.put(s[i], 1); i++; } int ans = i; int left = 0; int right = i - 1; while(right < n) { while(left < right) { int y = mapa.get(s[left]); if(y == 1) mapa.remove(s[left]); else mapa.replace(s[left], y - 1); if(mapa.size() == sz) { ans = Math.min(ans, right - left); left++; } else { left++; break; } } right++; if(right < n) { if (mapa.containsKey(s[right])) { int x = mapa.get(s[right]); mapa.replace(s[right], x + 1); } else mapa.put(s[right], 1); } } out.print(ans); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.HashMap; import java.math.BigInteger; 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 Liavontsi Brechka */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static @SuppressWarnings("Duplicates") class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long[] a = in.nextLongArray(n); HashMap<Integer, Integer> count = new HashMap<>(); BigInteger res = BigInteger.ZERO; long prev = 0; count.put((int) a[0], 1); long temp; long nextRes; for (int i = 1; i < n; i++) { temp = ((a[i] - a[i - 1]) * i + prev); nextRes = temp - count.getOrDefault((int) a[i] - 1, 0) + count.getOrDefault((int) a[i] + 1, 0); res = res.add(new BigInteger(String.valueOf(nextRes))); count.put((int) a[i], count.getOrDefault((int) a[i], 0) + 1); prev = temp; } out.print(res); } } static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public long[] nextLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; ++i) { array[i] = nextLong(); } return array; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
nlogn
903_D. Almost Difference
CODEFORCES
//make sure to make new file! import java.io.*; import java.util.*; public class EG14{ public static long MOD; public static int MAX = 405; public static long[] fac; public static long[] ifac; public static void main(String[] args)throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); MOD = Long.parseLong(st.nextToken()); long[] pow2 = new long[MAX]; pow2[0] = 1L; for(int k = 1; k < MAX; k++){ pow2[k] = (2L*pow2[k-1] + MOD)%MOD; } fac = new long[MAX]; ifac = new long[MAX]; fac[0] = 1L; ifac[0] = 1L; for(int k = 1; k < MAX; k++){ fac[k] = ((long)k*fac[k-1] + MOD)%MOD; ifac[k] = modInverse(fac[k],MOD); } long[][] dp = new long[n][n+1]; //what n you're on, what how many computers you've turned on manually //initial for(int k = 0; k < n; k++){ dp[k][k+1] = pow2[k]; } for(int k = 2; k < n; k++){ for(int j = 1; j <= n; j++){ if(dp[k-2][j-1] == 0) continue; long start = dp[k-2][j-1]; //number for part up to previous block for(int add = 1; ; add++){ if(k+add-1 >= n || j+add-1 > n) break; long adder = (start * pow2[add-1] + MOD)%MOD; adder = (adder * choose(j+add-1,j-1) + MOD)%MOD; dp[k+add-1][j+add-1] = (dp[k+add-1][j+add-1] + adder + MOD)%MOD; } } } long answer = 0L; for(int k = 1; k <= n; k++){ answer = (answer + dp[n-1][k] + MOD)%MOD; } out.println(answer); out.close(); } //a choose b public static long choose(int a, int b){ long prod = (fac[a]*ifac[b] + MOD)%MOD; return (prod*ifac[a-b] + MOD)%MOD; } //from geeksforgeeks public static long modInverse(long a, long m) { long m0 = m; long y = 0L; long x = 1L; if (m == 1L) return 0L; while (a > 1L) { // q is quotient long q = a / m; long t = m; // m is remainder now, process same as // Euclid's algo m = a % m; a = t; t = y; // Update y and x y = x - q * y; x = t; } // Make x positive if (x < 0L) x += m0; return x; } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; public class Main { InputStreamReader inp = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(inp); boolean test = false; String[] inData = { "9", "HTHTHTHHT", }; static int id = -1; public String readLine() throws IOException { id++; if(test) return inData[id]; else return in.readLine(); } public Main() throws Throwable { int animalNr = Integer.valueOf(readLine()); String animals = readLine(); boolean[] state = new boolean[animalNr]; int tigerCount = 0; for (int i = 0; i < animals.length(); i++) { if('T' == animals.charAt(i)){ state[i] = true; tigerCount++; } } int best = Integer.MAX_VALUE; for (int i = 0; i < state.length; i++) { int swaps = 0; for (int j = i; j < i+tigerCount; j++) { if(state[j %animalNr] == false){ swaps ++; } } if(swaps < best){ best = swaps; } } System.out.println(best); } public static void main(String[] args) throws Throwable { new Main(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.util.*; import java.math.*; import java.io.*; public class b implements Runnable{ PrintWriter out = null; public int toint(String s){ int res = 0; for (int i = 0; i < s.length(); i++){ res *= 10; res += s.charAt(i)-'0'; } return res; } public void tostr(int k){ if (k == 0) return; tostr((k-1)/26); out.print((char)(('A'+((k-1)%26)))); } public int fromstr(String s){ if (s.length() == 0) return 0; int r = s.charAt(s.length()-1)-'A'+1; r += 26*(fromstr(s.substring(0,s.length()-1))); return r; } public void run(){ try{ Scanner in = new Scanner(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); for (int t = 0; t < n; t++){ int rp = -1; int cp = -1; String s = in.next(); for (int i = 0; i < s.length(); i++) if (s.charAt(i) == 'R') rp = i; else if (s.charAt(i) == 'C') cp = i; boolean good = true; if (rp == 0 && cp > 1){ for (int i = 0; i <= cp; i++) if (s.charAt(i) >= '0' && s.charAt(i) <= '9') good = false; } if (good){ int k = 0; for (;s.charAt(k) < '0' || s.charAt(k) > '9'; k++); int r = toint(s.substring(k,s.length())); int c = fromstr(s.substring(0,k)); out.print('R'); out.print(r); out.print('C'); out.println(c); } else { int r = toint(s.substring(1,cp)); int c = toint(s.substring(cp+1,s.length())); tostr(c); out.println(r); } } in.close(); out.close(); } catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args){ new Thread(new b()).start(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Andrew Porokhin, andrew.porokhin@gmail.com */ public class Problem111A implements Runnable { void solve() throws NumberFormatException, IOException { // TODO: Write your code here ... final int n = nextInt(); final int[] a = new int[n]; long sum = 0; for (int i = 0; i < n; i++) { final int nextInt = nextInt(); sum += nextInt; a[i] = nextInt; } Arrays.sort(a); int currSum = 0; int maxCoins = 0; for (int j = a.length - 1; j >= 0; j--) { currSum += a[j]; maxCoins++; if (sum - currSum < currSum) { break; } } System.out.println(maxCoins); } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) { // Introduce thread in order to increase stack size new Problem111A().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } catch (Exception e) { System.exit(9000); } finally { out.flush(); out.close(); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
nlogn
160_A. Twins
CODEFORCES
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws Exception { new A().solve(); // new FileInputStream(new File("input.txt")), // new PrintStream(new FileOutputStream(new File("output.txt")))); } void solve() throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Scanner sc = new Scanner(System.in); String[] sp; sp = in.readLine().split(" "); int n = Integer.parseInt(sp[0]); long k = Integer.parseInt(sp[1]); Long[] a = new Long[n]; sp = in.readLine().split(" "); for (int i = 0; i < n; i++) { a[i] = (long) Integer.parseInt(sp[i]); } Arrays.sort(a); TreeSet<Long> set = new TreeSet<Long>(); for (int i = 0; i < n; i++) { long x = a[i]; if (!set.contains(x)) { set.add(x * k); } } System.out.println(set.size()); } } // // // // // // // // // // // // // // // // // // // // // // // //
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.*; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int oo = (int)1e9; static int mod = 1000000007; public static void main(String[] args) throws IOException { int n = in.nextInt(); int[] a = in.nextIntArray(n); Arrays.sort(a); boolean[] color = new boolean[n]; int cnt = 0; for(int i = 0; i < n; ++i) { if(!color[i]) { cnt++; for(int j = i; j < n; j++) { if(a[j] % a[i] == 0) color[j] = true; } } } System.out.println(cnt); out.close(); } static class SegmentTree { int n; long[] a, seg; int DEFAULT_VALUE = 0; public SegmentTree(long[] a, int n) { super(); this.a = a; this.n = n; seg = new long[n * 4 + 1]; build(1, 0, n-1); } private long build(int node, int i, int j) { if(i == j) return seg[node] = a[i]; long first = build(node * 2, i, (i+j) / 2); long second = build(node * 2 + 1, (i+j) / 2 + 1, j); return seg[node] = combine(first, second); } long update(int k, long value) { return update(1, 0, n-1, k, value); } private long update(int node, int i, int j, int k, long value) { if(k < i || k > j) return seg[node]; if(i == j && j == k) { a[k] = value; seg[node] = value; return value; } int m = (i + j) / 2; long first = update(node * 2, i, m, k, value); long second = update(node * 2 + 1, m + 1, j, k, value); return seg[node] = combine(first, second); } long query(int l, int r) { return query(1, 0, n-1, l, r); } private long query(int node, int i, int j, int l, int r) { if(l <= i && j <= r) return seg[node]; if(j < l || i > r) return DEFAULT_VALUE; int m = (i + j) / 2; long first = query(node * 2, i, m, l, r); long second = query(node * 2 + 1, m+1, j, l, r); return combine(first, second); } private long combine(long a, long b) { return a + b; } } static class DisjointSet { int n; int[] g; int[] h; public DisjointSet(int n) { super(); this.n = n; g = new int[n]; h = new int[n]; for(int i = 0; i < n; ++i) { g[i] = i; h[i] = 1; } } int find(int x) { if(g[x] == x) return x; return g[x] = find(g[x]); } void union(int x, int y) { x = find(x); y = find(y); if(x == y) return; if(h[x] >= h[y]) { g[y] = x; if(h[x] == h[y]) h[x]++; } else { g[x] = y; } } } static int[] getPi(char[] a) { int m = a.length; int j = 0; int[] pi = new int[m]; for(int i = 1; i < m; ++i) { while(j > 0 && a[i] != a[j]) j = pi[j-1]; if(a[i] == a[j]) { pi[i] = j + 1; j++; } } return pi; } static long lcm(long a, long b) { return a * b / gcd(a, b); } static boolean nextPermutation(int[] a) { for(int i = a.length - 2; i >= 0; --i) { if(a[i] < a[i+1]) { for(int j = a.length - 1; ; --j) { if(a[i] < a[j]) { int t = a[i]; a[i] = a[j]; a[j] = t; for(i++, j = a.length - 1; i < j; ++i, --j) { t = a[i]; a[i] = a[j]; a[j] = t; } return true; } } } } return false; } static void shuffle(int[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); int t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(long[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); long t = a[si]; a[si] = a[i]; a[i] = t; } } static int lower_bound(int[] a, int n, int k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int lower_bound(long[] a, int n, long k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return this.first != o.first ? this.first - o.first : this.second - o.second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import static java.util.Arrays.*; import static java.lang.Math.*; import java.util.*; import java.io.*; public class Main implements Runnable { public static void main(String [] args) throws IOException { new Thread(null, new Main(), "", 1 << 20).start(); } String file = "input"; BufferedReader input; PrintWriter out; public void run() { try { //input = new BufferedReader(new FileReader(file + ".in")); input = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); solve(); input.close(); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } int[] x = new int[25]; int[] y = new int[25]; int[][] dist = new int[25][25]; int[] single = new int[25]; int[] c = new int[25]; int INF = 1 << 30; void solve() throws IOException { StringTokenizer st = tokens(); x[0] = nextInt(st); y[0] = nextInt(st); int n = nextInt(); for(int i = 1; i <= n; i++) { st = tokens(); x[i] = nextInt(st); y[i] = nextInt(st); } for(int i = 1; i <= n; i++) single[i] = 2 * ((x[i] - x[0]) * (x[i] - x[0]) + (y[i] - y[0]) * (y[i] - y[0])); for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) dist[i][j] = single[i] / 2 + single[j] / 2 + (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]); int[] dp = new int[1 << n]; int[] prev = new int[1 << n]; fill(dp, INF); dp[0] = 0; for(int i = 1; i < 1 << n; i++) { for(int j = 0; j < n; j++) { if((i >> j & 1) != 0) { if(dp[i] > dp[i ^ (1 << j)] + single[j + 1]) { dp[i] = dp[i ^ (1 << j)] + single[j + 1]; prev[i] = j + 1; } for(int k = j + 1; k < n; k++) if((i >> k & 1) != 0) { if(dp[i] > dp[i ^ (1 << j) ^ (1 << k)] + dist[j + 1][k + 1]) { dp[i] = dp[i ^ (1 << j) ^ (1 << k)] + dist[j + 1][k + 1]; prev[i] = (j + 1) * 100 + (k + 1); } } break; } } } out.println(dp[(1 << n) - 1]); out.print("0 "); int mask = (1 << n) - 1; while(mask > 0) { int s = prev[mask]; int x = s / 100; int y = s % 100; if(x == 0) { out.print(y + " " + 0 + " "); mask -= 1 << (y - 1); } else { out.print(x + " " + y + " " + 0 + " "); mask -= 1 << (y - 1); mask -= 1 << (x - 1); } } } StringTokenizer tokens() throws IOException { return new StringTokenizer(input.readLine()); } String next(StringTokenizer st) { return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(input.readLine()); } int nextInt(StringTokenizer st) { return Integer.parseInt(st.nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(input.readLine()); } double nextDouble(StringTokenizer st) { return Double.parseDouble(st.nextToken()); } void print(Object... o) { out.println(deepToString(o)); } }
np
8_C. Looking for Order
CODEFORCES
import javax.print.attribute.standard.RequestingUserName; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); int tc = in.nextInt(); for(int i = 0; i < tc; i++) solver.solve(i, in, out); out.close(); } static class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { int k = in.nextInt(); int[] s = getArray(in.nextToken()); int[] a = getArray(in.nextToken()); int[] b = getArray(in.nextToken()); int[] per = new int[k]; boolean[] used = new boolean[k]; Arrays.fill(per , -1); if(!check(s , a, per.clone(), k, used)){ out.println("NO"); return; } for(int i = 0; i < s.length; i++){ if(per[s[i]] != -1){ continue; } for(int j = 0; j < k; j++){ if(used[j]){ continue; } per[s[i]] = j; used[j] = true; if(check(s , a , per.clone() , k, used)){ break; } per[s[i]] = -1; used[j] = false; } } for(int i = 0; i < s.length; i++){ if(per[s[i]] == -1){ out.println("NO"); return; } s[i] = per[s[i]]; } if(cmp(s , b) > 0){ out.println("NO"); return; } int last = 0; for(int i = 0; i < k; i++){ if(per[i] == -1) { while(used[last])last++; per[i] = last; used[last] = true; } } char[] result = new char[k]; for(int i = 0; i < k; i++){ result[i] = (char)('a' + per[i]); } out.println("YES"); out.println(new String(result)); } private int cmp(int[] a, int[] b){ for(int i = 0; i < a.length; i++){ if(a[i] != b[i]){ return a[i] < b[i] ? -1 : 1; } } return 0; } private boolean check(int[] s, int[] a, int[] per, int k, boolean[] used) { int res[] = new int[s.length]; int last = k - 1; for(int i = 0; i < res.length; ++i){ if(per[s[i]] == -1){ while(last >= 0 && used[last]){ last--; } if(last < 0){ return false; } per[s[i]] = last; last--; } res[i] = per[s[i]]; } return cmp(a , res) <= 0; } private int[] getArray(String nextToken) { int result[] = new int[nextToken.length()]; for(int i = 0; i < nextToken.length(); i++){ result[i] = nextToken.charAt(i) - 'a'; } return result; } } static class InputReader { BufferedReader in; StringTokenizer tok; public InputReader(InputStream stream){ in = new BufferedReader(new InputStreamReader(stream), 32768); tok = null; } String nextToken() { String line = ""; while(tok == null || !tok.hasMoreTokens()) { try { if((line = in.readLine()) != null) tok = new StringTokenizer(line); else return null; } catch (IOException e) { e.printStackTrace(); return null; } } return tok.nextToken(); } int nextInt(){ return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
quadratic
1086_C. Vasya and Templates
CODEFORCES
import java.util.*; import java.io.*; import java.text.*; public class CF_1523_C{ //SOLUTION BEGIN void pre() throws Exception{} void solve(int TC) throws Exception{ int N = ni(); int[] A = new int[N]; for(int i = 0; i< N; i++)A[i] = ni(); // Stack<Integer> stack = new Stack<>(); int[] stack = new int[2*N]; int sz = 0; for(int i = 0; i< N; i++){ if(A[i] == 1)stack[sz++] = 1; else{ while (sz > 0 && stack[sz-1]+1 != A[i])sz--;//!stack.isEmpty() && stack.peek()+1 != A[i])stack.pop(); hold(sz != 0); stack[sz-1]++; hold(stack[sz-1] == A[i]); } hold(sz != 0); StringBuilder st = new StringBuilder(); for(int s = 0; s< sz; s++){ st.append(stack[s]); if(s+1 < sz)st.append("."); } pn(st.toString()); } } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} void exit(boolean b){if(!b)System.exit(0);} static void dbg(Object... o){System.err.println(Arrays.deepToString(o));} final long IINF = (long)1e17; final int INF = (int)1e9+2; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8; static boolean multipleTC = true, memory = true, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ long ct = System.currentTimeMillis(); if (fileIO) { in = new FastReader(""); out = new PrintWriter(""); } else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = multipleTC? ni():1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); System.err.println(System.currentTimeMillis() - ct); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new CF_1523_C().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start(); else new CF_1523_C().run(); } int[][] make(int n, int e, int[] from, int[] to, boolean f){ int[][] g = new int[n][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = to[i]; if(f)g[to[i]][--cnt[to[i]]] = from[i]; } return g; } int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){ int[][][] g = new int[n][][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0}; if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1}; } return g; } int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));} int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object... o){for(Object oo:o)out.print(oo+" ");} void pn(Object... o){for(int i = 0; i< o.length; i++)out.print(o[i]+(i+1 < o.length?" ":"\n"));} void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskG2 solver = new TaskG2(); solver.solve(1, in, out); out.close(); } static class TaskG2 { static final int MOD = 1000000000 + 7; static final int MAXN = 51; int getWays(int i, int j, int k, int l, int[][][][] ways, boolean[][][][] cached) { if (i + j + k == 0) return l == -1 ? 1 : 0; if (l < 0) return 0; if (cached[i][j][k][l]) return ways[i][j][k][l]; int s = i + j + k; long value = 0; if (l == 0 && i != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i - 1, j, k, x, ways, cached); } } if (l == 1 && j != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i, j - 1, k, x, ways, cached); } } if (l == 2 && k != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i, j, k - 1, x, ways, cached); } } ways[i][j][k][l] = (int) (value % MOD); cached[i][j][k][l] = true; return ways[i][j][k][l]; } int totalWays(int i, int j, int k, int[][][][] ways, boolean[][][][] cached, int[] factorial) { long ret = 0; for (int l = 0; l < 3; l++) ret += getWays(i, j, k, l, ways, cached); ret *= factorial[i]; ret %= MOD; ret *= factorial[j]; ret %= MOD; ret *= factorial[k]; ret %= MOD; return (int) ret; } int add(int type, int value, int[] sizes, int sum, int[][][][] dp) { sizes[type]++; if (type == 0) { for (int s = sum + value; s >= value; s--) { for (int i = 1; i <= sizes[0]; i++) for (int j = 0; j <= sizes[1]; j++) for (int k = 0; k <= sizes[2]; k++) { dp[i][j][k][s] += dp[i - 1][j][k][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } if (type == 1) { for (int s = sum + value; s >= value; s--) { for (int i = 0; i <= sizes[0]; i++) for (int j = 1; j <= sizes[1]; j++) for (int k = 0; k <= sizes[2]; k++) { // System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length); dp[i][j][k][s] += dp[i][j - 1][k][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } if (type == 2) { for (int s = sum + value; s >= value; s--) { for (int i = 0; i <= sizes[0]; i++) for (int j = 0; j <= sizes[1]; j++) for (int k = 1; k <= sizes[2]; k++) { // System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length); dp[i][j][k][s] += dp[i][j][k - 1][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } return sum + value; } public void solve(int testNumber, InputReader in, OutputWriter out) { int[][][][] ways = new int[MAXN][MAXN][MAXN][3]; boolean[][][][] cached = new boolean[MAXN][MAXN][MAXN][3]; // Arrays.fill(ways, -1); int n = in.nextInt(), T = in.nextInt(); ArrayList<Integer>[] ar = new ArrayList[3]; for (int i = 0; i < 3; i++) ar[i] = new ArrayList<Integer>(); int total_sum = 0; for (int i = 0; i < n; i++) { int t = in.nextInt(), g = in.nextInt(); ar[g - 1].add(t); total_sum += t; } if (T > total_sum) { out.println(0); return; } int min_index = 0, mn = 100000000; for (int i = 0; i < 3; i++) { if (ar[i].size() < mn) { mn = ar[i].size(); min_index = i; } } int[][][][] dp = new int[ar[(1 + min_index) % 3].size() + 1][ar[(2 + min_index) % 3].size() + 1][1][total_sum + 1]; int[][][][] dp2 = new int[1][1][mn + 1][total_sum + 1]; dp[0][0][0][0] = dp2[0][0][0][0] = 1; int[] sizes = {0, 0, 0}; int sum = 0; int[] order = {(min_index + 1) % 3, (min_index + 2) % 3}; int type = 0; for (int i : order) { for (int v : ar[i]) sum = add(type, v, sizes, sum, dp); type++; } sum = 0; sizes[0] = sizes[1] = sizes[2] = 0; for (int i : ar[min_index]) sum = add(2, i, sizes, sum, dp2); int[] factorial = new int[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; i++) factorial[i] = (int) ((factorial[i - 1] * 1L * i) % MOD); long answer = 0; for (int i = 0; i < dp.length; i++) for (int j = 0; j < dp[0].length; j++) for (int k = 0; k <= mn; k++) for (int s = 0; s <= T; s++) { long x = (dp[i][j][0][s] * 1L * totalWays(i, j, k, ways, cached, factorial)) % MOD; x *= dp2[0][0][k][T - s]; x %= MOD; answer += x; } out.println(answer % MOD); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import javax.script.*; public class Noldbach { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); boolean[] sieve=new boolean[1001]; sieve[2]=false; ArrayList<Integer> primes=new ArrayList<Integer>(); for(int x=2;x<1001;x++) if(!sieve[x]) { primes.add(x); for(int y=x;y<1001;y+=x) sieve[y]=true; } int sum=0; for(int x=2;x<=n;x++) { if(primes.contains(x)) { int need=x-1; for(int y=0;y<primes.size()-1;y++) { if(primes.get(y)+primes.get(y+1)==need) { sum++; break; } } } if(sum==k)break; } if(sum==k)System.out.println("YES"); else System.out.println("NO"); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt();HashSet<Integer>nums=new HashSet<Integer>(); int[]in=new int[n];for(int i=0;i<n;i++)in[i]=sc.nextInt(); Arrays.sort(in); int ans=0; boolean vis[]=new boolean[n]; for(int i=0;i<n;i++) { if(vis[i])continue; for(int j=i+1;j<n;j++) { if(in[j]%in[i]==0) { vis[j]=true; } } ans++; } pw.println(ans); pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
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.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Asgar Javadov */ 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(); int d = in.nextInt(); int[] a = in.readIntArray(n); int ans = 1; for (int i = 0; i < a.length - 1; ++i) { int left = a[i] + d; int right = a[i + 1] - d; if (left < right) { ans += 2; } else if (left == right) ans++; } out.println(ans + 1); } } static class OutputWriter extends PrintWriter { public OutputWriter(OutputStream outputStream) { super(outputStream); } public OutputWriter(Writer writer) { super(writer); } public OutputWriter(String filename) throws FileNotFoundException { super(filename); } public void close() { super.close(); } } static class InputReader extends BufferedReader { StringTokenizer tokenizer; public InputReader(InputStream inputStream) { super(new InputStreamReader(inputStream), 32768); } public InputReader(String filename) { super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename))); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(readLine()); } catch (IOException e) { throw new RuntimeException(); } } return tokenizer.nextToken(); } public Integer nextInt() { return Integer.valueOf(next()); } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = nextInt(); return array; } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author sheep */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { long a = in.nextLong(); long b = in.nextLong(); out.println(go(a, b)); } private long go(long a, long b) { if (b == 0) return 0; return a / b + go(b, a % b); } } class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new UnknownError(); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.*; import java.util.*; public class A { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { String s = nextToken(); int res = Integer.parseInt(s); String s1 = s.substring(0, s.length() - 1); res = Math.max(res, Integer.parseInt(s1)); String s2 = s.substring(0, s.length() - 2) + s.charAt(s.length() - 1); res = Math.max(res, Integer.parseInt(s2)); out.println(res); } A() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new A(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.util.Scanner; public class Subtractions { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while (t-- > 0) { int a = scan.nextInt(); int b = scan.nextInt(); int res = 0; while (a != 0 && b != 0) { if (a > b) { res += (a / b); a %= b; } else { res += (b / a); b %= a; } } System.out.println(res); } } }
constant
267_A. Subtractions
CODEFORCES
import java.io.*; public class n5D { public static void main(String[] args) { double a = 0, v = 0, l = 0, d = 0, w = 0; try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] str = br.readLine().split(" "); a = Double.parseDouble(str[0]); v = Double.parseDouble(str[1]); str = br.readLine().split(" "); l = Double.parseDouble(str[0]); d = Double.parseDouble(str[1]); w = Double.parseDouble(str[2]); } catch(Exception e) { System.out.println(e); } double t1, t2, t3, t4, t5, t, D = 0; if (w > v) w = v; t2 = d / v - v / a + w * w / 2 / a / v; if (t2 >= 0) { t1 = v / a; t3 = t1 - w / a; } else { if (Math.sqrt(2 * d / a) > (w / a)) { t1 = Math.sqrt((2 * a * d + w * w) / (a * a * 2)); t3 = t1 - w / a; } else { t1 = Math.sqrt(2 * d / a); t3 = 0; } t2 = 0; } t5 = (l - d - v * v / 2 / a + a * (t1 - t3) * (t1 - t3) / 2) / v; if (t5 >= 0) t4 = v / a - (t1 - t3); else { t5 = 0; t4 = -t1 + t3 + Math.sqrt((t1 - t3) * (t1 - t3) + 2 * (l - d) / a); } t = t1 + t2 + t3 + t4 + t5; System.out.println(t); //System.out.println(t1 + " " + t2 + " " + t3 + " " + t4 + " " + t5); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.io.*; import java.util.*; public class C { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader s = new FastReader(); static PrintWriter out = new PrintWriter(System.out); private static int[] rai(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } return arr; } private static int[][] rai(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextInt(); } } return arr; } private static long[] ral(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextLong(); } return arr; } private static long[][] ral(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextLong(); } } return arr; } private static int ri() { return s.nextInt(); } private static long rl() { return s.nextLong(); } private static String rs() { return s.next(); } static long gcd(long a,long b) { if(b==0) { return a; } return gcd(b,a%b); } static int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } static boolean isPrime(int n) { //check if n is a multiple of 2 if (n % 2 == 0) return false; //if not, then just check the odds for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static int MOD=1000000007; static long mpow(long base,long pow) { long res=1; while(pow>0) { if(pow%2==1) { res=(res*base)%MOD; } pow>>=1; base=(base*base)%MOD; } return res; } public static void main(String[] args) { StringBuilder ans = new StringBuilder(); int t = ri(); // int t = 1; while (t-- > 0) { int n=ri(); int[] arr=rai(n); List<Integer> list = new ArrayList<>(); for(int i:arr) { if(i==1) { list.add(i); } else { int ind = list.size()-1; while(list.size()>0 && list.get(ind)+1!=i ) { list.remove(list.size()-1); ind=list.size()-1; } if(list.size()>0) { list.remove(list.size()-1); } list.add(i); } for(int j=0;j<list.size()-1;j++) { ans.append(list.get(j)).append("."); } ans.append(list.get(list.size()-1)).append("\n"); } } out.print(ans.toString()); out.flush(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class R489C { static long m = (long)(1e9+7); /* 1000000000000000000 */ public static void main(String[] args) { JS scan = new JS(); long n = scan.nextLong(); long k = scan.nextLong(); if(n == 0) { System.out.println(0); return; } if(k == 0) { long ans = (n%m)*(2%m)%m; System.out.println(ans%m); return; } //System.out.println(2+" "+(k+1)+" "+m); long coeff = power(2L, k+1, m); //System.out.println(coeff); long r = (coeff%m)*(n%m)%m; //System.out.println(r); long x = power(2L, k, m)%m-1; if(x < 0) x += m; long ans = r-x; if(ans < 0) ans += m; System.out.println(ans%m); } static long power(long x, long y, long p){ // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0){ // If y is odd, multiply x // with result if((y & 1)==1) res = (res%p * x%p) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x%p * x%p) % p; } return res; } /* 1000000000000000000 1000000000000000000 */ static class JS{ public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public JS() { in = new BufferedInputStream(System.in, BS); } public JS(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.*; import java.util.LinkedList; public class Solution { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("input.txt")); PrintWriter out = new PrintWriter("output.txt"); String[] raw = in.readLine().split(" "); int n = Integer.parseInt(raw[0]); int m = Integer.parseInt(raw[1]); int k = Integer.parseInt(in.readLine()); raw = in.readLine().split(" "); boolean[][] map = new boolean[n][m]; LinkedList<Point> queue = new LinkedList<>(); for (int i = 0; i < k; i++) { Point fireStarter = new Point(Integer.parseInt(raw[i * 2]) - 1, Integer.parseInt(raw[i * 2 + 1]) - 1); queue.addLast(fireStarter); } int treesLeft = n * m; while (true) { Point firepoint = queue.removeFirst(); if (map[firepoint.x][firepoint.y]) continue; treesLeft--; map[firepoint.x][firepoint.y] = true; if (treesLeft == 0) { out.printf("%d %d", firepoint.x + 1, firepoint.y + 1); out.flush(); return; } if (firepoint.x > 0 && !map[firepoint.x - 1][firepoint.y]) queue.add(new Point(firepoint.x - 1, firepoint.y)); if (firepoint.y > 0 && !map[firepoint.x][firepoint.y - 1]) queue.add(new Point(firepoint.x, firepoint.y - 1)); if (firepoint.x < n - 1 && !map[firepoint.x + 1][firepoint.y]) queue.add(new Point(firepoint.x + 1, firepoint.y)); if (firepoint.y < m - 1 && !map[firepoint.x][firepoint.y + 1]) queue.add(new Point(firepoint.x, firepoint.y + 1)); // // for (int i = 0; i < n; i++) { // for (int j = 0; j < m; j++) { // System.out.printf("%d ", map[i][j] ? 1 : 0); // } // System.out.println(); // } // System.out.println("\n-------\n"); } } private static class Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Berland implements Runnable { private void solve() throws IOException { double a = nextInt(); double v = nextInt(); double l = nextInt(); double d = nextInt(); double w = nextInt(); double res; if (v <= w) { res = simpleCase(a, v, l, 0); } else { double vMax = Math.sqrt(2 * d * a); if (vMax <= w) { res = simpleCase(a, v, l, 0); } else { double tFullSpeed = v / a; double tSlowdown = (v - w) / a; if (a * tFullSpeed * tFullSpeed / 2 + v * tSlowdown - a * tSlowdown * tSlowdown / 2 <= d) { res = tFullSpeed + tSlowdown + (d - (a * tFullSpeed * tFullSpeed / 2 + v * tSlowdown - a * tSlowdown * tSlowdown / 2)) / v + simpleCase(a, v, l - d, w); } else { double min = w; double max = v; for (int i = 0; i < 1000; ++i) { double cur = (min + max) / 2; double cFullSpeed = cur / a; double cSlowdown = (cur - w) / a; if (a * cFullSpeed * cFullSpeed / 2 + cur * cSlowdown - a * cSlowdown * cSlowdown / 2 <= d) min = cur; else max = cur; } res = min / a + (min - w) / a + simpleCase(a, v, l - d, w); } } } writer.printf("%.20f\n", res); } private double simpleCase(double a, double v, double l, double v0) { double tFullSpeed = (v - v0) / a; if (v0 * tFullSpeed + a * tFullSpeed * tFullSpeed / 2 <= l) { return tFullSpeed + (l - (v0 * tFullSpeed + a * tFullSpeed * tFullSpeed / 2)) / v; } else { double min = 0; double max = tFullSpeed; for (int i = 0; i < 1000; ++i) { double cur = (min + max) / 2; if (v0 * cur + a * cur * cur / 2 <= l) min = cur; else max = cur; } return min; } } public static void main(String[] args) { new Berland().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
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 CFD { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; final long MOD = 1000L * 1000L * 1000L + 7; int[] dx = {0, -1, 0, 1}; int[] dy = {1, 0, -1, 0}; void solve() throws IOException { int n = nextInt(); long[] arr = nextLongArr(n); long[] diff = new long[n]; long presum = 0; for (int i = n - 1; i >= 0; i--) { diff[i] = presum - (n - i - 1) * arr[i]; presum += arr[i]; } BigInteger pairs = new BigInteger("0"); for (long s : diff) { pairs = pairs.add(new BigInteger(Long.toString(s))); } BigInteger need = new BigInteger("0"); Map<Long, Long> hm = new HashMap<>(); for (int i = n - 1; i >= 0; i--) { long v1 = hm.getOrDefault(arr[i] - 1, 0L) * (-1); need = need.add(new BigInteger(Long.toString(v1))); long v2 = hm.getOrDefault(arr[i] + 1, 0L); need = need.add(new BigInteger(Long.toString(v2))); hm.put(arr[i], hm.getOrDefault(arr[i], 0L) + 1); } BigInteger res = pairs.subtract(need); out(res.toString()); } void shuffle(long[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); long tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } public CFD() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFD(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
nlogn
903_D. Almost Difference
CODEFORCES
import java.io.*; import java.util.*; public class Main implements Runnable { Scanner in; PrintWriter out; //= new PrintWriter(System.out); public static void main(String[] args) throws FileNotFoundException, IOException { new Thread(new Main()).start(); } public class Pair { public long last; public long count; public int L; Pair(long l, long c) {last = l; count = c;} Pair(long l, long c, int L) {last = l; count = c; this.L = L;} } public void run() { final String name = "B-small"; //try { in = new Scanner(System.in);// (new File(name + ".in"));//StreamTokenizer(new FileReader(new File(name + ".in"))); out = new PrintWriter(System.out); // new PrintWriter(new File(name + ".out")); //= new PrintWriter(System.out); //} catch (IOException e) {} String s = in.next().trim(); int n = s.length(); boolean[][] a = new boolean[n][n]; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) a[i][j] = (s.charAt(i) == s.charAt(j)); int max = 0; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) { int k =0; while (i + k < n && j + k < n && a[i + k][j + k]) ++k; if (max < k) max = k; } out.println(max); out.flush(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; arr[0] = sc.nextInt(); for (int i = 1; i < n; i++) { arr[i] = arr[i - 1] + sc.nextInt(); } HashMap<Integer, List<Pair>> map = new HashMap<>(); for (int i = 0; i < n; i++) { if (map.containsKey(arr[i])) map.get(arr[i]).add(new Pair(0, i)); else { List<Pair> l = new ArrayList<>(); l.add(new Pair(0, i)); map.put(arr[i], l); } for (int j = 1; j <= i; j++) { int ss = arr[i] - arr[j - 1]; if (map.containsKey(ss)) map.get(ss).add(new Pair(j, i)); else { List<Pair> l = new ArrayList<>(); l.add(new Pair(j, i)); map.put(ss, l); } } } List<Pair> el = null; for (List<Pair> value : map.values()) { value.sort(Comparator.comparingInt(Pair::getStart)); ArrayList<Pair> ps = new ArrayList<>(); Pair last = value.get(0); for (int i = 1; i < value.size(); i++) { if (last.getEnd() < value.get(i).getStart()) { ps.add(last); last = value.get(i); } else if (last.getEnd() > value.get(i).getEnd()) last = value.get(i); } ps.add(last); if (el == null) el = ps; else if (ps.size() > el.size()) el = ps; } System.out.println(el.size()); for (Pair pair : el) { System.out.println((pair.getStart() + 1) + " " + (pair.getEnd() + 1)); } } } class Pair { private final int start; private final int end; public int getStart() { return start; } public int getEnd() { return end; } public Pair(int start, int end) { this.start = start; this.end = end; } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.File; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class C { Scanner in; PrintWriter out; // String INPUT = "3 3 1 1 1"; String INPUT = ""; void solve() { int n = ni(); int m = ni(); int k = ni(); int[][] f=new int[k][2]; for(int i=0;i<k;i++) { f[i][0]=ni()-1; f[i][1]=ni()-1; } int mx=-1; int resx=0; int resy=0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int min=Integer.MAX_VALUE; for(int l=0;l<k;l++) { min=Math.min(min, Math.abs(f[l][0]-i)+Math.abs(f[l][1]-j)); } if(min>mx) { mx=min; resx=i; resy=j; } } } out.println((resx+1)+" "+(resy+1)); } void run() throws Exception { in = INPUT.isEmpty() ? new Scanner(new File("input.txt")) : new Scanner(INPUT); out = INPUT.isEmpty() ? new PrintWriter("output.txt") : new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new C().run(); } int ni() { return Integer.parseInt(in.next()); } void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); } static String join(int[] a, int d){StringBuilder sb = new StringBuilder();for(int v : a){sb.append(v + d + " ");}return sb.toString();} }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SFly { public static void main(String[] args) throws IOException { BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); int planet = Integer.parseInt(lector.readLine()); int ini = Integer.parseInt(lector.readLine()); double peso = ini; int[] desp = new int[planet]; int[] ater = new int[planet]; String[] temp = lector.readLine().split(" "); for(int i=0; i<planet; i++) { desp[i] = Integer.parseInt(temp[i]); if(desp[i] == 1) { System.out.println(-1); lector.close(); return; } } temp = lector.readLine().split(" "); for(int i=0; i<planet; i++) { ater[i] = Integer.parseInt(temp[i]); if(ater[i] == 1) { System.out.println(-1); lector.close(); return; } } temp = null; int i=planet-1; peso = (peso*ater[0])/(ater[0]-1); while(i>0) { peso = (peso*desp[i])/(desp[i]-1); peso = (peso*ater[i])/(ater[i]-1); i--; } peso = (peso*desp[0])/(desp[0]-1); peso = peso - ini; System.out.println(peso); lector.close(); } }
linear
1010_A. Fly
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); Arrays.sort(a); if (k >= m) { out.println(0); return; } for (int i = 1; i <= n; i++) { int sockets = k - 1; for (int j = 0; j < i; j++) sockets += a[n - j - 1]; sockets -= i - 1; if (sockets >= m) { out.println(i); return; } } out.println(-1); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } }
nlogn
257_A. Sockets
CODEFORCES
import java.util.*; import java.io.*; public class Fish { public static void main(String[] args) throws Exception { new Fish(); } public Fish() throws Exception { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); double[][] P = new double[N][N]; for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) P[i][j] = sc.nextDouble(); double[] best = new double[1 << N]; best[(1 << N)-1] = 1; for(int mask = (1 << N)-1; mask > 0; mask--) { int C = Integer.bitCount(mask); if(C == 1) continue; for(int i = 0; i < N; i++) if (on(mask, i)) for(int j = i+1; j < N; j++) if(on(mask, j)) { int nmask = mask & ~(1 << j); best[nmask] += P[i][j] * best[mask] * 2.0 / (C*(C-1.0)); nmask = mask & ~(1 << i); best[nmask] += P[j][i] * best[mask] * 2.0/ (C*(C-1.0)); } } for(int i = 0; i < N; i++) System.out.printf("%.7f ", best[1 << i] + 1e-9); System.out.println(); } boolean on(int mask, int pos) { return (mask & (1 << pos)) > 0; } }
np
16_E. Fish
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class problemB185 { public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringBuffer sb=new StringBuffer(); int n=Integer.parseInt(br.readLine()); if(n<0){ int temp=-n; int temp2=temp/10; int x=temp%10; int y=temp2%10; if(x>y){ temp=temp/10; } else{ temp=temp/10 -y +x; } n=-temp; } System.out.println(n); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Test { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } private static void solve() throws IOException { int n=nextInt(); int[] a=new int[n]; int first=0; for (int i=0;i<n;i++) { a[i]=nextInt(); first+=a[i]; } Arrays.sort(a); int ans=1; int last=a[n-1]; first-=a[n-ans]; while (true) { if (first<last) break; ans++; last+=a[n-ans]; first-=a[n-ans]; } writer.print(ans); } }
nlogn
160_A. Twins
CODEFORCES
//package pack; import java.util.*; public class first { public static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); long x=sc.nextLong(); long k=sc.nextLong(); long mod=1000000007; if(k==0 || x==0) System.out.println((2*x)%mod); else { long answer=1; answer+=(power(2,k,mod))*(((2*x)-1)%mod); System.out.println(answer%mod); } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.awt.*; import java.io.*; import java.sql.Array; import java.util.*; import java.util.List; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static final int N=205; static final int mod=1000000007; static final int INF=1000000009; static final int numBit=17; static FastReader r=new FastReader(); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int n=r.nextInt(); int m=r.nextInt(); int k=r.nextInt(); int [][]hor=new int[n][m-1]; int [][]ver=new int[n-1][m]; for(int i=0;i<n;++i){ for(int j=0;j<m-1;++j) hor[i][j]=r.nextInt(); } for(int i=0;i<n-1;++i){ for(int j=0;j<m;++j) ver[i][j]=r.nextInt(); } int [][]dp=new int[n][m]; if(k%2!=0){ for(int i=0;i<n;++i){ for(int j=0;j<m;++j) dp[i][j]=-1; } } else{ int [][]new_dp=new int[n][m]; for(int step=0;step<k/2;++step){ for(int i=0;i<n;++i){ for(int j=0;j<m;++j){ new_dp[i][j]=INF; if(i>0){ new_dp[i][j]=Math.min(new_dp[i][j],dp[i-1][j]+ver[i-1][j]*2); } if(i<n-1){ new_dp[i][j]=Math.min(new_dp[i][j],dp[i+1][j]+ver[i][j]*2); } if(j>0){ new_dp[i][j]=Math.min(new_dp[i][j],dp[i][j-1]+hor[i][j-1]*2); } if(j<m-1){ new_dp[i][j]=Math.min(new_dp[i][j],dp[i][j+1]+hor[i][j]*2); } } } for(int i=0;i<n;++i){ for(int j=0;j<m;++j){ dp[i][j]=new_dp[i][j]; } } } } for(int i=0;i<n;++i){ for(int j=0;j<m;++j){ pw.print(dp[i][j]+" "); } pw.println(); } pw.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; // :%s/Cbeta35/"name"/ // if (debug) public class Cbeta35 { public static void main(String[] args) { new Cbeta35(); } Scanner in; PrintWriter out; int t; int n, m, k, oo; int[][] grid; boolean debug = !true, multi = !true; Cbeta35() { if (multi) t = in.nextInt(); do { if (multi) if (z(t--)) break; try { in = new Scanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } catch (Exception e) { in = new Scanner(System.in); out = new PrintWriter(System.out); } n = in.nextInt(); m = in.nextInt(); k = in.nextInt(); oo = n + m + 1; grid = new int[n][m]; for (int i = 0; i < n; i++) Arrays.fill(grid[i], oo); for (int i = 0; i < k; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; for (int j = 0; j < n; j++) for (int kk = 0; kk < m; kk++) { int dx = j - x < 0 ? x - j : j - x; int dy = kk - y < 0 ? y - kk : kk - y; grid[j][kk] = min(grid[j][kk], dx + dy); } } int x = 0, y = 0; int max = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (max < grid[i][j]) { max = grid[i][j]; x = i; y = j; } out.printf("%d %d%n", x + 1, y + 1); } while (debug || multi); out.close(); } int min(int a, int b) { if (a < b) return a; return b; } int max(int a, int b) { if (a > b) return a; return b; } long min(long a, long b) { if (a < b) return a; return b; } long max(long a, long b) { if (a > b) return a; return b; } boolean z(int x) { if (x == 0) return true; return false; } boolean z(long x) { if (x == 0) return true; return false; } void sort(int[] arr) { int szArr = arr.length; Random r = new Random(); for (int i = 0; i < szArr; i++) { int j = r.nextInt(szArr); arr[i] = arr[j]^(arr[i]^(arr[j] = arr[i])); } Arrays.sort(arr); } class FS { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.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()); } } }
cubic
35_C. Fire Again
CODEFORCES
import java.awt.Point; import java.io.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Main{ static class Run implements Runnable{ //TODO parameters final boolean consoleIO = false; final String inFile = "input.txt"; final String outFile = "output.txt"; int n,m,k; int[][] field; boolean[][] visited; LinkedList<Point> queue; int[][] steps = {{0,1},{1,0},{0,-1},{-1,0}}; void wave() { for(Point p:queue) visited[p.y][p.x] = true; while(!queue.isEmpty()) { Point cur = queue.removeFirst(); for(int i = 0; i < steps.length; ++i) { Point tmp = new Point(cur.x+steps[i][0],cur.y+steps[i][1]); if(ok(tmp)&&!visited[tmp.y][tmp.x]) { queue.add(tmp); visited[tmp.y][tmp.x] = true; field[tmp.y][tmp.x] = field[cur.y][cur.x]+1; } } } } boolean ok(Point p) { return p.x>=0 && p.y>=0 && p.x<n && p.y<m; } @Override public void run() { n = nextInt(); m = nextInt(); k = nextInt(); queue = new LinkedList<Point>(); for(int i = 0; i < k; ++i) queue.add(new Point(nextInt()-1,nextInt()-1)); field = new int[m][n]; visited = new boolean[m][n]; wave(); Point maxP = new Point(0,0); int maxV = Integer.MIN_VALUE; for(int i = 0; i < m; ++i) for(int j = 0; j < n; ++j) if(field[i][j] > maxV) { maxV = field[i][j]; maxP = new Point(j,i); } print((maxP.x+1)+" "+(maxP.y+1)); close(); } //========================================================================================================================= BufferedReader in; PrintWriter out; StringTokenizer strTok; Run() { if (consoleIO) { initConsoleIO(); } else { initFileIO(); } } void initConsoleIO() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } void initFileIO() { try { in = new BufferedReader(new FileReader(inFile)); out = new PrintWriter(new FileWriter(outFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } void close() { try { in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } int nextInt() { return Integer.parseInt(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } float nextFloat() { return Float.parseFloat(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } String nextLine() { try { return in.readLine(); } catch (IOException e) { return "__NULL"; } } boolean hasMoreTokens() { return (strTok == null) || (strTok.hasMoreTokens()); } String nextToken() { while (strTok == null || !strTok.hasMoreTokens()) { String line; try { line = in.readLine(); strTok = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return strTok.nextToken(); } void cout(Object o){ System.out.println(o); } void print(Object o) { out.write(o.toString()); } void println(Object o) { out.write(o.toString() + '\n'); } void printf(String format, Object... args) { out.printf(format, args); } String sprintf(String format, Object... args) { return MessageFormat.format(format, args); } } static class Pair<A, B> { A a; B b; A f() { return a; } B s() { return b; } Pair(A a, B b) { this.a = a; this.b = b; } Pair(Pair<A, B> p) { a = p.f(); b = p.s(); } } public static void main(String[] args) throws IOException { Run run = new Run(); Thread thread = new Thread(run); thread.run(); } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.util.NoSuchElementException; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ 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); } InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int maxdist = -1, maxrow = -1, maxcol = -1; int rows = in.ri(), cols = in.ri(); int k = in.ri(); IntPair[] points = new IntPair[k]; for(int i = 0; i < k; i++) points[i] = new IntPair(in.ri(), in.ri()); for(int row = 1; row <= rows; row++) { for(int col = 1; col <= cols; col++) { int mindist = Integer.MAX_VALUE; for(int i = 0; i < k; i++) mindist = Math.min(mindist, Math.abs(row - points[i].first) + Math.abs(col - points[i].second)); if (mindist > maxdist){ maxdist = mindist; maxrow = row; maxcol = col; } } } out.printLine(maxrow, maxcol); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int ri(){ return readInt(); } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IntPair implements Comparable<IntPair> { public int first, second; public IntPair(int first, int second) { this.first = first; this.second = second; } public String toString() { return "(" + first + "," + second + ")"; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IntPair intPair = (IntPair) o; return first == intPair.first && second == intPair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public int compareTo(IntPair o) { if (first < o.first) return -1; if (first > o.first) return 1; if (second < o.second) return -1; if (second > o.second) return 1; return 0; } }
cubic
35_C. Fire Again
CODEFORCES
import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Main { private static void solve() { int n = ni(); int d = ni(); int[] a = na(n); Arrays.sort(a); Set<Integer> set = new HashSet<>(); for (int i = 0; i < n; i ++) { int cand1 = a[i] - d; int cand2 = a[i] + d; int d1 = d; int d2 = d; for (int j = 0; j < n; j ++) { d1 = Math.min(d1, Math.abs(a[j] - cand1)); d2 = Math.min(d2, Math.abs(a[j] - cand2)); } if (d1 == d) { set.add(cand1); } if (d2 == d) { set.add(cand2); } } System.out.println(set.size()); } public static void main(String[] args) { new Thread(null, new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); String debug = args.length > 0 ? args[0] : null; if (debug != null) { try { is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug)); } catch (Exception e) { throw new RuntimeException(e); } } reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768); solve(); out.flush(); tr((System.currentTimeMillis() - start) + "ms"); } }, "", 64000000).start(); } private static java.io.InputStream is = System.in; private static java.io.PrintWriter out = new java.io.PrintWriter(System.out); private static java.util.StringTokenizer tokenizer = null; private static java.io.BufferedReader reader; public static String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new java.util.StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } private static double nd() { return Double.parseDouble(next()); } private static long nl() { return Long.parseLong(next()); } private static int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private static char[] ns() { return next().toCharArray(); } private static long[] nal(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private static int[][] ntable(int n, int m) { int[][] table = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { table[i][j] = ni(); } } return table; } private static int[][] nlist(int n, int m) { int[][] table = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { table[j][i] = ni(); } } return table; } private static int ni() { return Integer.parseInt(next()); } private static void tr(Object... o) { if (is != System.in) System.out.println(java.util.Arrays.deepToString(o)); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Bag implements Runnable { private void solve() throws IOException { int xs = nextInt(); int ys = nextInt(); int n = nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = nextInt(); y[i] = nextInt(); } final int[][] pair = new int[n][n]; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]); final int[] single = new int[n]; for (int i = 0; i < n; ++i) { single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys)); } final int[] best = new int[1 << n]; final int[] prev = new int[1 << n]; for (int set = 1; set < (1 << n); ++set) { int i; for (i = 0; i < n; ++i) if ((set & (1 << i)) != 0) break; best[set] = best[set ^ (1 << i)] + single[i]; prev[set] = 1 << i; int nextSet = set ^ (1 << i); int unoI = 1 << i; for (int j = i + 1, unoJ = 1 << (i + 1); j < n; ++j, unoJ <<= 1) if ((set & unoJ) != 0) { int cur = best[nextSet ^ unoJ] + pair[i][j]; if (cur < best[set]) { best[set] = cur; prev[set] = unoI | unoJ; } } } writer.println(best[(1 << n) - 1]); int now = (1 << n) - 1; writer.print("0"); while (now > 0) { int differents = prev[now]; for(int i = 0; i < n; i++) if((differents & (1 << i)) != 0) { writer.print(" "); writer.print(i + 1); now ^= 1 << i; } writer.print(" "); writer.print("0"); } writer.println(); } public static void main(String[] args) { new Bag().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.Scanner; import java.util.TreeSet; public class Test { int readInt() { int ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } final int N = 5010; final int M = 1_000_000_007; long[][] dp = new long[2][N]; long[] sums = new long[N]; char[] p = new char[N]; Scanner sca = new Scanner(System.in); void start() { int n = Integer.parseInt(sca.nextLine()); int idx = 0; Arrays.fill(dp[idx], 0); dp[idx][0] = 1; for (int i = 0; i < n; i++) p[i] = sca.nextLine().charAt(0); for (int i = 0; i < n;) { int nidx = idx ^ 1; Arrays.fill(dp[nidx], 0); Arrays.fill(sums, 0); int j = i; while (p[j] != 's') j++; int levels = j - i; i = j+1; for (j = n; j >= 0; j--) { sums[j] = sums[j + 1] + dp[idx][j]; if (sums[j] >= M) sums[j] -= M; } for (j = 0; j <= n; j++) { int ind = j + levels; if (ind > n) continue; dp[nidx][ind] = sums[j]; } idx = nidx; } long ans = 0; for (int i = 0; i <= n; i++) { ans += dp[idx][i]; if (ans >= M) ans -=M; } System.out.println(ans); } public static void main(String[] args) { new Test().start(); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Code { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); HashMap<Double,Integer>h = new HashMap<>(); double [] temp = new double[n]; int m = 0; for(int i=0;i<n;i++) { String l = br.readLine(); int[] x = new int[4]; int k=0; boolean t = false; for(int j=0;j<l.length();j++) { if(l.charAt(j)=='(' || l.charAt(j)=='+' || l.charAt(j)==')' || l.charAt(j)=='/') x[k++] = j; } double a = Integer.parseInt(l.substring(x[0]+1,x[1])); double b = Integer.parseInt(l.substring(x[1]+1, x[2])); double c = Integer.parseInt(l.substring(x[3]+1)); temp[m++] = (a+b)/c; //System.out.print((a+b)/c + " "); if(h.containsKey((a+b)/c)) h.put((a+b)/c, h.get((a+b)/c)+1); else h.put((a+b)/c, 1); } //System.out.println(h); for(int i=0;i<n;i++) { System.out.print(h.get(temp[i]) + " "); } } }
linear
958_D1. Hyperspace Jump (easy)
CODEFORCES
import java.util.*; import java.io.*; public class code { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); long[] d = new long[30]; d[0] = 1; for(int i=1;i<30;i++) d[i] = d[i-1]*4; for(int z=0;z<q;z++){ long r = 0; long n = sc.nextLong(); long k = sc.nextLong(); long c = 1; while(k>0&&n>=1){ if(k<=r) { k=0; break; } n--; k-=c; if(k<=0) break; if(n>30) { k=0; break; } for(int i=0;i<(int)n;i++){ r += d[i]*(c*2-1); if(k<=r) { k=0; break; } } if(k<=r) { k=0; break; } c*=2; c++; } if(k==0) System.out.println("YES "+n); else System.out.println("NO"); } } } /* NO YES 0 YES 0 NO NO YES 999999942 YES 59 YES 63 YES 2 NO YES 1 YES 1 NO NO YES 0 YES 0*/
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.OutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Objects; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Queue; import java.util.LinkedList; 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; 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); } InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CFireAgain solver = new CFireAgain(); solver.solve(1, in, out); out.close(); } static class CFireAgain { private int n; private int m; private int K; private boolean[][] vis; private Queue<Util.Pair<Integer>> queue = new LinkedList<>(); private Util.Pair<Integer> p; private boolean isValid(int x, int y) { return x >= 1 && x <= n && y >= 1 && y <= m && !vis[x][y]; } private void bfs() { while (!queue.isEmpty()) { p = queue.poll(); if (isValid(p.x + 1, p.y)) { queue.offer(new Util.Pair<>(p.x + 1, p.y)); vis[p.x + 1][p.y] = true; } if (isValid(p.x - 1, p.y)) { queue.offer(new Util.Pair<>(p.x - 1, p.y)); vis[p.x - 1][p.y] = true; } if (isValid(p.x, p.y + 1)) { queue.offer(new Util.Pair<>(p.x, p.y + 1)); vis[p.x][p.y + 1] = true; } if (isValid(p.x, p.y - 1)) { queue.offer(new Util.Pair<>(p.x, p.y - 1)); vis[p.x][p.y - 1] = true; } } } public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); m = in.nextInt(); K = in.nextInt(); vis = new boolean[n + 1][m + 1]; for (int i = 0; i < K; i++) { int a = in.nextInt(), b = in.nextInt(); vis[a][b] = true; queue.offer(new Util.Pair<>(a, b)); } bfs(); out.println(p.x + " " + p.y); out.flush(); } } static class OutputWriter { private final PrintWriter writer; private ArrayList<String> res = new ArrayList<>(); private StringBuilder sb = new StringBuilder(""); public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(Object... objects) { for (int i = 0; i < objects.length; i++) { sb.append(objects[i]); } res.add(sb.toString()); sb = new StringBuilder(""); } public void close() { // writer.flush(); writer.close(); } public void flush() { for (String str : res) writer.printf("%s\n", str); res.clear(); sb = new StringBuilder(""); } } static class Util { public static class Pair<T> { public T x; public T y; public Pair(T x, T y) { this.x = x; this.y = y; } public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Util.Pair)) return false; Util.Pair<T> pair = (Util.Pair<T>) obj; return this.x == pair.x && this.y == pair.y; } public String toString() { return ("(" + this.x + "," + this.y + ")"); } public int hashCode() { return Objects.hash(x, y); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public InputReader(FileInputStream file) { this.stream = file; } 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 = (res << 3) + (res << 1) + c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
cubic
35_C. Fire Again
CODEFORCES
import java.util.*; import java.io.*; public class CF911D { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] array = new int[n]; for(int i = 0; i < n; i++){ array[i] = sc.nextInt(); } int count = 0; for(int i = 0; i < array.length; i++){ for(int j = i+1; j < array.length; j++){ if(array[i] > array[j]){ count++; } } } count%=2; int q = sc.nextInt(); for(int i = 0; i < q; i++){ int l = sc.nextInt(); int r = sc.nextInt(); int sz = r - l + 1; count += (sz*(sz-1))/2; count %= 2; if(count == 1) System.out.println("odd"); else System.out.println("even"); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class D { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } final int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } @SuppressWarnings("unchecked") void solve() throws IOException { final int n = nextInt(); int m = nextInt(); int[] from = new int[m]; int[] to = new int[m]; for(int i = 0; i < m; i++) { from[i] = nextInt(); to[i] = nextInt(); } int ans = solve(n, m, from, to); writer.println(ans); writer.close(); } private int solve(final int n, int m, int[] from, int[] to) { final List<List<Integer>> g = new ArrayList<>(); final List<List<Integer>> rg = new ArrayList<>(); for(int i = 0; i <= n; i++) { g.add(new ArrayList<Integer>()); rg.add(new ArrayList<Integer>()); } int[] c = new int[n + 1]; int[] loop = new int[n + 1]; for(int i = 0; i < m; i++) { int u = from[i]; int v = to[i]; g.get(u).add(v); rg.get(v).add(u); c[u]++; c[v]++; if(u == v) { loop[u]++; } } class Utils { int[] prev = new int[n + 1]; int[] next = new int[n + 1]; int[] used = new int[n + 1]; int mark; int forbidden; int maxMatch() { maxMatch = 0; for(int i = 1; i <= n; i++) { mark = i; if(findPath(i)) { maxMatch++; } } return maxMatch; } boolean findPath(int u) { if(u == forbidden) { return false; } used[u] = mark; for (int v : g.get(u)) { if(v == forbidden) { continue; } if(prev[v] == 0 || (used[prev[v]] != mark && findPath(prev[v]))) { prev[v] = u; next[u] = v; return true; } } return false; } int maxMatch = 0; void amend(int u) { // Arrays.fill(used, false); if(findPath(u)) { maxMatch++; } } void cancel(int u) { forbidden = u; int v = next[u]; if(v != 0) { maxMatch--; prev[v] = 0; next[u] = 0; for (int i : rg.get(v)) { if(next[i] == 0) { amend(i); } } // amend(v); } if(prev[u] != 0) { maxMatch--; amend(prev[u]); prev[u] = 0; } } } // Utils utils = new Utils(); // for(int i = 1; i <= n; i++) { // utils.amend(i); // } int ans = Integer.MAX_VALUE; for(int i = 1; i <= n; i++) { // utils.cancel(i); // utils.amend(i - 1); Utils utils = new Utils(); utils.forbidden = i; utils.maxMatch(); ans = Math.min(ans, (2 * n - 1 - c[i] + loop[i]) + (m - c[i] + loop[i] - utils.maxMatch) + (n - 1 - utils.maxMatch)); } return ans; } void test() { final int N = 4; final int[] ef = new int[N * N]; final int[] et = new int[N * N]; for(int i = 1; i <= N; i++) { for(int j = 1; j <= N; j++) { ef[(i - 1) * N + j - 1] = i; et[(i - 1) * N + j - 1] = j; } } List<Integer> good = new ArrayList<>(); for(int mask = 0; mask < 1 << N * N; mask++) { int[] in = new int[N + 1]; int[] out = new int[N + 1]; for(int i = 0; i < N * N; i++) { if((mask >> i) % 2 == 1) { out[ef[i]]++; in[et[i]]++; } } boolean ok = false; for(int i = 1; i <= N; i++) { if(in[i] == N && out[i] == N) { in[i] = 2; out[i] = 2; ok = true; break; } } for(int i = 1; i <= N; i++) { if(in[i] != 2 || out[i] != 2) { ok = false; } } if(ok) { good.add(mask); } } System.out.println("good graphs count: " + good.size()); for (int mask : good) { int m = Integer.bitCount(mask); int[] from = new int[m]; int[] to = new int[m]; int index = 0; for(int i = 0; i < N * N; i++) { if((mask >> i) % 2 == 1) { from[index] = ef[i]; to[index] = et[i]; index++; } } if(solve(N, m, from, to) != 0) { writer.println(N + " " + m); for(int i = 0; i < m; i++) { writer.println(from[i] + " " + to[i]); } writer.close(); return; } } for(int mask = 0; mask < 1 << N * N; mask++) { int optimal = Integer.MAX_VALUE; for (Integer i : good) { optimal = Math.min(optimal, Integer.bitCount(i ^ mask)); } int m = Integer.bitCount(mask); int[] from = new int[m]; int[] to = new int[m]; int index = 0; for(int i = 0; i < N * N; i++) { if((mask >> i) % 2 == 1) { from[index] = ef[i]; to[index] = et[i]; index++; } } final int fast = solve(N, m, from, to); if(optimal != fast) { System.out.println("fast = " + fast + ", optimal = " + optimal); writer.println(N + " " + m); for(int i = 0; i < m; i++) { writer.println(from[i] + " " + to[i]); } writer.close(); return; } } } public static void main(String[] args) throws IOException { new D().solve(); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.*; import java.lang.*; import java.util.*; import static java.lang.Integer.*; import static java.lang.Long.*; import static java.lang.Math.*; import static java.lang.System.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main { Main() throws IOException { String a = nextLine(); String b = nextLine(); long ans = 0; int s = 0; for (int i = 0; i < b.length() - a.length(); ++i) { s += b.charAt(i) == '1' ? 1 : 0; } for (int i = 0; i < a.length(); ++i) { s += b.charAt(i + b.length() - a.length()) == '1' ? 1 : 0; ans += a.charAt(i) == '1' ? b.length() - a.length() + 1 - s : s; s -= b.charAt(i) == '1' ? 1 : 0; } out.println(ans); } ////////////////////////////// PrintWriter out = new PrintWriter(System.out, false); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stok = null; String nextLine() throws IOException { while (stok == null || !stok.hasMoreTokens()) { stok = new StringTokenizer(in.readLine()); } return stok.nextToken(); } public static void main(String args[]) throws IOException { if (args.length > 0) { setIn(new FileInputStream(args[0] + ".inp")); setOut(new PrintStream(args[0] + ".out")); } Main solver = new Main(); solver.out.flush(); // could be replace with a method, but nah, this is just competitive programming :p } }
linear
608_B. Hamming Distance Sum
CODEFORCES
import java.io.*; import java.util.*; public class Main { static Scanner in; static PrintWriter out; // static final String PROBLEM = ""; public static void main(String[] args) throws Exception { in = new Scanner(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); boolean[] p = new boolean[n + 5]; int[] pp = new int[n + 5]; int ind = 0; Arrays.fill(p, true); p[0] = false; p[1] = false; for (int i = 2; i < n + 5; i++) if (p[i]) { pp[ind++] = i; for (int j = 2*i; j < n + 5; j += i) p[j] = false; } // for (int i = 0; i < 30; i++) if (p[i]) out.println(i); boolean[] b = new boolean[n + 1]; for (int i = 0; i < ind - 1; i++) if (pp[i] + pp[i + 1] + 1 <= n && p[pp[i] + pp[i + 1] + 1]) b[pp[i] + pp[i + 1] + 1] = true; int kol = 0; for (int i = 2; i <= n; i++) if (b[i]) kol++; if (kol >= k) out.println("YES"); else out.println("NO"); out.close(); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class E { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int T = Integer.parseInt(bf.readLine()); for(int t=0; t<T; t++) { StringTokenizer st = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[][] a = new int[n][m]; for(int i=0; i<n; i++) { st = new StringTokenizer(bf.readLine()); for(int j=0; j<m; j++) a[i][j] = Integer.parseInt(st.nextToken()); } // small case int[] max = new int[m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if(a[i][j] > max[j]) max[j] = a[i][j]; } } int[][] pos = new int[m][2]; for(int i=0; i<m; i++) { pos[i][0] = max[i]; pos[i][1] = i; } Arrays.sort(pos, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o2[0], o1[0]); } }); int[][] new_a = new int[n][Math.min(n,m)]; for(int i=0; i<n; i++) { for(int j=0; j<Math.min(n,m); j++) { new_a[i][j] = a[i][pos[j][1]]; } } int exp = 1; for(int i=0; i<Math.min(n,m); i++) exp *= n; int maxval = -1; for(int i=0; i<exp; i++) { // int val = i; int sum = 0; for(int j=0; j<n; j++) { int toAdd = 0; int val = i; for(int k=0; k<Math.min(n,m); k++) { int tooAdd = new_a[(j+val)%n][k]; val /= n; if(tooAdd > toAdd) toAdd = tooAdd; } sum += toAdd; } if(sum > maxval) maxval = sum; } out.println(maxval); } // StringTokenizer st = new StringTokenizer(bf.readLine()); // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); // int n = Integer.parseInt(st.nextToken()); out.close(); System.exit(0); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; import java.awt.*; // U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................ //JUst keep faith in ur strengths .................................................. // ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219 // odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4 // FOR ANY ODD NO N : N,N-1,N-2 //ALL ARE PAIRWISE COPRIME //THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS // two consecutive odds are always coprime to each other // two consecutive even have always gcd = 2 ; // Rectangle r = new Rectangle(int x , int y,int widht,int height) //Creates a rect. with bottom left cordinates as (x, y) and top right as ((x+width),(y+height)) //BY DEFAULT Priority Queue is MIN in nature in java //to use as max , just push with negative sign and change sign after removal // We can make a sieve of max size 1e7 .(no time or space issue) // In 1e7 starting nos we have about 66*1e4 prime nos public class Main { // static int[] arr = new int[100002] ; // static int[] dp = new int[100002] ; static PrintWriter out; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out); } 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 int countDigit(long n) { return (int)Math.floor(Math.log10(n) + 1); } ///////////////////////////////////////////////////////////////////////////////////////// public static int sumOfDigits(long n) { if( n< 0)return -1 ; int sum = 0; while( n > 0) { sum = sum + (int)( n %10) ; n /= 10 ; } return sum ; } ////////////////////////////////////////////////////////////////////////////////////////////////// public static long arraySum(int[] arr , int start , int end) { long ans = 0 ; for(int i = start ; i <= end ; i++)ans += arr[i] ; return ans ; } ///////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public static void swapArray(int[] arr , int start , int end) { while(start < end) { int temp = arr[start] ; arr[start] = arr[end]; arr[end] = temp; start++ ;end-- ; } } ////////////////////////////////////////////////////////////////////////////////// static long factorial(long a) { if(a== 0L || a==1L)return 1L ; return a*factorial(a-1L) ; } /////////////////////////////////////////////////////////////////////////////// public static int[][] rotate(int[][] input){ int n =input.length; int m = input[0].length ; int[][] output = new int [m][n]; for (int i=0; i<n; i++) for (int j=0;j<m; j++) output [j][n-1-i] = input[i][j]; return output; } /////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////// //////////////////////////////////////////////// public static boolean isPowerOfTwo(long n) { if(n==0) return false; if(((n ) & (n-1)) == 0 ) return true ; else return false ; } ///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// public static String reverse(String input) { StringBuilder str = new StringBuilder("") ; for(int i =input.length()-1 ; i >= 0 ; i-- ) { str.append(input.charAt(i)); } return str.toString() ; } /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean isPossibleTriangle(int a ,int b , int c) { if( a + b > c && c+b > a && a +c > b)return true ; else return false ; } //////////////////////////////////////////////////////////////////////////////////////////// static long xnor(long num1, long num2) { if (num1 < num2) { long temp = num1; num1 = num2; num2 = temp; } num1 = togglebit(num1); return num1 ^ num2; } static long togglebit(long n) { if (n == 0) return 1; long i = n; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return i ^ n; } /////////////////////////////////////////////////////////////////////////////////////////////// public static int xorOfFirstN(int n) { if( n % 4 ==0)return n ; else if( n % 4 == 1)return 1 ; else if( n % 4 == 2)return n+1 ; else return 0 ; } ////////////////////////////////////////////////////////////////////////////////////////////// public static int gcd(int a, int b ) { if(b==0)return a ; else return gcd(b,a%b) ; } public static long gcd(long a, long b ) { if(b==0)return a ; else return gcd(b,a%b) ; } //////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c , int d ) { int temp = lcm(a,b , c) ; int ans = lcm(temp ,d ) ; return ans ; } /////////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c ) { int temp = lcm(a,b) ; int ans = lcm(temp ,c) ; return ans ; } //////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a , int b ) { int gc = gcd(a,b); return (a/gc)*b ; } public static long lcm(long a , long b ) { long gc = gcd(a,b); return (a/gc)*b; } /////////////////////////////////////////////////////////////////////////////////////////// static boolean isPrime(long n) { if(n==1) { return false ; } boolean ans = true ; for(long i = 2L; i*i <= n ;i++) { if(n% i ==0) { ans = false ;break ; } } return ans ; } static boolean isPrime(int n) { if(n==1) { return false ; } boolean ans = true ; for(int i = 2; i*i <= n ;i++) { if(n% i ==0) { ans = false ;break ; } } return ans ; } /////////////////////////////////////////////////////////////////////////// static int sieve = 1000000 ; static boolean[] prime = new boolean[sieve + 1] ; public static void sieveOfEratosthenes() { // FALSE == prime // TRUE == COMPOSITE // FALSE== 1 // time complexity = 0(NlogLogN)== o(N) // gives prime nos bw 1 to N for(int i = 4; i<= sieve ; i++) { prime[i] = true ; i++ ; } for(int p = 3; p*p <= sieve; p++) { if(prime[p] == false) { for(int i = p*p; i <= sieve; i += p) prime[i] = true; } p++ ; } } /////////////////////////////////////////////////////////////////////////////////// public static void sortD(int[] arr , int s , int e) { sort(arr ,s , e) ; int i =s ; int j = e ; while( i < j) { int temp = arr[i] ; arr[i] =arr[j] ; arr[j] = temp ; i++ ; j-- ; } return ; } ///////////////////////////////////////////////////////////////////////////////////////// public static long countSubarraysSumToK(long[] arr ,long sum ) { HashMap<Long,Long> map = new HashMap<>() ; int n = arr.length ; long prefixsum = 0 ; long count = 0L ; for(int i = 0; i < n ; i++) { prefixsum = prefixsum + arr[i] ; if(sum == prefixsum)count = count+1 ; if(map.containsKey(prefixsum -sum)) { count = count + map.get(prefixsum -sum) ; } if(map.containsKey(prefixsum )) { map.put(prefixsum , map.get(prefixsum) +1 ); } else{ map.put(prefixsum , 1L ); } } return count ; } /////////////////////////////////////////////////////////////////////////////////////////////// // KMP ALGORITHM : TIME COMPL:O(N+M) // FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING //RETURN THE ARRAYLIST OF INDEXES // IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING public static ArrayList<Integer> kmpAlgorithm(String str , String pat) { ArrayList<Integer> list =new ArrayList<>(); int n = str.length() ; int m = pat.length() ; String q = pat + "#" + str ; int[] lps =new int[n+m+1] ; longestPefixSuffix(lps, q,(n+m+1)) ; for(int i =m+1 ; i < (n+m+1) ; i++ ) { if(lps[i] == m) { list.add(i-2*m) ; } } return list ; } public static void longestPefixSuffix(int[] lps ,String str , int n) { lps[0] = 0 ; for(int i = 1 ; i<= n-1; i++) { int l = lps[i-1] ; while( l > 0 && str.charAt(i) != str.charAt(l)) { l = lps[l-1] ; } if(str.charAt(i) == str.charAt(l)) { l++ ; } lps[i] = l ; } } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n // TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1 // or n and the no will be coprime in nature //time : O(n*(log(logn))) public static void eulerTotientFunction(int[] arr ,int n ) { for(int i = 1; i <= n ;i++)arr[i] =i ; for(int i= 2 ; i<= n ;i++) { if(arr[i] == i) { arr[i] =i-1 ; for(int j =2*i ; j<= n ; j+= i ) { arr[j] = (arr[j]*(i-1))/i ; } } } return ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long nCr(int n,int k) { long ans=1L; k=k>n-k?n-k:k; int j=1; for(;j<=k;j++,n--) { if(n%j==0) { ans*=n/j; }else if(ans%j==0) { ans=ans/j*n; }else { ans=(ans*n)/j; } } return ans; } /////////////////////////////////////////////////////////////////////////////////////////// public static ArrayList<Integer> allFactors(int n) { ArrayList<Integer> list = new ArrayList<>() ; for(int i = 1; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) { list.add(i) ; } else{ list.add(i) ; list.add(n/i) ; } } } return list ; } public static ArrayList<Long> allFactors(long n) { ArrayList<Long> list = new ArrayList<>() ; for(long i = 1L; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) { list.add(i) ; } else{ list.add(i) ; list.add(n/i) ; } } } return list ; } //////////////////////////////////////////////////////////////////////////////////////////////////// static final int MAXN = 1000001; static int spf[] = new int[MAXN]; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } static ArrayList<Integer> getPrimeFactorization(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() public static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } ///////////////////////////////////////////////////////////////////////////////////////// public static long knapsack(int[] weight,long value[],int maxWeight){ int n= value.length ; //dp[i] stores the profit with KnapSack capacity "i" long []dp = new long[maxWeight+1]; //initially profit with 0 to W KnapSack capacity is 0 Arrays.fill(dp, 0); // iterate through all items for(int i=0; i < n; i++) //traverse dp array from right to left for(int j = maxWeight; j >= weight[i]; j--) dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]); /*above line finds out maximum of dp[j](excluding ith element value) and val[i] + dp[j-wt[i]] (including ith element value and the profit with "KnapSack capacity - ith element weight") */ return dp[maxWeight]; } /////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// // to return max sum of any subarray in given array public static long kadanesAlgorithm(long[] arr) { if(arr.length == 0)return 0 ; long[] dp = new long[arr.length] ; dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) { dp[i] = dp[i-1] + arr[i] ; } else{ dp[i] = arr[i] ; } if(dp[i] > max)max = dp[i] ; } return max ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long kadanesAlgorithm(int[] arr) { if(arr.length == 0)return 0 ; long[] dp = new long[arr.length] ; dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) { dp[i] = dp[i-1] + arr[i] ; } else{ dp[i] = arr[i] ; } if(dp[i] > max)max = dp[i] ; } return max ; } /////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING // JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive //Function for swapping the characters at position I with character at position j public static String swapString(String a, int i, int j) { char[] b =a.toCharArray(); char ch; ch = b[i]; b[i] = b[j]; b[j] = ch; return String.valueOf(b); } //Function for generating different permutations of the string public static void generatePermutation(String str, int start, int end) { //Prints the permutations if (start == end-1) System.out.println(str); else { for (int i = start; i < end; i++) { //Swapping the string by fixing a character str = swapString(str,start,i); //Recursively calling function generatePermutation() for rest of the characters generatePermutation(str,start+1,end); //Backtracking and swapping the characters again. str = swapString(str,start,i); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// public static long factMod(long n, long mod) { if (n <= 1) return 1; long ans = 1; for (int i = 1; i <= n; i++) { ans = (ans * i) % mod; } return ans; } ///////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static long power(int a ,int b) { //time comp : o(logn) long x = (long)(a) ; long n = (long)(b) ; if(n==0)return 1 ; if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1) { ans = ans *x ; } n = n/2L ; x = x*x ; } return ans ; } public static long power(long a ,long b) { //time comp : o(logn) long x = (a) ; long n = (b) ; if(n==0)return 1L ; if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1) { ans = ans *x ; } n = n/2L ; x = x*x ; } return ans ; } //////////////////////////////////////////////////////////////////////////////////////////////////// public static long powerMod(long x, long n, long mod) { //time comp : o(logn) if(n==0)return 1L ; if(n==1)return x; long ans = 1; while (n > 0) { if (n % 2 == 1) ans = (ans * x) % mod; x = (x * x) % mod; n /= 2; } return ans; } ////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// /* lowerBound - finds largest element equal or less than value paased upperBound - finds smallest element equal or more than value passed if not present return -1; */ public static long lowerBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static int lowerBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static long upperBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } public static int upperBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } ////////////////////////////////////////////////////////////////////////////////////////// public static void printArray(int[] arr , int si ,int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } } public static void printArrayln(int[] arr , int si ,int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } out.println() ; } public static void printLArray(long[] arr , int si , int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } } public static void printLArrayln(long[] arr , int si , int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } out.println() ; } public static void printtwodArray(int[][] ans) { for(int i = 0; i< ans.length ; i++) { for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" "); out.println() ; } out.println() ; } static long modPow(long a, long x, long p) { //calculates a^x mod p in logarithmic time. a = a % p ; if(a == 0)return 0L ; long res = 1L; while(x > 0) { if( x % 2 != 0) { res = (res * a) % p; } a = (a * a) % p; x =x/2; } return res; } static long modInverse(long a, long p) { //calculates the modular multiplicative of a mod p. //(assuming p is prime). return modPow(a, p-2, p); } static long[] factorial = new long[1000001] ; static void modfac(long mod) { factorial[0]=1L ; factorial[1]=1L ; for(int i = 2; i<= 1000000 ;i++) { factorial[i] = factorial[i-1] *(long)(i) ; factorial[i] = factorial[i] % mod ; } } static long modBinomial(long n, long r, long p) { // calculates C(n,r) mod p (assuming p is prime). if(n < r) return 0L ; long num = factorial[(int)(n)] ; long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) % p ; long ans = num*(modInverse(den,p)) ; ans = ans % p ; return ans ; } static void update(int val , long[] bit ,int n) { for( ; val <= n ; val += (val &(-val)) ) { bit[val]++ ; } } static long query(int val , long[] bit , int n) { long ans = 0L; for( ; val >=1 ; val-=(val&(-val)) )ans += bit[val]; return ans ; } static int countSetBits(long n) { int count = 0; while (n > 0) { n = (n) & (n - 1L); count++; } return count; } static int abs(int x) { if(x < 0)x = -1*x ; return x ; } static long abs(long x) { if(x < 0)x = -1L*x ; return x ; } //////////////////////////////////////////////////////////////////////////////////////////////// static void p(int val) { out.print(val) ; } static void p() { out.print(" ") ; } static void pln(int val) { out.println(val) ; } static void pln() { out.println() ; } static void p(long val) { out.print(val) ; } static void pln(long val) { out.println(val) ; } //////////////////////////////////////////////////////////////////////////////////////////// // calculate total no of nos greater than or equal to key in sorted array arr static int bs(int[] arr, int s ,int e ,int key) { if( s> e)return 0 ; int mid = (s+e)/2 ; if(arr[mid] <key) { return bs(arr ,mid+1,e , key) ; } else{ return bs(arr ,s ,mid-1, key) + e-mid+1; } } // static ArrayList<Integer>[] adj ; // static int mod= 1000000007 ; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// public static void solve() { FastReader scn = new FastReader() ; //Scanner scn = new Scanner(System.in); //int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ; // product of first 11 prime nos is greater than 10 ^ 12; //sieve() ; //ArrayList<Integer> arr[] = new ArrayList[n] ; ArrayList<Integer> list = new ArrayList<>() ; ArrayList<Long> lista = new ArrayList<>() ; ArrayList<Long> listb = new ArrayList<>() ; // ArrayList<Integer> lista = new ArrayList<>() ; // ArrayList<Integer> listb = new ArrayList<>() ; //ArrayList<String> lists = new ArrayList<>() ; HashMap<Integer,ArrayList<Pair>> map = new HashMap<>() ; //HashMap<Long,Long> map = new HashMap<>() ; HashMap<Integer,Integer> mapx = new HashMap<>() ; HashMap<Integer,Integer> mapy = new HashMap<>() ; //HashMap<String,Integer> maps = new HashMap<>() ; //HashMap<Integer,Boolean> mapb = new HashMap<>() ; //HashMap<Point,Integer> point = new HashMap<>() ; Set<Integer> set = new HashSet<>() ; Set<Integer> setx = new HashSet<>() ; Set<Integer> sety = new HashSet<>() ; StringBuilder sb =new StringBuilder("") ; //Collections.sort(list); //if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ; //else map.put(arr[i],1) ; // if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ; // else map.put(temp,1) ; //int bit =Integer.bitCount(n); // gives total no of set bits in n; // Arrays.sort(arr, new Comparator<Pair>() { // @Override // public int compare(Pair a, Pair b) { // if (a.first != b.first) { // return a.first - b.first; // for increasing order of first // } // return a.second - b.second ; //if first is same then sort on second basis // } // }); int testcase = 1; //testcase = scn.nextInt() ; for(int testcases =1 ; testcases <= testcase ;testcases++) { //if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ; //if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ; //adj = new ArrayList[n] ; // for(int i = 0; i< n; i++) // { // adj[i] = new ArrayList<Integer>(); // } // long n = scn.nextLong() ; //String s = scn.next() ; int n= scn.nextInt() ; int[] arr= new int[n] ; for(int i=0; i < n;i++) { arr[i]= scn.nextInt(); } for(int r= 0 ; r < n ;r++) { int sum = 0 ; for(int l =r ;l>= 0 ;l--) { sum = sum + arr[l] ; if(map.containsKey(sum)) { map.get(sum).add(new Pair(l,r)) ; } else{ map.put(sum,new ArrayList<Pair>()); map.get(sum).add(new Pair(l,r)) ; } } } ArrayList<Pair> ans = null ; int bestcount = 0 ; for(int x : map.keySet()) { ArrayList<Pair> curr = map.get(x) ; ArrayList<Pair> now = new ArrayList<Pair>() ; int r=-1 ; int count = 0 ; for(Pair seg : curr) { if(seg.first > r) { count++ ; now.add(seg) ; r= seg.second ; } } if(count > bestcount) { ans = now ; bestcount = count ; } } pln(bestcount) ; if(bestcount >0) { for(Pair x : ans) { out.println((x.first+1) +" " +( x.second+1)) ; } } //out.println(ans) ; //out.println(ans+" "+in) ; //out.println("Case #" + testcases + ": " + ans ) ; //out.println("@") ; set.clear() ; sb.delete(0 , sb.length()) ; list.clear() ;lista.clear() ;listb.clear() ; map.clear() ; mapx.clear() ; mapy.clear() ; setx.clear() ;sety.clear() ; } // test case end loop out.flush() ; } // solve fn ends public static void main (String[] args) throws java.lang.Exception { solve() ; } } class Pair { int first ; int second ; public Pair(int l , int r) { first = l ;second = r ; } @Override public String toString() { String ans = "" ; ans += this.first ; ans += " "; ans += this.second ; return ans ; } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; public class A { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] a = new int[n]; for(int i=0;i < n;i++) a[i] = scan.nextInt(); Arrays.sort(a); int min = a[0]; for(int i=1;i < n;i++) { if(a[i] > min) { System.out.println(a[i]); return; } } System.out.println("NO"); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class B { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // int n = Integer.parseInt(bf.readLine()); StringTokenizer st = new StringTokenizer(bf.readLine()); // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); StringBuilder ans1 = new StringBuilder(); StringBuilder ans2 = new StringBuilder(); for(int i=0; i<2229; i++) ans1.append('5'); ans1.append('6'); for(int i=0; i<2230; i++) ans2.append('4'); out.println(ans1.toString()); out.println(ans2.toString()); out.close(); System.exit(0); } }
constant
1028_B. Unnatural Conditions
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { (new Main()).solve(); } public Main() { } MyReader in = new MyReader(); PrintWriter out = new PrintWriter(System.out); void solve() throws IOException { // BufferedReader in = new BufferedReader(new // InputStreamReader(System.in)); // Scanner in = new Scanner(System.in); //Scanner in = new Scanner(new FileReader("forbidden-triples.in")); //PrintWriter out = new PrintWriter("forbidden-triples.out"); long n = in.nextLong(); long k = in.nextLong(); long sum = 1; long count = 0; long index = k - 1; long[] delta = {1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1, 0}; while (index > 0) { if (index + sum <= n) { for (int d = 0; d < delta.length; d++) { if (delta[d] < index) { long m = (2 * index - delta[d])*(delta[d] + 1)/2; if (m + sum <= n) { sum += m; index -= (delta[d] + 1); count += (delta[d] + 1); } } } } else { index = n - sum; } } if (sum == n) { out.println(count); } else { out.println(-1); } out.close(); } }; class MyReader { private BufferedReader in; String[] parsed; int index = 0; public MyReader() { in = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt() throws NumberFormatException, IOException { if (parsed == null || parsed.length == index) { read(); } return Integer.parseInt(parsed[index++]); } public long nextLong() throws NumberFormatException, IOException { if (parsed == null || parsed.length == index) { read(); } return Long.parseLong(parsed[index++]); } public String nextString() throws IOException { if (parsed == null || parsed.length == index) { read(); } return parsed[index++]; } private void read() throws IOException { parsed = in.readLine().split(" "); index = 0; } public String readLine() throws IOException { return in.readLine(); } };
logn
287_B. Pipeline
CODEFORCES
import java.util.Scanner; public class C { static long n = 0; static void R (long a,long b){ n += a/b; a = a%b; if(a==0) return; R(b,a); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); long a = sc.nextLong(); long b = sc.nextLong(); R(a,b); System.out.println(n); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CF1197B { public static void main(String[] args) { FastReader input = new FastReader(); int n = input.nextInt(); int[] arr = new int[n]; int max = 0; int maxIndex = 0; for(int i = 0;i < n;i++){ arr[i] = input.nextInt(); if(arr[i] > max){ max = arr[i]; maxIndex = i; } } int j = maxIndex - 1; int k = maxIndex + 1; while (j >= 0 && k < n){ if(arr[j] > arr[k]){ if(arr[j] < max){ max = arr[j]; j--; } else { System.out.println("NO"); return; } } else{ if(arr[k] < max){ max = arr[k]; k++; } else{ System.out.println("NO"); return; } } } if(j >= 0){ while (j >= 0){ if(arr[j] < max){ max = arr[j]; j--; } else{ System.out.println("NO"); return; } } } if(k < n){ while (k < n){ if(arr[k] < max){ max = arr[k]; k++; } else{ System.out.println("NO"); return; } } } if(j == -1 && k == n){ System.out.println("YES"); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
linear
1197_B. Pillars
CODEFORCES
import java.util.Scanner; public class D { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][]a = new int[n][n]; for (int i = 1; i <= m; i++) { int v1 = sc.nextInt(); int v2 = sc.nextInt(); v1--; v2--; a[v1][v2] = a[v2][v1] = 1; } long[][]dp = new long[1 << n][n]; for (int i = 0; i < n; i++) { dp[1 << i][i] = 1; } for (int mask = 0; mask < (1 << n); mask++) { if (Integer.bitCount(mask) > 1) { for (int i = 0; i < n; i++) { if (i==Integer.numberOfTrailingZeros(mask)) continue; if ((mask & (1 << i)) != 0) { for (int j = 0; j < n; j++) { if ((mask & (1 << j)) != 0 && a[j][i]==1) { dp[mask][i] += dp[(mask ^ (1 << i))][j]; } } } } } } long ans = 0; for (int mask = 0; mask < (1 << n); mask++) { if (Integer.bitCount(mask) >= 3) { int t = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if (a[t][i]==1) ans += dp[mask][i]; } } } ans /= 2; System.out.println(ans); } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class loser { static class InputReader { public BufferedReader br; public StringTokenizer token; public InputReader(InputStream stream) { br=new BufferedReader(new InputStreamReader(stream),32768); token=null; } public String next() { while(token==null || !token.hasMoreTokens()) { try { token=new StringTokenizer(br.readLine()); } catch(IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } static class card{ long a; int i; public card(long a,int i) { this.a=a; this.i=i; } } static class sort implements Comparator<pair> { public int compare(pair o1,pair o2) { if(o1.a!=o2.a) return (int)(o1.a-o2.a); else return (int)(o1.b-o2.b); } } static void shuffle(long a[]) { List<Long> l=new ArrayList<>(); for(int i=0;i<a.length;i++) l.add(a[i]); Collections.shuffle(l); for(int i=0;i<a.length;i++) a[i]=l.get(i); } /*static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); }*/ /*static boolean valid(int i,int j) { if(i<4 && i>=0 && j<4 && j>=0) return true; else return false; }*/ static class pair{ int a,b; public pair(int a,int b) { this.a=a; this.b=b; } } public static void main(String[] args) { InputReader sc=new InputReader(System.in); int k=sc.nextInt(); int n=sc.nextInt(); int s=sc.nextInt(); int p=sc.nextInt(); long d=(long)Math.ceil((double)n/s); if(d==0) d=1; d=k*d; long ans=(long)Math.ceil((double)d/p); System.out.println(ans); } }
constant
965_A. Paper Airplanes
CODEFORCES
import java.io.*; import java.util.Locale; import java.util.StringTokenizer; public class B implements Runnable { private static final boolean ONLINE_JUDGE = true;//System.getProperty("ONLINE_JUDGE") != null; private BufferedReader in; private PrintWriter out; private StringTokenizer tok = new StringTokenizer(""); private void init() throws FileNotFoundException { Locale.setDefault(Locale.US); String fileName = ""; if (ONLINE_JUDGE && fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { if (fileName.isEmpty()) { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } } String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } double readDouble() { return Double.parseDouble(readString()); } int[] readIntArray(int size) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = readInt(); } return a; } public static void main(String[] args) { //new Thread(null, new _Solution(), "", 128 * (1L << 20)).start(); new B().run(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } @Override public void run() { try { timeBegin = System.currentTimeMillis(); init(); int n = readInt(); int[] rect1 = solve1(n); int[] rect2 = solve2(n, rect1); out.printf("! %s %s %s %s %s %s %s %s\n", rect1[0], rect1[1], rect1[2], rect1[3], rect2[0], rect2[1], rect2[2], rect2[3]); out.flush(); out.close(); time(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } int ask(int x1, int y1, int x2, int y2) { out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2); out.flush(); return readInt(); } int ask(int x1, int y1, int x2, int y2, int[] rect) { out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2); out.flush(); int res = readInt(); if (rect[0] >= x1 && rect[2] <= x2 && rect[1] >= y1 && rect[3] <= y2) { res--; } return res; } int[] dropTopAndLeft1(int x2, int y2) { int x1 = x2, y1 = y2; int left = 1, right = x2; while (left <= right) { int mid = (left + right) >> 1; int count = ask(mid, 1, x2, y2); if (count >= 1) { x1 = mid; left = mid + 1; } if (count == 0) { right = mid - 1; } } left = 1; right = y2; while (left <= right) { int mid = (left + right) >> 1; int count = ask(x1, mid, x2, y2); if (count >= 1) { y1 = mid; left = mid + 1; } if (count == 0) { right = mid - 1; } } return new int[]{x1, y1, x2, y2}; } private int[] solve1(int n) { int x = -1; int left = 1, right = n; while (left <= right) { int mid = (left + right) >> 1; int count = ask(1, 1, mid, n); if (count >= 1) { x = mid; right = mid - 1; } if (count == 0) { left = mid + 1; } } left = 1; right = n; int y = -1; while (left <= right) { int mid = (left + right) >> 1; int count = ask(1, 1, x, mid); if (count >= 1) { y = mid; right = mid - 1; } if (count == 0) { left = mid + 1; } } return dropTopAndLeft1(x, y); } private int[] solve2(int n, int[] rect) { int x = -1; int left = 1, right = n; while (left <= right) { int mid = (left + right) >> 1; int count = ask(mid, 1, n, n, rect); if (count >= 1) { x = mid; left = mid + 1; } if (count == 0) { right = mid - 1; } } left = 1; right = n; int y = -1; while (left <= right) { int mid = (left + right) >> 1; int count = ask(x, mid, n, n, rect); if (count >= 1) { y = mid; left = mid + 1; } if (count == 0) { right = mid - 1; } } return dropTopAndLeft2(x, y, n, rect); } int[] dropTopAndLeft2(int x1, int y1, int n, int[] rect) { int x2 = x1, y2 = y1; int left = x1, right = n; while (left <= right) { int mid = (left + right) >> 1; int count = ask(x1, y1, mid, n, rect); if (count >= 1) { x2 = mid; right = mid - 1; } if (count == 0) { left = mid + 1; } } left = y1; right = n; while (left <= right) { int mid = (left + right) >> 1; int count = ask(x1, y1, x2, mid, rect); if (count == 1) { y2 = mid; right = mid - 1; } if (count == 0) { left = mid + 1; } } return new int[]{x1, y1, x2, y2}; } }
logn
713_B. Searching Rectangles
CODEFORCES
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.*; public class CFContest { public static void main(String[] args) throws Exception { boolean local = System.getProperty("ONLINE_JUDGE") == null; boolean async = true; Charset charset = Charset.forName("ascii"); FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset); Task task = new Task(io, new Debug(local)); if (async) { Thread t = new Thread(null, task, "dalt", 1 << 27); t.setPriority(Thread.MAX_PRIORITY); t.start(); t.join(); } else { task.run(); } if (local) { io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M"); } io.flush(); } public static class Task implements Runnable { final FastIO io; final Debug debug; int inf = (int) 1e8; long lInf = (long) 1e18; public Task(FastIO io, Debug debug) { this.io = io; this.debug = debug; } @Override public void run() { solve(); } public void solve() { int n = io.readInt(); int[] data = new int[n]; for (int i = 0; i < n; i++) { data[i] = io.readInt(); } Arrays.sort(data); boolean[] paint = new boolean[n]; int cnt = 0; for (int i = 0; i < n; i++) { if (paint[i]) { continue; } cnt++; for (int j = i; j < n; j++) { if (data[j] % data[i] == 0) { paint[j] = true; } } } io.cache.append(cnt); } } public static class FastIO { public final StringBuilder cache = new StringBuilder(20 << 20); private final InputStream is; private final OutputStream os; private final Charset charset; private StringBuilder defaultStringBuf = new StringBuilder(1 << 8); private byte[] buf = new byte[1 << 20]; private int bufLen; private int bufOffset; private int next; public FastIO(InputStream is, OutputStream os, Charset charset) { this.is = is; this.os = os; this.charset = charset; } public FastIO(InputStream is, OutputStream os) { this(is, os, Charset.forName("ascii")); } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public long readLong() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } long val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public double readDouble() { boolean sign = true; skipBlank(); if (next == '+' || next == '-') { sign = next == '+'; next = read(); } long val = 0; while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } if (next != '.') { return sign ? val : -val; } next = read(); long radix = 1; long point = 0; while (next >= '0' && next <= '9') { point = point * 10 + next - '0'; radix = radix * 10; next = read(); } double result = val + (double) point / radix; return sign ? result : -result; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } public int readLine(char[] data, int offset) { int originalOffset = offset; while (next != -1 && next != '\n') { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(byte[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (byte) next; next = read(); } return offset - originalOffset; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } public void flush() { try { os.write(cache.toString().getBytes(charset)); os.flush(); cache.setLength(0); } catch (IOException e) { throw new RuntimeException(e); } } public boolean hasMore() { skipBlank(); return next != -1; } } public static class Debug { private boolean allowDebug; public Debug(boolean allowDebug) { this.allowDebug = allowDebug; } public void assertTrue(boolean flag) { if (!allowDebug) { return; } if (!flag) { fail(); } } public void fail() { throw new RuntimeException(); } public void assertFalse(boolean flag) { if (!allowDebug) { return; } if (flag) { fail(); } } private void outputName(String name) { System.out.print(name + " = "); } public void debug(String name, int x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, long x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, double x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, int[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, long[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, double[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, Object x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, Object... x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.deepToString(x)); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import com.sun.org.apache.xpath.internal.operations.Bool; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { MyScanner scan = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = scan.nextInt(); int[] vals = new int[n]; for (int i = 0; i < n; i++) { vals[i] = scan.nextInt(); } for (int i = 0; i < n; i++) { if (solve(i, vals)) { out.print('A'); } else { out.print('B'); } } out.close(); } static HashMap<Integer, Boolean> dpResult = new HashMap<>(); private static boolean solve(int pos, int[] vals) { if (dpResult.containsKey(pos)) return dpResult.get(pos); int val = vals[pos]; boolean hasLose = false; for (int i = pos; i < vals.length; i += val) { if (i == pos) continue; if (vals[i] <= vals[pos]) continue; if (hasLose) break; if (!solve(i, vals)) { hasLose = true; } } for (int i = pos; i >= 0; i -= val) { if (i == pos) continue; if (vals[i] <= vals[pos]) continue; if (hasLose) break; if (!solve(i, vals)) { hasLose = true; } } dpResult.put(pos, hasLose); return hasLose; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
nlogn
1033_C. Permutation Game
CODEFORCES
import java.io.*; import java.util.*; public class F { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(reader.readLine()); long n = Integer.parseInt(st.nextToken()); long k = Integer.parseInt(st.nextToken()); long l = 0; long r = n; while(l <= r){ long min = (l + r) / 2; if((min * (min + 1) / 2 - (n - min) == k)){ System.out.println(n - min); return; } else if((min * (min + 1) / 2 - (n - min) > k)){ r = min - 1; } else{ l = min + 1; } } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.InputMismatchException; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { try { int n = in.readInt(); int[] x = new int[n], w = new int[n]; in.readIntArrays(x, w); int[] begin = new int[n], end = new int[n]; Arrays.setAll(begin, i -> x[i] - w[i]); Arrays.setAll(end, i -> x[i] + w[i]); int m = ArrayUtils.compress(begin, end).length; int[] dp = new int[m + 1], order = ArrayUtils.order(end); int idx = 0; for (int i = 0; i < m; i++) { if (i > 0) { dp[i] = dp[i - 1]; } while (idx < n && end[order[idx]] == i) { dp[i] = Math.max(dp[i], dp[begin[order[idx]]] + 1); idx++; } } int res = dp[m - 1]; out.printLine(res); } catch (Exception e) { e.printStackTrace(); } } } static class Sorter { private static final int INSERTION_THRESHOLD = 16; private Sorter() { } public static void sort(IntList list, IntComparator comparator) { quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1, comparator); } private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) { if (to - from < INSERTION_THRESHOLD) { insertionSort(list, from, to, comparator); return; } if (remaining == 0) { heapSort(list, from, to, comparator); return; } remaining--; int pivotIndex = (from + to) >> 1; int pivot = list.get(pivotIndex); list.swap(pivotIndex, to); int storeIndex = from; int equalIndex = to; for (int i = from; i < equalIndex; i++) { int value = comparator.compare(list.get(i), pivot); if (value < 0) { list.swap(storeIndex++, i); } else if (value == 0) { list.swap(--equalIndex, i--); } } quickSort(list, from, storeIndex - 1, remaining, comparator); for (int i = equalIndex; i <= to; i++) { list.swap(storeIndex++, i); } quickSort(list, storeIndex, to, remaining, comparator); } private static void heapSort(IntList list, int from, int to, IntComparator comparator) { for (int i = (to + from - 1) >> 1; i >= from; i--) { siftDown(list, i, to, comparator, from); } for (int i = to; i > from; i--) { list.swap(from, i); siftDown(list, from, i - 1, comparator, from); } } private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) { int value = list.get(start); while (true) { int child = ((start - delta) << 1) + 1 + delta; if (child > end) { return; } int childValue = list.get(child); if (child + 1 <= end) { int otherValue = list.get(child + 1); if (comparator.compare(otherValue, childValue) > 0) { child++; childValue = otherValue; } } if (comparator.compare(value, childValue) >= 0) { return; } list.swap(start, child); start = child; } } private static void insertionSort(IntList list, int from, int to, IntComparator comparator) { for (int i = from + 1; i <= to; i++) { int value = list.get(i); for (int j = i - 1; j >= from; j--) { if (comparator.compare(list.get(j), value) <= 0) { break; } list.swap(j, j + 1); } } } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void set(int index, int value); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public void swap(int first, int second) { if (first == second) { return; } int temp = get(first); set(first, get(second)); set(second, temp); } default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } default public IntList sort(IntComparator comparator) { Sorter.sort(this, comparator); return this; } default IntList unique() { int last = Integer.MIN_VALUE; IntList result = new IntArrayList(); int size = size(); for (int i = 0; i < size; i++) { int current = get(i); if (current != last) { result.add(current); last = current; } } return result; } default public IntList subList(final int from, final int to) { return new IntList() { private final int shift; private final int size; { if (from < 0 || from > to || to > IntList.this.size()) { throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size()); } shift = from; size = to - from; } public int size() { return size; } public int get(int at) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } return IntList.this.get(at + shift); } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int at, int value) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } IntList.this.set(at + shift, value); } public IntList compute() { return new IntArrayList(this); } }; } } static interface IntComparator { IntComparator DEFAULT = Integer::compare; int compare(int first, int second); } static class Range { public static IntList range(int from, int to) { int[] result = new int[Math.abs(from - to)]; int current = from; if (from <= to) { for (int i = 0; i < result.length; i++) { result[i] = current++; } } else { for (int i = 0; i < result.length; i++) { result[i] = current--; } } return new IntArray(result); } } static interface IntReversableCollection extends IntCollection { } 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); } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { IntIterator intIterator(); default Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } 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 void readIntArrays(int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } static interface IntCollection extends IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public int[] toArray() { int size = size(); int[] array = new int[size]; int i = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { array[i++] = it.value(); } return array; } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int index, int value) { data[index] = value; } } static class ArrayUtils { public static int[] range(int from, int to) { return Range.range(from, to).toArray(); } public static int[] createOrder(int size) { return range(0, size); } public static int[] sort(int[] array, IntComparator comparator) { return sort(array, 0, array.length, comparator); } public static int[] sort(int[] array, int from, int to, IntComparator comparator) { if (from == 0 && to == array.length) { new IntArray(array).sort(comparator); } else { new IntArray(array).subList(from, to).sort(comparator); } return array; } public static int[] order(final int[] array) { return sort(createOrder(array.length), (first, second) -> Integer.compare(array[first], array[second])); } public static int[] unique(int[] array) { return new IntArray(array).unique().toArray(); } public static int[] compress(int[]... arrays) { int totalLength = 0; for (int[] array : arrays) { totalLength += array.length; } int[] all = new int[totalLength]; int delta = 0; for (int[] array : arrays) { System.arraycopy(array, 0, all, delta, array.length); delta += array.length; } sort(all, IntComparator.DEFAULT); all = unique(all); for (int[] array : arrays) { for (int i = 0; i < array.length; i++) { array[i] = Arrays.binarySearch(all, array[i]); } } return all; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static class IntArrayList extends IntAbstractStream implements IntList { private int size; private int[] data; public IntArrayList() { this(3); } public IntArrayList(int capacity) { data = new int[capacity]; } public IntArrayList(IntCollection c) { this(c.size()); addAll(c); } public IntArrayList(IntStream c) { this(); if (c instanceof IntCollection) { ensureCapacity(((IntCollection) c).size()); } addAll(c); } public IntArrayList(IntArrayList c) { size = c.size(); data = c.data.clone(); } public IntArrayList(int[] arr) { size = arr.length; data = arr.clone(); } public int size() { return size; } public int get(int at) { if (at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size); } return data[at]; } private void ensureCapacity(int capacity) { if (data.length >= capacity) { return; } capacity = Math.max(2 * data.length, capacity); data = Arrays.copyOf(data, capacity); } public void addAt(int index, int value) { ensureCapacity(size + 1); if (index > size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } data[index] = value; size++; } public void removeAt(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size - 1) { System.arraycopy(data, index + 1, data, index, size - index - 1); } size--; } public void set(int index, int value) { if (index >= size) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } data[index] = value; } public int[] toArray() { return Arrays.copyOf(data, size); } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } }
nlogn
528_B. Clique Problem
CODEFORCES
import java.io.*; import java.util.*; public class Main { static final boolean _DEBUG = false; private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(BufferedReader _br) { br = _br; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); return ""; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static MyScanner scan; static PrintWriter out; static int debugCount = 0; static void debug(String msg) { if (_DEBUG && debugCount < 200) { out.println(msg); out.flush(); debugCount++; } } public static void main (String args[]) throws IOException { // scan = new MyScanner(new BufferedReader(new FileReader("test.in"))); scan = new MyScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Main inst = new Main(); inst.execute(); out.close(); } int N, M, pow; int[] counts; int[][][] dp; void execute() { N = scan.nextInt(); M = scan.nextInt(); if (N < M) { int temp = N; N = M; M = temp; } pow = 1<<M; counts = new int[pow]; dp = new int[N][pow][pow]; for (int[][] i : dp) { for (int[] j : i) { Arrays.fill(j, -1); } } for (int i = 0; i < pow; i++) { counts[i] = Integer.bitCount(i); dp[0][i][0] = counts[i]; } int spiders = Integer.MAX_VALUE; for (int y = 0; y < N-1; y++) { for (int i = 0; i < pow; i++) { for (int j = 0; j < pow; j++) { if (dp[y][i][j] == -1) { continue; } for (int k = 0; k < pow; k++) { if (((i|(i<<1)|(i>>1)|j|k)&(pow-1))==(pow-1)) { int value = dp[y][i][j] + counts[k]; if (dp[y+1][k][i] == -1 || dp[y+1][k][i] > value) { dp[y+1][k][i] = value; } } } } } } // for (int i = 0; i < N; i++) { // System.out.println(Arrays.deepToString(dp[i])); // } for (int i = 0; i < pow; i++) { for (int j = 0; j < pow; j++) { if (dp[N-1][i][j] != -1 && ((i|(i<<1)|(i>>1)|j)&(pow-1))==(pow-1)) { spiders = Math.min(spiders, dp[N-1][i][j]); // System.out.println(spiders+" "+i+" "+j); } } } out.println((N*M)-spiders); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.util.Scanner; public class Sub { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int noOfPairs=scan.nextInt(); while(noOfPairs-->0) { int x=scan.nextInt(); int y=scan.nextInt(); int res=0; while(x!=0&&y!=0) { if(x>y) { res+=x/y; x=x%y; } else { res+=y/x; y=y%x; } } System.out.println(res); } scan.close(); } }
constant
267_A. Subtractions
CODEFORCES
import java.io.*; import java.util.*; public class cfe { static DataReader input; static int LARGE_INT = 1000000007; //static int MAXN = 300000; //static int[] len = new int[300000]; //static int[] price = new int[300000]; static final int[] BM = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 1<<17, 1<<18, 1<<19, 1<<20}; public static void main(String[] args) throws IOException { input = new DataReader(); PrintWriter out = new PrintWriter(System.out); int N = nextInt(), M = nextInt(), P = 1<<M; String x = nextStr(); int c1 = x.charAt(0) - 'a'; int[][] pair_count = new int[M][M]; for (int i=1; i<N; i++) { int c2 = x.charAt(i) - 'a'; if (c1 < c2) pair_count[c1][c2]++; else if (c1 > c2) pair_count[c2][c1]++; c1 = c2; } int[] group_count = new int[P]; for (int mask = 1; mask <P; mask++) { int j; for (j=0; j<M; j++) { if ((mask & BM[j]) > 0) break; } int nmask = mask ^ BM[j]; int val = group_count[nmask]; for (int i=0; i<j; i++) { if ((mask & BM[i]) > 0) val -= pair_count[i][j]; else val += pair_count[i][j]; } for (int i=j+1; i<M; i++) { if ((mask & BM[i]) > 0) val -= pair_count[j][i]; else val += pair_count[j][i]; } group_count[mask] = val; } // dp[k][mask] = Accumulated cost of first K positions filled, mask position 1 letters are used // dp[0][0] = 0; int[][] dp = new int[M+1][P]; // for (int mask=1; mask<P; mask++) { // each bit mask dp[0][mask] = 0; int k = Integer.bitCount(mask); // computing first k position filled. int val = LARGE_INT; for (int j=0; j<M; j++) { if ((mask & BM[j]) > 0) { int nmask = mask ^ BM[j]; val = Math.min(val, dp[k-1][nmask] + group_count[nmask]); } } dp[k][mask] = val; } //out.println(Arrays.deepToString(dp)); out.println(dp[M][P-1]); out.flush(); out.close(); } static int nextInt() throws IOException { return Integer.parseInt(input.next()); } static String nextStr() throws IOException { return input.next(); } static class DataReader { BufferedReader br; StringTokenizer st; public DataReader() throws IOException { // reading from standard in br = new BufferedReader(new InputStreamReader(System.in)); } boolean hasNext() throws IOException { while (st == null || !st.hasMoreElements()) { String line = br.readLine(); if (line == null) { // end of file return false; } st = new StringTokenizer(line); } return true; } String next() throws IOException { if (hasNext()) return st.nextToken(); else return null; } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Main m = new Main(); m.run(); m.out.close(); } void run() throws IOException { int n = nextInt(); int m = nextInt(); int k = nextInt(); long[][] r = new long[n][m - 1]; long[][] d = new long[n - 1][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { r[i][j] = nextInt(); } } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { d[i][j] = nextInt(); } } if (k % 2 != 0) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(-1+" "); } out.println(); } return; } long[][][] dp = new long[n][m][k + 1]; for (int kk = 2; kk <= k; kk += 2) for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { long ans = (long) 1e18; if (i + 1 < n) { ans = Math.min(ans, dp[i + 1][j][kk - 2] + d[i][j]*2); } if (i - 1 > -1) ans = Math.min(ans, dp[i - 1][j][kk - 2] + d[i - 1][j]*2); if (j + 1 < m) ans = Math.min(ans, dp[i][j + 1][kk - 2] + r[i][j]*2); if (j - 1 > -1) ans = Math.min(ans, dp[i][j - 1][kk - 2] + r[i][j - 1]*2); dp[i][j][kk] = ans; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(dp[i][j][k] + " "); } out.println(); } } int gcd(int a, int b) { while (a % b != 0) { int h = a % b; a = b; b = h; } return b; } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer in = new StringTokenizer(""); // pairs class pil implements Comparable<pil> { int first; long second; pil(int f, long s) { this.first = f; this.second = s; } public int compareTo(pil o) { if (first != o.first) return Integer.compare(first, o.first); return Long.compare(second, o.second); } } class pii implements Comparable<pii> { int fi; int se; pii(int f, int s) { se = s; fi = f; } public int compareTo(pii o) { if (fi != o.fi) return Integer.compare(fi, o.fi); return Integer.compare(se, o.se); } } class pis implements Comparable<pis> { int fi; String s; pis(int f, String s) { this.s = s; fi = f; } public int compareTo(pis o) { return Integer.compare(fi, o.fi); } } class vert { int to; int iter; int idx; int ed; vert(int s, int f, int zz, int gg) { to = s; iter = f; idx = zz; ed = gg; } } class pll implements Comparable<pll> { long first; long second; pll(long f, long s) { this.first = f; this.second = s; } public int compareTo(pll o) { if (first != o.first) return Long.compare(first, o.first); return Long.compare(second, o.second); } } class pli implements Comparable<pli> { long first; int second; pli(long f, int s) { this.first = f; this.second = s; } public int compareTo(pli o) { if (first != o.first) return Long.compare(first, o.first); return Integer.compare(second, o.second); } } boolean hasNext() throws IOException { if (in.hasMoreTokens()) return true; String s; while ((s = br.readLine()) != null) { in = new StringTokenizer(s); if (in.hasMoreTokens()) return true; } return false; } String nextToken() throws IOException { while (!in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.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()); } }
cubic
1517_D. Explorer Space
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.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); EKeyboardPurchase solver = new EKeyboardPurchase(); solver.solve(1, in, out); out.close(); } static class EKeyboardPurchase { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int m = in.scanInt(); int step[][] = new int[m][m]; char arr[] = in.scanString().toCharArray(); for (int i = 0; i < n - 1; i++) { step[arr[i] - 'a'][arr[i + 1] - 'a']++; step[arr[i + 1] - 'a'][arr[i] - 'a']++; } int dp[] = new int[1 << m]; Arrays.fill(dp, Integer.MAX_VALUE / 2); for (int i = 0; i < m; i++) dp[1 << i] = 0; for (int i = 0; i < (1 << m); i++) { int cost = 0; for (int j = 0; j < m; j++) { if (((i & (1 << j)) != 0)) { for (int k = 0; k < m; k++) { if (((i & (1 << k)) == 0)) { cost += step[j][k]; } } } } for (int j = 0; j < m; j++) if (((i & (1 << j)) == 0)) dp[i | (1 << j)] = Math.min(dp[i | (1 << j)], dp[i] + cost); } out.println(dp[(1 << m) - 1]); } } 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 I = 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') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } public String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder RESULT = new StringBuilder(); do { RESULT.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return RESULT.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.io.*; import java.util.*; /** * * @author Jishnu_T */ public class ReallyBigNums { private static long[] factorArray(long s) { int d=0; long n=s; long f=1; while(n>0) { n=n/10; d++; f = f*10; } long[] fact = new long[d+1]; n=s; for(int i=d;i>=0;i--) { if(f==1) fact[i] = n; else { fact[i] = n/(f-1); n = n%(f-1); f=f/10; } } int carry=0; for(int i=0;i<=d;i++) { fact[i] = fact[i]+carry; if(fact[i]>9 || (i==0 && fact[i]>0)) { fact[i] = 0; carry = 1; for(int j=i-1;j>=0;j--) { fact[j] =0; } } else { carry = 0; } } return fact; } private static long bigNumCount(long n, long s) { if(s>=n) return 0; if(s==0) return n; long[] fact = factorArray(s); long startNum = 0; int len = fact.length; long tenPow = 1; for(int i=0;i<len;i++) { startNum = startNum+tenPow*fact[i]; tenPow = tenPow*10; } return(Math.max(0,n-startNum+1)); } private static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) { FastReader r = new FastReader(); long n = r.nextLong(); long s= r.nextLong(); System.out.println(bigNumCount(n,s)); } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.*; import java.lang.*; import java.util.*; public class Solver { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); TaskC solver = new TaskC(in, out); solver.solve(); out.close(); } static class TaskC { FastReader in; PrintWriter out; public TaskC(FastReader in, PrintWriter out) { this.in = in; this.out = out; } public void solve() { solveA(); } public void solveA() { int n = in.nextInt(); int[] inputColors = in.nextIntArray(n); int colors = 0; Arrays.sort(inputColors); for (int i = 0; i < inputColors.length; i++) { if (inputColors[i] == -1) { continue; } int colorCode = inputColors[i]; boolean colorFound = false; for (int j = i; j < inputColors.length; j++) { if (inputColors[j] != -1 && inputColors[j] % colorCode == 0) { if (!colorFound) { colorFound = true; colors++; } inputColors[j] = -1; } } } out.println(colors); } public void solveB() { } public void solveC() { } public void solveD() { } public void solveE() { } public void solveF() { } public void solveG() { } public void solveH() { } } private static long gcd(long a, long b) { if (a == 0) { return b; } return gcd(b % a, a); } private static long lcm(long a, long b) { return (a * b) / gcd(a, b); } private static int min(int a, int b) { return a < b ? a : b; } private static int max(int a, int b) { return a > b ? a : b; } private static int min(ArrayList<Integer> list) { int min = Integer.MAX_VALUE; for (int el : list) { if (el < min) { min = el; } } return min; } private static int max(ArrayList<Integer> list) { int max = Integer.MIN_VALUE; for (int el : list) { if (el > max) { max = el; } } return max; } private static int min(int[] list) { int min = Integer.MAX_VALUE; for (int el : list) { if (el < min) { min = el; } } return min; } private static int max(int[] list) { int max = Integer.MIN_VALUE; for (int el : list) { if (el > max) { max = el; } } return max; } private static void fill(int[] array, int value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } } }
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.Arrays; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); DExplorerSpace solver = new DExplorerSpace(); solver.solve(1, in, out); out.close(); } static class DExplorerSpace { int n; int m; int k; int[][] col; int[][] row; long[][][] memo; public void readInput(Scanner sc) { n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt(); col = new int[n][m - 1]; for (int i = 0; i < n; i++) for (int j = 0; j < m - 1; j++) col[i][j] = sc.nextInt(); row = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) for (int j = 0; j < m; j++) row[i][j] = sc.nextInt(); } public void solve(int testNumber, Scanner sc, PrintWriter pw) { int q = 1; while (q-- > 0) { readInput(sc); if (k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) pw.print(-1 + " "); pw.println(); } return; } memo = new long[k + 1][n][m]; for (long[][] x : memo) for (long[] y : x) Arrays.fill(y, -1); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { pw.print(2l * dp(i, j, k / 2) + " "); } pw.println(); } } } private long dp(int i, int j, int rem) { if (rem == 0) return 0; if (memo[rem][i][j] != -1) return memo[rem][i][j]; long min = (long) 1e18; if (j <= m - 2) min = Math.min(min, col[i][j] + dp(i, j + 1, rem - 1)); if (j > 0) min = Math.min(min, col[i][j - 1] + dp(i, j - 1, rem - 1)); if (i <= n - 2) min = Math.min(min, row[i][j] + dp(i + 1, j, rem - 1)); if (i > 0) min = Math.min(min, row[i - 1][j] + dp(i - 1, j, rem - 1)); return memo[rem][i][j] = min; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class P111C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int h, w; void run(){ h=sc.nextInt(); w=sc.nextInt(); solve(); } void shuffle(int[] is){ Random rand=new Random(); for(int i=is.length-1; i>=1; i--){ int j=rand.nextInt(i+1); int t=is[i]; is[i]=is[j]; is[j]=t; } } void solve(){ n=w*h; g=new long[n]; int[] dx={0, 0, -1, 1}; int[] dy={-1, 1, 0, 0}; for(int y=0; y<h; y++){ for(int x=0; x<w; x++){ for(int k=0; k<4; k++){ int x2=x+dx[k]; int y2=y+dy[k]; if(x2>=0&&x2<w&&y2>=0&&y2<h){ g[y*w+x]|=1L<<(y2*w+x2); } } } } candidate=new int[n]; xs=new Xorshift(); mds=(1L<<n)-1; mds(0, 0, 0); println((n-Long.bitCount(mds))+""); } int n; long[] g; long mds; int[] candidate; Xorshift xs; void mds(long choosed, long removed, long covered){ if(Long.bitCount(choosed)>=Long.bitCount(mds)) return; if(covered==((1L<<n)-1)){ if(Long.bitCount(choosed)<Long.bitCount(mds)) mds=choosed; return; } { long s=covered; for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); s|=(1L<<i)|g[i]; } if(s!=((1L<<n)-1)){ return; } } // int index=0; int k=-1; for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); if((covered>>>i&1)==1){ if(Long.bitCount(g[i]&~covered)==0){ mds(choosed, removed|(1L<<i), covered); return; }else if(Long.bitCount(g[i]&~covered)==1 &&(g[i]&~covered&~removed)!=0){ mds(choosed, removed|(1L<<i), covered); return; } }else{ if(Long.bitCount(g[i]&~removed)==0){ mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]); return; }else if(Long.bitCount(g[i]&~removed)==1 &&((g[i]&~removed)|(g[i]&~covered))==(g[i]&~removed)){ int j=Long.numberOfTrailingZeros(g[i]&~removed); mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered |(1L<<j)|g[j]); return; } } if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)) k=i; /* if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)){ index=0; candidate[index++]=i; k=i; }else if(Long.bitCount(g[i]&~covered)==Long.bitCount(g[k]&~covered)){ candidate[index++]=i; } */ } if(k==-1) return; // k=candidate[xs.nextInt(index)]; mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]); mds(choosed, removed|(1L<<k), covered); } class Xorshift{ int x, y, z, w; public Xorshift(){ x=123456789; y=362436069; z=521288629; w=88675123; } public Xorshift(int seed){ x=_(seed, 0); y=_(x, 1); z=_(y, 2); w=_(z, 3); } int _(int s, int i){ return 1812433253*(s^(s>>>30))+i+1; } // 32bit signed public int nextInt(){ int t=x^(x<<11); x=y; y=z; z=w; return w=w^(w>>>19)^t^(t>>>8); } // error = O(n*2^-32) public int nextInt(int n){ return (int)(n*nextDouble()); } // [0, 1) (53bit) public double nextDouble(){ int a=nextInt()>>>5, b=nextInt()>>>6; return (a*67108864.0+b)*(1.0/(1L<<53)); } } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } public static void main(String[] args){ Locale.setDefault(Locale.US); new P111C().run(); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Solution{ public static void main(String[] args) throws Exception { int n=nextInt(); int r=nextInt(); int x[]=new int[n]; double y[]=new double[n]; for(int i=0;i<n;i++) x[i]=nextInt(); for(int i=0;i<n;i++){ //(x1-x2)2+(y1-y2)2=r2 y[i]=r; for(int j=0;j<i;j++){ int d=sq(2*r)-sq(x[i]-x[j]); if(d>=0){ double y1=Math.sqrt(d)+y[j]; y[i]=Math.max(y1,y[i]); } } } for(int i=0;i<n;i++) System.out.printf("%.12g ",y[i]); } static int sq(int a){ return a*a; } static int nextInt()throws IOException{ InputStream in=System.in; int ans=0; boolean flag=true; byte b=0; while ((b>47 && b<58) || flag){ if(b>=48 && b<58){ ans=ans*10+(b-48); flag=false; } b=(byte)in.read(); } return ans; } static String next()throws Exception{ StringBuilder sb=new StringBuilder(1<<16); InputStream in=System.in; byte b=0; do{ if(!isWhiteSpace(b)) sb.append((char)b); b=(byte)in.read(); }while(!isWhiteSpace(b) || sb.length()==0); return sb.toString(); } static boolean isWhiteSpace(byte b){ char ch=(char)b; return ch=='\0' || ch==' ' || ch=='\n'; } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class AAA { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); String a=""; String b=""; for(int i=0;i<1129;i++) { a+="1"; b+="8"; } a+="9"; b+="1"; System.out.println(a); System.out.println(b); } }
constant
1028_B. Unnatural Conditions
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class TemplateBuf implements Runnable{ private void solve() throws Exception { long n = nextUnsignedLong(); out.println(n+n/2); } ///////////////////////////////////////////////// BufferedReader in; PrintWriter out; @Override public void run() { try{ in = new BufferedReader(new InputStreamReader(System.in), INPUT_BUF_SIZE); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); }catch (Exception e) { e.printStackTrace(); System.exit(1); } } final int INPUT_BUF_SIZE = 1024 * 8; final int BUF_SIZE = INPUT_BUF_SIZE; char[] buf = new char[BUF_SIZE]; int ch=-1; int charRead=-1; int charPos=-1; public char nextChar() throws IOException{ if (charPos<0 || charPos>=charRead){ charRead = in.read(buf); charPos=0; } return buf[charPos++]; } public long nextUnsignedLong() throws IOException{ while ((ch=nextChar())<'0' || ch>'9'); long num = ch-'0'; while ((ch=nextChar())>='0' && ch<='9'){ num*=10; num+=ch-'0'; } return num; } public int nextUnsignedInt() throws IOException{ return (int)nextUnsignedLong(); } public double nextDouble() throws IOException{ while (((ch=nextChar())<'0' || ch>'9') && ch!='.' && ch!='-'); char[] tmp = new char[255]; int itmp = 0; tmp[itmp++]=(char)ch; while (((ch=nextChar())>='0' && ch<='9') || ch=='.' || ch=='-'){ tmp[itmp++]=(char)ch; } return Double.parseDouble(new String(tmp,0,itmp)); } public static void main(String[] args) { new TemplateBuf().run(); } }
constant
84_A. Toy Army
CODEFORCES