src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; public class R035C { public void debug(Object... objects) { System.err.println(Arrays.deepToString(objects)); } public static final int INF = 987654321; public static final long LINF = 987654321987654321L; public static final double EPS = 1e-9; Scanner scanner; PrintWriter out; int[][] iss; public R035C() { try { this.scanner = new Scanner(new File("input.txt")); this.out = new PrintWriter("output.txt"); } catch(FileNotFoundException ex) { ex.printStackTrace(); } } class Point implements Comparable<Point> { int x, y, count; Point(int x, int y) { this.x = x; this.y = y; } public int hashCode() { return x * 17 + y; } public boolean equals(Object o) { if(!(o instanceof Point)) return false; Point that = (Point)o; return this.x == that.x && this.y == that.y; } public int compareTo(Point that) { return this.count - that.count; } public String toString() { return "(" + x + ", " + y + ":" + count + ")"; } } int[] dx = new int[] { 0, 0, -1, 1 }; int[] dy= new int[] { -1, 1, 0, 0 }; int n, m; Queue<Point> q; Point bfs() { int max = -INF; Point p = null; while(!q.isEmpty()) { Point cur = q.remove(); if(max < cur.count) { max = cur.count; p = cur; } for(int i=0; i<dx.length; i++) { int nx = cur.x + dx[i]; int ny = cur.y + dy[i]; if(nx < 0 || nx >= n) { continue; } if(ny < 0 || ny >= m) { continue; } Point np = new Point(nx, ny); if(iss[nx][ny] != 0) { continue; } np.count = cur.count+1; iss[nx][ny] = np.count; q.add(np); } } return p; } private void solve() { this.n = scanner.nextInt(); this.m = scanner.nextInt(); this.iss = new int[n][m]; int k = scanner.nextInt(); q = new PriorityQueue<Point>(); for(int i=0; i<k; i++) { int x = scanner.nextInt() - 1; int y = scanner.nextInt() - 1; Point init = new Point(x, y); init.count = 1; q.add(init); iss[x][y] = 1; } Point p = bfs(); out.println((p.x+1) + " " + (p.y+1)); } private void finish() { this.out.close(); } public static void main(String[] args) { R035C obj = new R035C(); obj.solve(); obj.finish(); } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); boolean[] isF = new boolean[n]; for (int i = 0; i < n; i++) { isF[i] = in.readCharacter() == 'f'; } long[][] mem = new long[n + 1][n + 1]; mem[n][0] = 1; for (int idx = n - 1; idx >= 0; idx--) { for (int indentLevel = 0; indentLevel < n; indentLevel++) { mem[idx + 1][indentLevel + 1] += mem[idx + 1][indentLevel]; long res = isF[idx] ? mem[idx + 1][indentLevel + 1] - mem[idx + 1][indentLevel] : mem[idx + 1][indentLevel]; mem[idx][indentLevel] = res % MiscUtils.MOD7; } } out.printLine(mem[0][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 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 char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class MiscUtils { public static final int MOD7 = (int) (1e9 + 7); } 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(long i) { writer.println(i); } } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { long n = in.nextLong(); long st = 1, en = n, ans = 0, len = 0; while (st <= en) { long mid = (st + en) / 2; long have = 0; int curLen = Long.toString(mid).length(); long bef = 0; for (int i = 1; i < curLen; i++) { long cur = 0; for (int j = 1; j <= i; j++) { cur *= 10; cur += 9; } have += i * (cur - bef); bef = cur; } have += curLen * (mid - bef); if (have < n) { ans = mid; len = have; st = mid + 1; } else en = mid - 1; } String s = Long.toString(ans + 1); for (int i = 0; i < s.length(); i++) { if (len + i + 1 == n) { out.print(s.charAt(i)); return; } } } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L; static final int INf = 1_000_000_000; static FastReader reader; static PrintWriter writer; public static void main(String[] args) { Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000); t.start(); } static class O implements Runnable { public void run() { try { magic(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } static class FastReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static int n,m,pre[][], pre_stop_and_start[][],mat[][], dp[][][]; static void magic() throws IOException { reader = new FastReader(); writer = new PrintWriter(System.out, true); n = reader.nextInt(); m = reader.nextInt(); mat = new int[n][m]; for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { mat[i][j] = reader.nextInt(); } } if(n==1) { int ans = Integer.MAX_VALUE; for(int i=0;i+1<m;++i) { ans = min(ans, abs(mat[0][i] - mat[0][i+1])); } writer.println(ans); System.exit(0); } pre = new int[n][n]; pre_stop_and_start = new int[n][n]; for(int i=0;i<n;++i) { for(int j=i+1;j<n;++j) { int min = Integer.MAX_VALUE; for(int k=0;k<m;++k) { min = min(min, abs(mat[i][k] - mat[j][k])); } pre[i][j] = pre[j][i] = min; } } for(int i=0;i<n;++i) { for(int j=0;j<n;++j) { if(j==i) { continue; } int min = Integer.MAX_VALUE; for(int k=0;k+1<m;++k) { min = min(min, abs(mat[j][k+1] - mat[i][k])); } pre_stop_and_start[i][j] = min; } } // writer.println("Pre array: "); // for(int i=0;i<n;++i) { // for(int j=0;j<n;++j) { // writer.print(pre[i][j]+" "); // } // writer.println(); // } // writer.println("Pre stop and start array: "); // for(int i=0;i<n;++i) { // for(int j=0;j<n;++j) { // if(j==i) { // writer.print("SKIP "); // } // else writer.print(pre_stop_and_start[i][j]+" "); // } // writer.println(); // } dp = new int[1<<n][n][n]; for(int i=0;i<(1<<n);++i) { for(int j=0;j<n;++j) { for(int k=0;k<n;++k) { dp[i][j][k] = -1; } } } int ans = 0; for(int i=0;i<n;++i) { ans = max(ans, f((1<<i), i, i)); } writer.println(ans); } static int f(int mask_already, int prev, int first) { if(mask_already==(1<<n) - 1) { return pre_stop_and_start[prev][first]; } if(dp[mask_already][prev][first] != -1) { return dp[mask_already][prev][first]; } int max = 0; for(int i=0;i<n;++i) { if((mask_already&(1<<i)) == 0) { max = max(max, min(pre[prev][i], f(mask_already|(1<<i), i, first))); } } return dp[mask_already][prev][first] = max; } }
np
1102_F. Elongated Matrix
CODEFORCES
// Don't place your source in a package import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner {//scanner from SecondThread BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(System.out); int T=1; for(int t=0;t<T;t++){ int n=Int();int m=Int(); int A[][]=new int[n][m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ A[i][j]=Int(); } } Sol sol=new Sol(); sol.solution(out,A); } out.flush(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Sol{ int dif[][]; int dp[][][]; public void solution(PrintWriter out,int A[][]){ int n=A.length;int m=A[0].length; int res=0; dif=new int[n][n]; for(int i=0;i<n;i++){ for(int j=i+1;j<A.length;j++){ int mn=Integer.MAX_VALUE; for(int k=0;k<m;k++){//different ordering pair mn=Math.min(mn,Math.abs(A[i][k]-A[j][k])); } dif[i][j]=mn; dif[j][i]=mn; //System.out.println(i+" "+j+" "+mn); } } int state=(1<<n)-1; dp=new int[state+5][n+1][n+1]; for(int i=0;i<dp.length;i++){ for(int j=0;j<dp[0].length;j++){ Arrays.fill(dp[i][j],-1); } } for(int i=0;i<n;i++){ res=Math.max(res,dfs(A,state^(1<<i),i,i)); } out.println(res); } public int dfs(int A[][],int state,int pre,int start){ if(state==0){ int mn=Integer.MAX_VALUE; for(int i=1;i<A[0].length;i++){ mn=Math.min(mn,Math.abs(A[start][i]-A[pre][i-1])); } return mn; } if(dp[state][pre][start]!=-1){ return dp[state][pre][start]; } int res=0; for(int i=0;i<A.length;i++){ if((state&(1<<i))!=0){ int di=dif[pre][i]; res=Math.max(res,Math.min(di,dfs(A,state^(1<<i),i,start))); } } //System.out.println(Integer.toBinaryString(state)+" "+res); dp[state][pre][start]=res; return res; } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.awt.Point; import java.io.*; import java.util.*; import static java.lang.Math.*; public class ProblemA_15 { final boolean ONLINE_JUDGE=System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok=new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in=new BufferedReader(new InputStreamReader(System.in)); out =new PrintWriter(System.out); } else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok=new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } public static void main(String[] args){ new ProblemA_15().run(); } public void run(){ try{ long t1=System.currentTimeMillis(); init(); solve(); out.close(); long t2=System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException{ int n=readInt(); int t=readInt(); Point[] a=new Point[n]; for (int i=0; i<n; i++){ a[i]=new Point(readInt(), readInt()); } int count=2; Arrays.sort(a, new Comparator<Point>(){ @Override public int compare(Point p1, Point p2) { return p1.x-p2.x; } }); for (int i=1; i<n; i++){ double li=a[i-1].x+(double)a[i-1].y/2; double ri=a[i].x-(double)a[i].y/2; if (ri-li>t){ count+=2; } if (ri-li==t){ count++; } } out.print(count); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.LinkedList; import java.util.Scanner; public class HexadecimalsTheorem { public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = in.nextInt(); LinkedList<Integer> result = new LinkedList<Integer>(); int temp0 = 1; int temp1 = 1; int temp2 = 0; result.add(0); result.add(0); result.add(0); result.add(temp0); result.add(temp1); if (num == 2) { System.out.println(0 + " " + 1 + " " + 1); } else if (num == 0) { System.out.println(0 + " " + 0 + " " + 0); } else { while (temp2 < num) { temp2 = temp1 + temp0; result.add(temp2); temp0 = temp1; temp1 = temp2; } int length = result.size(); System.out.println(result.get(length - 5) + " " + result.get(length - 4) + " " + result.get(length - 2)); } } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.util.* ; import java.io.* ; public class PythonIndentation { public static void main(String args[]) { Scanner in = new Scanner(System.in) ; int n = in.nextInt() ; boolean[] lst = new boolean[n] ; for(int i=0;i<n;i++) { lst[i] = (in.next().equals("s"))?false:true ; } System.out.println(dp(lst)) ; } static void arrayPrinter(int[][] dp) { System.out.println(":::") ; for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { System.out.print(dp[i][j]+" ") ; } System.out.println() ; } } static int dp(boolean[] lst) {//false in lst means an "s" (simple statement), and true a "f"(for loop) int[][] dp = new int[2][lst.length] ; dp[0][0] = 1 ; for(int i=1;i<lst.length;i++) { // arrayPrinter(dp) ; for(int j=0;j<lst.length;j++) { if(lst[i-1])//(i-1)st statement is a for loop { if(j==0) dp[i%2][j] = 0 ; else dp[i%2][j] = dp[(i-1)%2][j-1] ; } else//i-1 st statement is a simple statement { if(j==0) { int temp = 0 ; for(int k=0;k<lst.length;k++) temp = (temp+dp[(i-1)%2][k])%1000000007 ; dp[i%2][j] = temp ; } else dp[i%2][j] = (dp[i%2][j-1]-dp[(i-1)%2][j-1])%1000000007 ; } } } int ans = 0 ; for(int i=0;i<lst.length;i++) { ans = (ans + dp[(lst.length-1)%2][i])%1000000007 ; } if(ans<0) ans = ans + 1000000007 ; // arrayPrinter(dp) ; return ans ; } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); if(n%2==1) { System.out.println("NO"); continue; } // squares of 2 int num=n/2; int root = (int)Math.sqrt(num); if(root*root==num) { System.out.println("YES"); continue; } // squares of 4 if(n%4!=0) { System.out.println("NO"); continue; } num = n/4; root = (int) Math.sqrt(num); if(root*root==num) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.LinkedList; import java.util.StringTokenizer; public class GeorgeAndInterestingGraph { public static void main(String[] args) { MyScanner sc = new MyScanner(); int N = sc.nextInt(); int M = sc.nextInt(); int[] edgeFrom = new int[M]; int[] edgeTo = new int[M]; for (int i = 0; i < M; i++) { edgeFrom[i] = sc.nextInt(); edgeTo[i] = sc.nextInt(); } int best = Integer.MAX_VALUE; boolean[][] adjMat = makeAdjMat(N, edgeFrom, edgeTo); for (int i = 0; i < N; i++) { boolean[][] mat = copyOfArray2d(adjMat); best = Math.min(best, count(mat, M, i)); } System.out.println(best); } public static boolean[][] copyOfArray2d(boolean[][] arr) { int N = arr.length; int M = arr[0].length; boolean[][] copy = new boolean[N][M]; for (int i = 0; i < N; i++) { System.arraycopy(arr[i], 0, copy[i], 0, M); } return copy; } public static int count(boolean[][] mat, int M, int center) { // int N = mat.length; // int M = mat[0].length; // // int centerConnect = (mat[center][center]) ? 0 : 1; // for (int i = 0; i < N; i++) { // if (i != center) { // if (!mat[i][center]) { // centerConnect++; // } // if (!mat[center][i]) { // centerConnect++; // } // } // mat[i][center] = false; // mat[center][i] = false; // } // // int[][] adjMat = new int[2 * N + 2][2 * N + 2]; // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) { // int idx = N + j; // adjMat[i][idx] = (mat[i][j]) ? 1 : 0; // } // } // int s = 2 * N; // int t = 2 * N + 1; // for (int i = 0; i < N; i++) { // adjMat[s][i] = 1; // } // for (int i = N; i < 2 * N; i++) { // adjMat[i][t] = 1; // } // // int matches = fordFulkerson(adjMat, s, t); // // return centerConnect + matches; int N = mat.length; // int M = mat[0].length; int cntWithI = (mat[center][center]) ? 1 : 0; for (int i = 0; i < N; i++) { if (i != center) { if (mat[i][center]) { cntWithI++; } if (mat[center][i]) { cntWithI++; } } mat[i][center] = false; mat[center][i] = false; } int other = M - cntWithI; // int centerConnect = (mat[center][center]) ? 0 : 1; // // for (int i = 0; i < N; i++) { // if (i != center) { // if (!mat[i][center]) { // centerConnect++; // } // if (!mat[center][i]) { // centerConnect++; // } // } // mat[i][center] = false; // mat[center][i] = false; // } int matches = bipartiteMatching(mat); return (2 * N - 1 - cntWithI + other - matches + N - 1 - matches); // return (centerConnect + N - 1 - matches); } public static boolean[][] makeAdjMat(int N, int[] edgeFrom, int[] edgeTo) { boolean[][] mat = new boolean[N][N]; for (int i = 0; i < edgeFrom.length; i++) { int from = edgeFrom[i] - 1; int to = edgeTo[i] - 1; mat[from][to] = true; } return mat; } /** * Returns true if there is a path from the source 's' to the sink 't' in the residual graph. * Also fills parent[] to store the path. * See here for more info: http://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ */ public static boolean fordFulkersonHelper(int[][] resid, int s, int t, int[] parent) { int V = resid.length; boolean[] visited = new boolean[V]; LinkedList<Integer> q = new LinkedList<Integer>(); q.push(s); visited[s] = true; parent[s] = -1; while (!q.isEmpty()) { int u = q.pop(); for (int v = 0; v < V; v++) { if (!visited[v] && resid[u][v] > 0) { q.push(v); parent[v] = u; visited[v] = true; } } } return visited[t]; } /** * Returns the maximum flow from 's' to 't' in the given graph. * See here for more info: http://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ */ public static int fordFulkerson(int[][] graph, int s, int t) { int V = graph.length; int[][] resid = new int[V][V]; int[] parent = new int[V]; int maxFlow = 0; for (int u = 0; u < V; u++) { for (int v = 0; v < V; v++) { resid[u][v] = graph[u][v]; } } while (fordFulkersonHelper(resid, s, t, parent)) { int pathFlow = Integer.MAX_VALUE; for (int v = t; v != s; v = parent[v]) { int u = parent[v]; pathFlow = Math.min(pathFlow, resid[u][v]); } for (int v = t; v != s; v = parent[v]) { int u = parent[v]; resid[u][v] -= pathFlow; resid[v][u] += pathFlow; } maxFlow += pathFlow; } return maxFlow; } /** * Returns true if a matching for vertex 'u' is possible. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static boolean bipartiteMatchingHelper(boolean[][] bpGraph, int u, boolean[] seen, int[] matchR) { int N = bpGraph[0].length; for (int v = 0; v < N; v++) { if (bpGraph[u][v] && !seen[v]) { seen[v] = true; if (matchR[v] < 0 || bipartiteMatchingHelper(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchIJ, int[] matchJI) { int ans = bipartiteMatching(bpGraph, matchJI); for (int i = 0; i < matchJI.length; i++) { matchIJ[i] = -1; } for (int j = 0; j < matchJI.length; j++) { int i = matchJI[j]; if (i >= 0) { matchIJ[i] = j; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchJI) { int M = bpGraph.length; int N = bpGraph[0].length; for (int i = 0; i < N; i++) { matchJI[i] = -1; } int ans = 0; for (int u = 0; u < M; u++) { boolean[] seen = new boolean[N]; if (bipartiteMatchingHelper(bpGraph, u, seen, matchJI)) { ans++; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Overload of the bipartiteMatching function without output parameters. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph) { int N = bpGraph[0].length; int[] matchJI = new int[N]; return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. */ public static int bipartiteMatching(int[][] intGraph) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchIJ, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchIJ, matchJI); } /** * Converts an integer adjacency matrix of 1's and 0's to a boolean adjacency matrix. * Useful with bipartiteMatching, which takes adjancency matrix of boolean[][] as input (instead of int[][]). */ public static boolean[][] intToBooleanAdjMat(int[][] mat) { int M = mat.length; int N = mat[0].length; boolean[][] bMat = new boolean[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { bMat[i][j] = (mat[i][j] != 0); } } return bMat; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import com.sun.org.apache.regexp.internal.RE; import java.io.*; import java.nio.file.ClosedWatchServiceException; import java.nio.file.OpenOption; import java.security.SecureRandom; import java.util.*; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); //String test = "C-large"; //ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + test + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + test + "-out.txt"))); new Main(io).solve(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } List<List<Integer>> gr = new ArrayList<>(); long MOD = 1_000_000_007; public void solve() { int n = io.ri(), r = io.ri(); double[] res = new double[n]; int[] xs = new int[n]; for(int i = 0;i<n;i++){ int x = io.ri(); xs[i] = x; double max = r; for(int j = 0;j<i;j++){ int dx = Math.abs(xs[j] - x); int dx2 = dx*dx; if(dx <= 2*r){ max = Math.max(max, Math.sqrt(4*r*r - dx2) + res[j]); } } res[i] = max; } StringBuilder sb = new StringBuilder(); for(int i = 0;i<res.length;i++){ if(i>0)sb.append(' '); sb.append(res[i]); } io.writeLine(sb.toString()); } } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public void writeIntArray(int[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int ri() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public long readLong() { try { long r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public String readWord() { try { boolean start = false; StringBuilder sb = new StringBuilder(); while (true) { int c = br.read(); if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') { sb.append((char)c); start = true; } else if (start || c == -1) return sb.toString(); } } catch (Exception ex) { return ""; } } public char readSymbol() { try { while (true) { int c = br.read(); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { return (char) c; } } } catch (Exception ex) { return 0; } } //public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }} } class Pair { public Pair(int a, int b) {this.a = a;this.b = b;} public int a; public int b; } class PairLL { public PairLL(long a, long b) {this.a = a;this.b = b;} public long a; public long b; } class Triple { public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;} public int a; public int b; public int c; }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.FileReader; import java.util.StringTokenizer; import java.io.IOException; import java.util.Arrays; public class Fish extends Thread { public Fish() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } private void solve() throws Throwable { int n = nextInt(); double[][] a = new double[n][n]; double[] dp = new double[(1 << n)]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { a[i][j] = nextDouble(); } } int limit = (1 << n) - 1; //dp[mask] = probability of current subset (mask) to remain in the end dp[limit] = 1.0; for (int mask = limit; mask > 0; --mask) { int cardinality = Integer.bitCount(mask); int probability = cardinality * (cardinality - 1) / 2; for (int first = 0; first < n; ++first) { if ((mask & powers[first]) != 0) { for (int second = first + 1; second < n; ++second) { if ((mask & powers[second]) != 0) { dp[mask - powers[first]] += dp[mask] * a[second][first] / probability; dp[mask - powers[second]] += dp[mask] * a[first][second] / probability; } } } } } for (int i = 0; i < n; ++i) { output.printf("%.10f ", dp[powers[i]]); } } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new Fish().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } static int powers[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144}; private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
16_E. Fish
CODEFORCES
//package CF489; //comment this line import java.io.*; import java.util.*; import java.math.*; public class B { private static long MOD=1000000007; private static BigInteger m=new BigInteger(1000000007+""); private static long pow(long x, long a) { if(a==0) return 1; long ans=pow(x,a/2); ans=(ans*ans)%MOD; if(a%2==1) ans=(ans*x)%MOD; return ans%MOD; } public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); long N,K,ans; //System.out.println(); //comment this line String s[]=br.readLine().trim().split(" "); N=Long.parseLong(s[0]); K=Long.parseLong(s[1]); BigInteger bi=new BigInteger(N+""); BigInteger a=new BigInteger(N+""); BigInteger two=new BigInteger(2+""); if(N==0) { System.out.println(0); System.exit(0); } if(K==0) { a=a.multiply(two); a=a.mod(m); System.out.println(a); System.exit(0); } long p=pow(2,K); BigInteger p2=new BigInteger(p+""); BigInteger tmp=p2.subtract(BigInteger.ONE); tmp=tmp.mod(m); p2=p2.multiply(two); p2=p2.mod(m); a=a.multiply(p2); a=a.mod(m); a=a.subtract(tmp); a=a.mod(m); if(!(a.signum()==1)&&!(a.signum()==0)) a.add(m); System.out.println(a); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.Scanner; public class Sasha1113A { static int solution(int n, int v){ int count; if(v>=n) return n-1; else{ count = (v-1) + ((n-v)*(n-v+1))/2; } return count; } public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int v = scan.nextInt(); System.out.print(solution(n, v)); } }
constant
1113_A. Sasha and His Trip
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { private void solve() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(), m = nextInt(), u = 1, d = n; while (u < d) { for (int i = 1; i <= m; i++) { out.println(u + " " + i); out.println(d + " " + (m - i + 1)); } u++; d--; } if (u == d) { int l = 1, r = m; while (l < r) { out.println(u + " " + l++); out.println(d + " " + r--); } if (l == r) out.println(u + " " + l); } out.close(); } public static void main(String[] args) { new D().solve(); } private BufferedReader br; private StringTokenizer st; private PrintWriter out; private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return st.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
//Implemented By Aman Kotiyal Date:-30-May-2021 Time:-7:54:28 pm import java.io.*; import java.util.*; public class ques3 { public static void main(String[] args)throws Exception{ new ques3().run();} long mod=1000000000+7; void solve() throws Exception { for(int ii=ni();ii>0;ii--) { int n=ni(); //ArrayList<Integer> al=new ArrayList<Integer>(); Stack<Integer> st=new Stack<Integer>(); int x=ni(); //al.add(1); st.add(1); out.println("1"); for(int i=2;i<=n;i++) { x=ni(); if(x==1) { st.add(1); Stack<Integer> tep=(Stack<Integer>) st.clone(); display(tep); continue; } int top=st.peek(); if(top+1==x) { st.pop(); st.add(x); Stack<Integer> tep=(Stack<Integer>) st.clone(); display(tep); continue; } while(true) { top=st.peek(); if(top+1==x) { st.pop(); st.add(x); Stack<Integer> tep=(Stack<Integer>) st.clone(); display(tep); break; } top=st.pop(); } } } } void display(Stack<Integer> st) { ArrayList<Integer> al = new ArrayList<>(); while(st.size()!=0) { int tem=st.pop(); al.add(tem); } Collections.reverse(al); for (int i = 0; i <al.size()-1; i++) { out.print(al.get(i)+"."); } out.println(al.get(al.size()-1)); } /*FAST INPUT OUTPUT & METHODS BELOW*/ private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; private SpaceCharFilter filter; PrintWriter out; int min(int... ar){int min=Integer.MAX_VALUE;for(int i:ar)min=Math.min(min, i);return min;} long min(long... ar){long min=Long.MAX_VALUE;for(long i:ar)min=Math.min(min, i);return min;} int max(int... ar) {int max=Integer.MIN_VALUE;for(int i:ar)max=Math.max(max, i);return max;} long max(long... ar) {long max=Long.MIN_VALUE;for(long i:ar)max=Math.max(max, i);return max;} void reverse(int a[]){for(int i=0;i<a.length>>1;i++){int tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}} void reverse(long a[]){for(int i=0;i<a.length>>1;i++){long tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}} String reverse(String s){StringBuilder sb=new StringBuilder(s);sb.reverse();return sb.toString();} void shuffle(int a[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i=0;i<a.length;i++) al.add(a[i]); Collections.sort(al); for(int i=0;i<a.length;i++) a[i]=al.get(i); } long lcm(long a,long b) { return (a*b)/(gcd(a,b)); } int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } /* for (1/a)%mod = ( a^(mod-2) )%mod ----> use expo to calc -->(a^(mod-2)) */ long expo(long p,long q) /* (p^q)%mod */ { long z = 1; while (q>0) { if (q%2 == 1) { z = (z * p)%mod; } p = (p*p)%mod; q >>= 1; } return z; } void run()throws Exception { in=System.in; out = new PrintWriter(System.out); solve(); out.flush(); } private int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } private int ni() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); int sgn = 1; if (c == '-') { sgn = -1; c = scan(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = scan(); } while (!isSpaceChar(c)); return res * sgn; } private long nl() throws IOException { long num = 0; int b; boolean minus = false; while ((b = scan()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = scan(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = scan(); } } private double nd() throws IOException{ return Double.parseDouble(ns()); } private String ns() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = scan(); } while (!isSpaceChar(c)); return res.toString(); } private String nss() throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); return br.readLine(); } private char nc() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); return (char) c; } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } private boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhiteSpace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; public class Pizza { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long num = sc.nextLong() + 1; sc.close(); System.out.println(num % 2 == 0 || num == 1 ? num / 2 : num); } }
constant
979_A. Pizza, Pizza, Pizza!!!
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { int N; public void solve(int testNumber, InputReader in, PrintWriter out) { N = in.nextInt(); int low = 1; int lowVal = getval(1, out, in); int high = N / 2 + 1; int highVal = -lowVal; if (Math.abs(lowVal) % 2 == 1) { out.println("! -1"); out.flush(); } else { while (low < high) { int mid = (low + high) / 2; int a = getval(mid, out, in); if (Integer.signum(a) == 0) { out.println("! " + mid); out.flush(); return; } else { if (Integer.signum(a) == Integer.signum(lowVal)) { low = mid + 1; } else { high = mid; } } } out.println("! " + low); out.flush(); } } int getval(int i, PrintWriter out, InputReader in) { out.println("? " + i); out.flush(); int a = in.nextInt(); out.println("? " + (i + N / 2)); out.flush(); int b = in.nextInt(); return a - b; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
logn
1019_B. The hat
CODEFORCES
import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //int qq = 1; int qq = Integer.MAX_VALUE; //int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int n = readInt(); int[] l = new int[n]; for(int i = 0; i < n; i++) { l[i] = readInt(); } int ret = 0; for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) { if(l[i] > l[j]) { ret++; } } } int qqq = readInt(); while(qqq-- > 0) { int a = readInt(); int b = readInt(); int d = b-a; ret ^= d*(d+1)/2; pw.println(ret%2 == 0 ? "even" : "odd"); } } exitImmediately(); } private static void exitImmediately() { pw.close(); System.exit(0); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextLine() throws IOException { String s = br.readLine(); if(s == null) { exitImmediately(); } st = null; return s; } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine().trim()); } return st.nextToken(); } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.*; import java.util.*; public class CF1009E { static final int MD = 998244353; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] aa = new int[1 + n]; for (int i = 1, a = 0; i <= n; i++) aa[i] = a = (a + Integer.parseInt(st.nextToken())) % MD; int[] pp = new int[n]; pp[0] = 1; for (int i = 1, p = 1; i < n; i++) { pp[i] = p; p = p * 2 % MD; } int d = 0; long ans = 0; for (int i = n - 1; i >= 0; i--) { // rest at i d = (d * 2 % MD + aa[n - 1 - i]) % MD; // rest again before n ans = (ans + (long) (d + aa[n - i]) * pp[i]) % MD; } System.out.println(ans); } }
linear
1009_E. Intercity Travelling
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class E implements Runnable { public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();} int n, m; char[] str; int[][] occs, cost; int[] dp; public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println(""); //where's my 420???? :( n = fs.nextInt(); m = fs.nextInt(); byte[] str = fs.next().getBytes(); int[] occs = new int[1<<m]; for(int i = 0; i < n-1; i++) { int l1 = str[i] - 'a'; int l2 = str[i+1] - 'a'; occs[(1<<l1) | (1<<l2)]++; occs[(1<<l2) | (1<<l1)]++; } //cost[mask][v] = numPairs with v for some all bits on in mask int all = (1<<m)-1; cost = new int[m][1<<m]; for(int i = 0; i < m; i++) { for(int mask = 1; mask < all; mask++) { if(((1<<i)&mask) > 0) continue; int lb = mask & (-mask); int trail = Integer.numberOfTrailingZeros(lb); int nmask = mask ^ lb; cost[i][mask] = cost[i][nmask]+occs[1<<i | 1<<trail]; } } dp = new int[1<<m]; for(int mask = dp.length-2; mask >= 0; mask--) { int addOn = 0; for(int nxt = 0; nxt < m; nxt++) { if(((1<<nxt)&mask) > 0) continue; addOn += cost[nxt][mask]; } int res = oo; for(int nxt = 0; nxt < m; nxt++) { if(((1<<nxt)&mask) > 0) continue; int ret = addOn+dp[mask | (1<<nxt)]; res = min(res, ret); } dp[mask] = res; } System.out.println(dp[0]>>1); out.close(); } int oo = (int)1e9; int min(int a, int b) { if(a < b) return a; return b; } class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
np
1238_E. Keyboard Purchase
CODEFORCES
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ import java.util.*; import java.io.*; import java.math.*; public class x1141F { public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); //thonky wonky HashMap<Long, ArrayList<Range>> map = new HashMap<Long, ArrayList<Range>>(); for(int r=0; r < N; r++) { long sum = 0L; for(int i=r; i >= 0; i--) { sum += arr[i]; if(!map.containsKey(sum)) map.put(sum, new ArrayList<Range>()); map.get(sum).add(new Range(i, r)); } } ArrayList<Range> res = new ArrayList<Range>(); for(long key: map.keySet()) { ArrayList<Range> ls = map.get(key); ArrayList<Range> temp = new ArrayList<Range>(); temp.add(ls.get(0)); int r = ls.get(0).r; for(int i=1; i < ls.size(); i++) if(r < ls.get(i).l) { r = ls.get(i).r; temp.add(ls.get(i)); } if(res.size() < temp.size()) res = temp; } System.out.println(res.size()); StringBuilder sb = new StringBuilder(); for(Range x: res) { sb.append(x.l+" "+x.r); sb.append("\n"); } System.out.print(sb); } } class Range { public int l; public int r; public Range(int a, int b) { l = a+1; r = b+1; } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author pandusonu */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { // out.print("Case #" + testNumber + ": "); int n = in.readInt(); int[] a = in.readIntArray(n); int[][] sol = new int[n][n]; for (int i = 0; i < n; i++) { sol[0][i] = a[i]; } for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { sol[i][j] = sol[i - 1][j] ^ sol[i - 1][j + 1]; } } for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { sol[i][j] = Math.max(sol[i][j], Math.max(sol[i - 1][j], sol[i - 1][j + 1])); } } int q = in.readInt(); for (int i = 0; i < q; i++) { int l = in.readInt() - 1; int r = in.readInt() - 1; out.println(sol[r - l][l]); } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { try { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) return -1; } } catch (IOException e) { throw new RuntimeException(e); } return buf[curChar++]; } public int readInt() { return (int) readLong(); } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); if (c == -1) throw new RuntimeException(); } boolean negative = false; if (c == '-') { negative = true; 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 negative ? (-res) : (res); } public int[] readIntArray(int size) { int[] arr = new int[size]; for (int i = 0; i < size; i++) arr[i] = readInt(); return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
983_B. XOR-pyramid
CODEFORCES
/* stream Butter! eggyHide eggyVengeance I need U xiao rerun when */ 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 x1523C { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = new int[N]; for(int i=0; i < N; i++) arr[i] = Integer.parseInt(infile.readLine()); ArrayList<Integer>[] buckets = new ArrayList[N]; buckets[0] = new ArrayList<Integer>(); buckets[0].add(arr[0]); //first element always 1? for(int i=1; i < N; i++) { ArrayList<Integer> ls = new ArrayList<Integer>(); if(arr[i] == 1) { for(int x: buckets[i-1]) ls.add(x); ls.add(1); } else { int dex = -1; for(int a=0; a < buckets[i-1].size(); a++) if(buckets[i-1].get(a) == arr[i]-1) dex = a; for(int a=0; a < dex; a++) ls.add(buckets[i-1].get(a)); ls.add(arr[i]); } buckets[i] = ls; } //output answer for(int a=0; a < N; a++) { for(int i=0; i < buckets[a].size()-1; i++) { sb.append(buckets[a].get(i)); sb.append("."); } sb.append(arr[a]); sb.append("\n"); } } System.out.print(sb); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class InversionCounting { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = Integer.parseInt(sc.nextLine()); int inversions = 0; int[] data = new int[n]; StringTokenizer st = new StringTokenizer(sc.nextLine()); for(int i = 0; i < n; i ++) { data[i] = Integer.parseInt(st.nextToken()); } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { if(data[i] > data[j]) inversions++; } } //false = 0, true = 1; boolean inversiontype = (inversions % 2 == 1); int n2 = Integer.parseInt(sc.nextLine()); for(int i = 0; i < n2; i++) { st = new StringTokenizer(sc.nextLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int parity = (b-a)*(b - a + 1)/2; if(parity % 2 == 0) { if(inversiontype) pw.println("odd"); else pw.println("even"); } else { inversiontype = !inversiontype; if(inversiontype) pw.println("odd"); else pw.println("even"); } } pw.close(); } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.Scanner; public class A1177 { public static long exponential(long a, long b){ long result = 1; for(int i=0;i<b;i++){ result *= a; } return result; } public static void main(String args[]){ Scanner scanner = new Scanner(System.in); long k = scanner.nextLong(); //int k =21; long sum = 0; long i=1; while(true){ long interval = 9 * exponential(10,i-1) * i; if(sum + interval >= k){ break; } else { i++; sum += interval; } } long t = k-sum; long targetNumber = exponential(10, i-1) + (t-1)/i; String s = "" + targetNumber; int hedef = (int)((t-1)%i); System.out.println(s.charAt(hedef)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; public class A4 { public BufferedReader input; public PrintWriter output; public StringTokenizer stoken = new StringTokenizer(""); public static void main(String[] args) throws IOException { new A4(); } A4() throws IOException { input = new BufferedReader(new InputStreamReader(System.in)); output = new PrintWriter(System.out); run(); input.close(); output.close(); } private void run() throws IOException { int n = Math.toIntExact(nextLong()); int m = Math.toIntExact(nextLong()); int[] coor = new int[n + 1]; int[] ss = new int[n + 1]; for (int i = 0; i < n; i++) { coor[i] = Math.toIntExact(nextLong()); } coor[n] = 1000000000; Arrays.sort(coor); for (int i = 0; i < m; i++) { long x1 = nextLong(); long x2 = nextLong(); nextLong(); if (x1 == 1 && x2 >= coor[0]) { int l = 0; int r = n + 1; while (r - l > 1) { int mi = (r + l) / 2; if (coor[mi] > x2) { r = mi; } else { l = mi; } } ss[l]++; } } long[] ans = new long[n + 1]; ans[n] = ss[n] + n; long min = ans[n]; for (int i = n - 1; i > -1; i--) { ans[i] = ans[i + 1] - 1 + ss[i]; if (ans[i] < min) { min = ans[i]; } } System.out.println(min); } private Long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextString()); } private String nextString() throws IOException { while (!stoken.hasMoreTokens()) { String st = input.readLine(); stoken = new StringTokenizer(st); } return stoken.nextToken(); } }
nlogn
1075_C. The Tower is Going Home
CODEFORCES
import java.util.*; import java.io.*; public class RGBSubstring { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int Q = scanner.nextInt(); while(Q-->0) { int N = scanner.nextInt(); int K = scanner.nextInt(); String s1 = "RGB"; String s2 = "GBR"; String s3 = "BRG"; char[] arr = scanner.next().toCharArray(); int[] cnts = new int[3]; for(int i = 0; i < K; i++) { int ind = i % 3; if (arr[i] != s1.charAt(ind)) cnts[0]++; if (arr[i] != s2.charAt(ind)) cnts[1]++; if (arr[i] != s3.charAt(ind)) cnts[2]++; } int ans = Math.min(Math.min(cnts[0], cnts[1]), cnts[2]); for(int i = K; i < N; i++) { int ind = (K-1)%3; int[] nextCnts = new int[3]; nextCnts[1] = cnts[0]; nextCnts[2] = cnts[1]; nextCnts[0] = cnts[2]; if ('R' != arr[i-K]) nextCnts[1]--; if ('G' != arr[i-K]) nextCnts[2]--; if ('B' != arr[i-K]) nextCnts[0]--; if (arr[i] != s1.charAt(ind)) nextCnts[0]++; if (arr[i] != s2.charAt(ind)) nextCnts[1]++; if (arr[i] != s3.charAt(ind)) nextCnts[2]++; cnts = nextCnts; for(int j = 0; j < 3; j++) ans = Math.min(ans, cnts[j]); } out.println(ans); } out.flush(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } }
quadratic
1196_D1. RGB Substring (easy version)
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.lang.Character.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class A { public void run() { Scanner sc = new Scanner(System.in); String s = sc.next(); int n = s.length(); String[] ss = new String[n]; for (int i = 0; i < n; i++) ss[i] = s.substring(i); sort(ss); int res = 0; for (int i = 1; i < n; i++) res = max(res, count(ss[i - 1], ss[i])); System.out.println(res); } int count(String s, String t) { int ret = 0; for (int i = 0; i < min(s.length(), t.length()); i++) if (s.charAt(i) != t.charAt(i)) return ret; else ret++; return ret; } void debug(Object... os) { System.err.println(Arrays.deepToString(os)); } public static void main(String... args) { new A().run(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.util.StringTokenizer; import java.io.InputStreamReader; public class Main{ public static void main(String[] args)throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); int max=0; for(int i=0;i<s.length();i++){ int len=0; int k=i; boolean flag=false; for(int j=i+1;j<s.length();j++){ if(s.charAt(k)==s.charAt(j)){ len++; k++; flag=true; } else if(flag==true){ j=j-len; k=i; if(max<len) max=len; len=0; flag=false; } } if(max<len) max=len; } System.out.print(max); }}
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Hieu Le */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { private int n; private InputReader in; private PrintWriter out; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); this.in = in; this.out = out; query(new Point(1, 1), new Point(n, n), new Rectangle()); } private boolean query(Point bottomLeft, Point topRight, Rectangle rectangle) { if (bottomLeft.r > topRight.r || bottomLeft.c > topRight.c) return false; // Find the column of the right edge. int low = bottomLeft.c, high = topRight.c; while (low < high) { int mid = low + (high - low) / 2; int answer = ask(bottomLeft.r, bottomLeft.c, topRight.r, mid); if (answer > 0) high = mid; else low = mid + 1; } int rightCol = low; // Find the column of the left edge. low = bottomLeft.c; high = topRight.c; while (low < high) { int mid = low + (high - low + 1) / 2; int answer = ask(bottomLeft.r, mid, topRight.r, topRight.c); if (answer > 0) low = mid; else high = mid - 1; } int leftCol = low; // Find the topmost row. low = bottomLeft.r; high = topRight.r; while (low < high) { int mid = low + (high - low) / 2; int answer = ask(bottomLeft.r, bottomLeft.c, mid, topRight.c); if (answer > 0) high = mid; else low = mid + 1; } int topRow = low; // Find the bottommost row. low = bottomLeft.r; high = topRight.r; while (low < high) { int mid = low + (high - low + 1) / 2; int answer = ask(mid, bottomLeft.c, topRight.r, topRight.c); if (answer > 0) low = mid; else high = mid - 1; } int bottomRow = low; if (leftCol > rightCol) { Rectangle first = new Rectangle(); query(new Point(1, leftCol), new Point(n, n), first); Rectangle second = new Rectangle(); query(new Point(1, 1), new Point(n, rightCol), second); out.printf("! %d %d %d %d %d %d %d %d\n", first.bottomLeft.r, first.bottomLeft.c, first.topRight.r, first.topRight.c, second.bottomLeft.r, second.bottomLeft.c, second.topRight.r, second.topRight.c); return true; } if (bottomRow > topRow) { Rectangle first = new Rectangle(); query(new Point(bottomRow, 1), new Point(n, n), first); Rectangle second = new Rectangle(); query(new Point(1, 1), new Point(topRow, n), second); out.printf("! %d %d %d %d %d %d %d %d\n", first.bottomLeft.r, first.bottomLeft.c, first.topRight.r, first.topRight.c, second.bottomLeft.r, second.bottomLeft.c, second.topRight.r, second.topRight.c); return true; } rectangle.bottomLeft.r = bottomRow; rectangle.bottomLeft.c = leftCol; rectangle.topRight.r = topRow; rectangle.topRight.c = rightCol; return true; } private int ask(int r1, int c1, int r2, int c2) { out.printf("? %d %d %d %d\n", r1, c1, r2, c2); out.flush(); return in.nextInt(); } private class Point { private int r; private int c; public Point(int r, int c) { this.r = r; this.c = c; } } private class Rectangle { private Point bottomLeft; private Point topRight; public Rectangle() { bottomLeft = new Point(-1, -1); topRight = new Point(-1, -1); } } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; private static final int BUFFER_SIZE = 32768; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
logn
713_B. Searching Rectangles
CODEFORCES
import java.io.*; import java.math.*; import static java.lang.Math.*; import java.security.SecureRandom; import static java.util.Arrays.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import sun.misc.Regexp; import java.awt.geom.*; import sun.net.www.content.text.plain; public class Main { public static void main(String[] args) throws IOException { new Main().run(); } StreamTokenizer in; PrintWriter out; //deb//////////////////////////////////////////////// public static void deb(String n, Object n1) { System.out.println(n + " is : " + n1); } public static void deb(int[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(boolean[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(double[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(String[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(int[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } public static void deb(double[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } public static void deb(long[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } public static void deb(String[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } ///////////////////////////////////////////////////////////// int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } void run() throws IOException { // in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt"))); // out = new PrintWriter(new FileWriter("output.txt")); in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); } //boolean inR(int x,int y){ //return (x<=0)&&(x<4)&&(y<=0)&&(y<4); //} @SuppressWarnings("unchecked") void solve() throws IOException { // BufferedReader re= new BufferedReader(new FileReader("C:\\Users\\ASELA\\Desktop\\PROBLEMSET\\input\\F\\10.in")); BufferedReader re= new BufferedReader(new InputStreamReader(System.in)); Scanner sc= new Scanner(System.in); long n=sc.nextLong(),k=sc.nextLong(); if(k*(k-1)/2<n-1) System.out.println("-1"); else{ long ff=k*(k-1)/2; ff=-2*(n-1-ff); // System.out.println(ff); long up=k,dw=0; while(up-dw>1){ long c=(up+dw)/2; if(c*(c-1)<=ff)dw=c; else up=c; } if(n==1) { System.out.println("0"); return; } System.out.println(k-dw); } } }
logn
287_B. Pipeline
CODEFORCES
import java.util.ArrayList; import java.util.Scanner; public class Main { static ArrayList<Edge> graph; static ArrayList<ArrayList<Integer>> graphForKuhn; static int n, m, u = 0; static int mt[]; static int used[]; public static void main(String[] args) { formGraph(); System.out.println(getAnswer()); } static boolean kuhn(int start) { if (used[start] == u) return false; used[start] = u; for (int i=0; i< graphForKuhn.get(start).size(); i++) { int to = graphForKuhn.get(start).get(i); if (mt[to] == -1 || kuhn(mt[to])) { mt[to] = start; return true; } } return false; } private static int getAnswer() { int currentAnswer = Integer.MAX_VALUE; for (int cur= 0; cur<n; cur++) { int adj = 0, otheradj = 0, answer = 0; for (int j=0; j<n; j++) { graphForKuhn.get(j).clear(); mt[j] = -1; } for (int j=0; j<m; j++) { if (graph.get(j).from == cur || graph.get(j).to == cur) adj++; else { graphForKuhn.get(graph.get(j).from).add(graph.get(j).to); otheradj++; } } for (int j=0; j<n; j++) { u++; kuhn(j); } int tsz = 0; for (int j=0; j<n; j++) { if (mt[j] != -1) tsz++; } answer = 2*(n-1)+1-adj+otheradj-2*tsz+(n-1); currentAnswer = Math.min(answer, currentAnswer); } return currentAnswer; } private static void formGraph() { Scanner in = new Scanner(System.in); n = in.nextInt(); m = in.nextInt(); graph = new ArrayList<Edge>(m); for (int i=0; i<m; i++) { int x = in.nextInt(); int y = in.nextInt(); graph.add(new Edge(x-1, y-1)); } graphForKuhn = new ArrayList<ArrayList<Integer>>(n); for (int i=0; i<n; i++) graphForKuhn.add(new ArrayList<Integer>(n)); mt = new int[n]; used = new int[n]; in.close(); } } class Edge { int from; int to; public Edge(int from, int to) { this.from = from; this.to = to; } }
cubic
387_D. George and Interesting Graph
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 Don Li */ public class EhabAndAComponentChoosingProblem { long INF = (long) 1e18; int n; int[] a; int[][] G; void solve() { n = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); int[] fr = new int[n - 1], to = new int[n - 1]; for (int i = 0; i < n - 1; i++) { fr[i] = in.nextInt() - 1; to[i] = in.nextInt() - 1; } G = build_graph(n, fr, to); int[][] ret = bfs(G, 0); int[] par = ret[0], ord = ret[2]; long best = -INF; long[] dp = new long[n]; for (int i = n - 1; i >= 0; i--) { int u = ord[i]; dp[u] = a[u]; for (int v : G[u]) { if (v != par[u]) { if (dp[v] > 0) dp[u] += dp[v]; } } best = Math.max(best, dp[u]); } int k = 0; for (int i = n - 1; i >= 0; i--) { int u = ord[i]; dp[u] = a[u]; for (int v : G[u]) { if (v != par[u]) { if (dp[v] > 0) dp[u] += dp[v]; } } if (dp[u] == best) { dp[u] = -INF; k++; } } out.printf("%d %d%n", best * k, k); } int[][] bfs(int[][] G, int root) { int n = G.length; int[] par = new int[n]; Arrays.fill(par, -1); int[] dep = new int[n]; dep[root] = 0; int[] qu = new int[n]; qu[0] = root; for (int l = 0, r = 1; l < r; l++) { int u = qu[l]; for (int v : G[u]) { if (v != par[u]) { qu[r++] = v; par[v] = u; dep[v] = dep[u] + 1; } } } return new int[][]{par, dep, qu}; } int[][] build_graph(int n, int[] from, int[] to) { int[][] G = new int[n][]; int[] cnt = new int[n]; for (int i = 0; i < from.length; i++) { cnt[from[i]]++; cnt[to[i]]++; } for (int i = 0; i < n; i++) G[i] = new int[cnt[i]]; for (int i = 0; i < from.length; i++) { G[from[i]][--cnt[from[i]]] = to[i]; G[to[i]][--cnt[to[i]]] = from[i]; } return G; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new EhabAndAComponentChoosingProblem().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
linear
1088_E. Ehab and a component choosing problem
CODEFORCES
import java.io.*; import java.util.*; public class l { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int mod = (int) (1e9 + 7); // static int n; static StringBuilder sol; static class pair implements Comparable<pair> { int left, type; double w; public pair(int x, double y) { left = x; w = y; type= 0; } public int compareTo(pair o) { return Double.compare(w,o.w); } public String toString() { return left + " " + w; } } static class tri implements Comparable<tri> { int st, end,len, side; tri(int a, int b, int c,int d) { st = a; end = b; len = c; side=d; } public int compareTo(tri o) { if (st == o.st) return end - o.end; return st - o.st; } public String toString() { return st + " " + end ; } } static ArrayList<pair>[]adj; static int n; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); //FileWriter f = new FileWriter("C:\\Users\\Ibrahim\\out.txt"); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); int lo=0; int hi=n; int ans=0; while (lo<=hi){ int mid=lo+hi>>1; long rem= n-mid; rem*=(rem+1); rem/=2; rem-=mid; //pw.println(rem+" "+mid+" "+k); if (rem==k){ ans=mid; break; } else if (rem>k){ lo=mid+1; } else hi=mid-1; } pw.println(ans); pw.flush(); } static long gcd(long a ,long b){ if (a==0)return b; return gcd(b%a,a); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.HashMap; import java.io.IOException; import java.util.LinkedHashMap; import java.io.UncheckedIOException; import java.util.Map; import java.io.Closeable; import java.util.Map.Entry; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } static class TaskC { SubsetGenerator sg = new SubsetGenerator(); Node[] nodes; int n; Map<Long, Node> map; long notExist; long[] mask2Key; Map<Long, LongList> sequence; DigitUtils.BitOperator bo = new DigitUtils.BitOperator(); boolean[] dp; public void solve(int testNumber, FastInput in, FastOutput out) { n = in.readInt(); nodes = new Node[n]; for (int i = 0; i < n; i++) { nodes[i] = new Node(); nodes[i].id = i; } map = new LinkedHashMap<>(200000); for (int i = 0; i < n; i++) { int k = in.readInt(); for (int j = 0; j < k; j++) { long x = in.readInt(); map.put(x, nodes[i]); nodes[i].sum += x; } } long total = 0; for (Node node : nodes) { total += node.sum; } if (total % n != 0) { out.println("No"); return; } long avg = total / n; notExist = (long) 1e18; mask2Key = new long[1 << n]; Arrays.fill(mask2Key, notExist); sequence = new HashMap<>(200000); for (Map.Entry<Long, Node> kv : map.entrySet()) { for (Node node : nodes) { node.handled = false; } long key = kv.getKey(); Node node = kv.getValue(); node.handled = true; int mask = bo.setBit(0, node.id, true); LongList list = new LongList(15); list.add(key); long req = avg - (node.sum - key); boolean valid = true; while (true) { if (req == key) { break; } Node next = map.get(req); if (next == null || next.handled) { valid = false; break; } next.handled = true; list.add(req); req = avg - (next.sum - req); mask = bo.setBit(mask, next.id, true); } if (!valid) { continue; } mask2Key[mask] = key; sequence.put(key, list); } dp = new boolean[1 << n]; for (int i = 0; i < (1 << n); i++) { dp[i] = mask2Key[i] != notExist; sg.setSet(i); while (!dp[i] && sg.hasNext()) { int next = sg.next(); if (next == 0 || next == i) { continue; } dp[i] = dp[i] || (dp[next] && dp[i - next]); } } if (!dp[(1 << n) - 1]) { out.println("No"); return; } populate((1 << n) - 1); out.println("Yes"); for (Node node : nodes) { out.append(node.out).append(' ').append(node.to + 1).append('\n'); } } public void populate(int mask) { if (mask2Key[mask] != notExist) { LongList list = sequence.get(mask2Key[mask]); int m = list.size(); for (int i = 0; i < m; i++) { long v = list.get(i); long last = list.get(DigitUtils.mod(i - 1, m)); Node which = map.get(v); Node to = map.get(last); which.out = v; which.to = to.id; } return; } sg.setSet(mask); while (sg.hasNext()) { int next = sg.next(); if (next == 0 || next == mask) { continue; } if (dp[next] && dp[mask - next]) { populate(next); populate(mask - next); return; } } } } static class LongList { private int size; private int cap; private long[] data; private static final long[] EMPTY = new long[0]; public LongList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new long[cap]; } } public LongList(LongList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public LongList() { this(0); } private void ensureSpace(int need) { int req = size + need; if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } private void checkRange(int i) { if (i < 0 || i >= size) { throw new ArrayIndexOutOfBoundsException(); } } public long get(int i) { checkRange(i); return data[i]; } public void add(long x) { ensureSpace(1); data[size++] = x; } public int size() { return size; } public String toString() { return Arrays.toString(Arrays.copyOf(data, size)); } } static class SubsetGenerator { private int[] meanings = new int[33]; private int[] bits = new int[33]; private int remain; private int next; public void setSet(int set) { int bitCount = 0; while (set != 0) { meanings[bitCount] = set & -set; bits[bitCount] = 0; set -= meanings[bitCount]; bitCount++; } remain = 1 << bitCount; next = 0; } public boolean hasNext() { return remain > 0; } private void consume() { remain = remain - 1; int i; for (i = 0; bits[i] == 1; i++) { bits[i] = 0; next -= meanings[i]; } bits[i] = 1; next += meanings[i]; } public int next() { int returned = next; consume(); return returned; } } static class Node { int id; long sum; boolean handled; long out; long to; } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(long c) { cache.append(c); return this; } public FastOutput println(String c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class DigitUtils { private static final long[] DIGIT_VALUES = new long[19]; static { DIGIT_VALUES[0] = 1; for (int i = 1; i < 19; i++) { DIGIT_VALUES[i] = DIGIT_VALUES[i - 1] * 10; } } private DigitUtils() { } public static int mod(int x, int mod) { x %= mod; if (x < 0) { x += mod; } return x; } public static class BitOperator { public int setBit(int x, int i, boolean v) { if (v) { x |= 1 << i; } else { x &= ~(1 << i); } return x; } } } }
np
1242_C. Sum Balance
CODEFORCES
import java.io.*; import java.util.*; public class A { FastScanner in; PrintWriter out; void solve() { int tc = in.nextInt(); for (int t = 0; t < tc; t++) { int n = in.nextInt(); int m = in.nextInt(); O[] a = new O[n * m]; int[][] cols = new int[m][n + n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cols[j][i] = cols[j][i + n] = in.nextInt(); a[i * m + j] = new O(i, j, cols[j][i]); } } Arrays.sort(a); boolean[] used = new boolean[m]; int cntUsed = 0; for (O o : a) { if (!used[o.y]) { used[o.y] = true; cntUsed++; if (cntUsed == n) { break; } } } int[] dp = new int[1 << n]; int[] ndp = new int[1 << n]; int[] maxndp = new int[1 << n]; for (int col = 0; col < m; col++) { if (!used[col]) { continue; } int[] curColumn = cols[col]; for (int shift = 0; shift < n; shift++) { System.arraycopy(dp, 0, ndp, 0, ndp.length); for (int mask = 0; mask < 1 << n; mask++) { for (int bit = 0; bit < n; bit++) { if (((1 << bit) & mask) == 0) { int nmask = mask | (1 << bit); ndp[nmask] = Math.max(ndp[nmask], ndp[mask] + curColumn[bit + shift]); } } } for (int i = 0; i < ndp.length; i++) { maxndp[i] = Math.max(maxndp[i], ndp[i]); } } int[] tmp = dp; dp = maxndp; maxndp = tmp; } out.println(dp[dp.length - 1]); } } class O implements Comparable<O> { int x, y, value; public O(int x, int y, int value) { this.x = x; this.y = y; this.value = value; } @Override public int compareTo(O o) { return -Integer.compare(value, o.value); } } void run() { try { in = new FastScanner(new File("A.in")); out = new PrintWriter(new File("A.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new A().runIO(); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.Scanner; import java.io.StreamTokenizer; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author KNIGHT0X300 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputStreamReader in = new InputStreamReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { StreamTokenizer in; PrintWriter out; BufferedReader re; Scanner sc; public void solve (int testNumber, InputStreamReader in, PrintWriter out) { this.in = new StreamTokenizer(new BufferedReader(in)); this.re = new BufferedReader(in); this.sc = new Scanner(in); this.out = out; try { this.solve(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } out.flush(); } void solve() throws IOException { long a=sc.nextLong(),b=sc.nextLong(); long ans=0,t; while(Math.min(a,b)!=1){ if(a>b){ ans+=a/b; a%=b; } else{ t=b; b=a; a=t; long g=gcd(a,b); a/=g;b/=g; } } ans+=Math.max(a,b); out.println(ans); } public static long gcd(long a, long b) { long c = 0; if(a<0) a=-a; if(b<0) b=-b; while (b>0) { c = a % b; a = b; b = c; } return a; } // do the sum }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; import java.util.StringTokenizer; import java.util.Queue; public class Solution{ static int[] dx = {1,-1,0,0}; static int[] dy = {0,0,1,-1}; static Queue<Pair> q ; static boolean[][] visited ; static Pair result = new Pair(0,0); static int n,m,k; public static void main(String[] args){ try(BufferedReader in = new BufferedReader(new FileReader("input.txt")); BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"))) { StringTokenizer s = new StringTokenizer(in.readLine()); n = Integer.parseInt(s.nextToken()); m = Integer.parseInt(s.nextToken()); k = Integer.parseInt(in.readLine()); visited = new boolean[n][m]; q = new LinkedList <>(); s = new StringTokenizer(in.readLine()); for(int i=0;i<k;i++){ int x = Integer.parseInt(s.nextToken()); int y = Integer.parseInt(s.nextToken()); q.add(new Pair(--x,--y)); } bfs(); String ans = "" + (result.x+1) +" "+ (result.y+1); out.write(ans); }catch(IOException e){ } } static void bfs(){ while(!q.isEmpty()){ Pair temp = q.poll(); if(visited[temp.x][temp.y]) continue; visited[temp.x][temp.y] = true; result.x = temp.x; result.y= temp.y; for(int i=0;i<4;i++){ int x = temp.x + dx[i]; int y = temp.y + dy[i]; if(x>=0 && x<n && y>=0 && y<m && !visited[x][y]) q.add(new Pair(x,y)); } } } } class Pair{ int x,y; public Pair(int x,int y){ this.x=x; this.y=y; } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class Primes { static Scanner in = new Scanner( new BufferedReader( new InputStreamReader( System.in ) ) ); public static void main( String[] args ) { int n = in.nextInt(), k = in.nextInt(), count = 0; boolean[] isP = new boolean[n+1]; for( int i = 2; i <= n; i++ ) isP[i] = true; ArrayList<Integer> primes = new ArrayList<Integer>(); for( int i = 2; i <= n; i++ ) if( isP[i] ) { primes.add(i); if( i <= Math.sqrt(n) ) for( int j = 2*i; j <= n; j += i ) isP[j] = false; } for( int i = 0; i < primes.size()-1; i++ ) { int sum = primes.get(i)+primes.get(i+1)+1; if( sum<=n && isP[sum] ) count++; } if( count>=k ) System.out.println( "YES" ); else System.out.println( "NO" ); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=s.nextInt(); Arrays.sort(a); ArrayList<Integer>al=new ArrayList(); int k=a[0]; int count=0; for(int j=0;j<n;j++) {k=a[j]; if(Collections.frequency(al,a[j])==0) {for(int i=0;i<n;i++) {if(a[i]%k==0) {al.add(a[i]);}} count++;}} System.out.println(count);}}
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.Scanner; public class Counterexample { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc= new Scanner(System.in); long l=sc.nextLong(),r=sc.nextLong(); if (l%2==0&&r-l>=2) System.out.print(l+" "+(l+1)+" "+(l+2)); else if (l%2==1&&r-l>=3) System.out.print((l+1)+" "+(l+2)+" "+(l+3)); else System.out.print("-1"); } }
constant
483_A. Counterexample
CODEFORCES
import java.util.*; import java.io.*; public class A{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int ans = 0; for(int i = 1; i <= n; i++){ ans += ((i*2) <= n) ? i : n-i+1; } System.out.println(ans); } }
linear
909_B. Segments
CODEFORCES
import java.util.Scanner; public final class b1 { public static void main(String[] args) { Scanner datain = new Scanner(System.in); long l=datain.nextLong(); long r=datain.nextLong(); if(r-l<2){System.out.print(-1);}else{ if(((r-l)==2)&&(l%2==1)){System.out.print(-1);}else{ if((l%2)==0){System.out.print(""+l+" "+(l+1)+" "+(l+2));}else{ System.out.print(""+(l+1)+" "+(l+2)+" "+(l+3)); } } } } }
constant
483_A. Counterexample
CODEFORCES
import java.util.Map; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.TreeMap; 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); int a = in.readInt(); int b = in.readInt(); TreeMap<Integer, Integer> mp = new TreeMap<Integer, Integer>(); for (int i = 0; i < n; ++i) { mp.put(in.readInt(), i); } int aname = 0; int bname = 1; if (a > b) { int t = a; a = b; b = t; aname = 1; bname = 0; } int[] res = new int[n]; while (mp.size() > 0) { Map.Entry<Integer, Integer> e = mp.firstEntry(); int val = e.getKey(); if (mp.containsKey(b - val)) { res[mp.get(val)] = res[mp.get(b - val)] = bname; mp.remove(val); mp.remove(b - val); } else if (mp.containsKey(a - val)) { res[mp.get(val)] = res[mp.get(a - val)] = aname; mp.remove(val); mp.remove(a - val); } else { break; } } if (mp.size() > 0) { out.println("NO"); } else { out.println("YES"); for (int i = 0; i < n; ++i) { if (i > 0) out.print(" "); out.print(res[i]); } out.println(); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { // InputMismatchException -> UnknownError if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } 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(); } else if (c == '+') { 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
linear
468_B. Two Sets
CODEFORCES
import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); /*int n = stdin.nextInt(); for(int i = 0; i < n; i++) { test(stdin); }*/ test(stdin); stdin.close(); } public static void test(Scanner stdin) { int n = stdin.nextInt(); int min = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { int a = stdin.nextInt(); if((int)((1.0)*a/(Math.max(i, n - i - 1))) < min) { min = (int)((1.0)*a/(Math.max(i, n - i - 1))); } } System.out.println(min); } }
linear
1159_B. Expansion coefficient of the array
CODEFORCES
import java.util.*; public class Contests { public static void main(String[] args) { Scanner clavier=new Scanner(System.in); long a=clavier.nextLong(); clavier.close(); if(a==1) System.out.println(5); else System.out.println(25); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { static final long mod=(int)1e9+7; public static void main(String[] args) throws Exception { FastReader in=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int n=in.nextInt(); long ans=0; for(int i=2;2*i<=n;i++) { ans+=i*(n/i-1); } ans*=4; pw.print(ans); pw.flush(); } } class pair { int f,s; } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if(st==null || !st.hasMoreElements()) { st=new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } }
linear
1062_D. Fun with Integers
CODEFORCES
import java.util.*; public class CompressionAndExpansion { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t = 0; t < T; t++) { int N = in.nextInt(); List<Integer> list = new ArrayList<>(); for (int i = 0; i < N; i++) { int n = in.nextInt(); if (n == 1) { list.add(n); } else { for (int j = list.size() - 1; j >= 0; j--) { if (list.get(j) == n - 1) { list.set(j, n); break; } list.remove(j); } } for (int j = 0; j < list.size(); j++) { System.out.print(list.get(j) + (j == list.size() - 1 ? "\n" : ".")); } } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.awt.*; import java.io.PrintWriter; 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]; for (int i=0;i<n;i++){ arr[i]=sc.nextInt(); } boolean vis[]=new boolean[n]; int c=0; for (int i=0;i<n;i++){ int min=200; for (int j=0;j<n;j++){ if (!vis[j] && min>arr[j]){ min=arr[j]; } } for (int j=0;j<n;j++){ if (!vis[j]&&arr[j]%min==0){ vis[j]=true; // System.out.println(arr[j]); } } if (min!=200){ c++; // System.out.println(min+" k"); }else break; } System.out.println(c); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] P = new int[n]; int[] check=new int[n]; for (int i = 1; i < n; i++) { P[i] = scanner.nextInt(); P[i]--; check[P[i]]++; } int[] leaves = new int[n]; for (int i=0;i<n;i++) { if(check[i]==0){ leaves[P[i]]++; } } for (int i = 0; i < n; i++) { if (check[i]>0&&leaves[i]<3) { System.out.println("No"); return; } } System.out.println("Yes"); } }
linear
913_B. Christmas Spruce
CODEFORCES
import java.util.Scanner; public class origami { public static void main(String args[]){ Scanner input = new Scanner(System.in); double n = input.nextInt(); double k = input.nextInt(); double red = 0; double green = 0; double blue = 0; double ans = 0; red = (2 * n) / k; green = (5 * n) / k; blue = (8 * n) / k; double red1 = Math.ceil(red) ; double green1 = Math.ceil(green); double blue1 = Math.ceil(blue); ans+=red1; ans+=green1; ans+=blue1; Double answer = new Double(ans); int finished = answer.intValue(); System.out.println(finished); } }
constant
1080_A. Petya and Origami
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.Deque; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.ArrayDeque; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); CCompressionAndExpansion solver = new CCompressionAndExpansion(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class CCompressionAndExpansion { Node end = new Node(null, -1); FastOutput out; public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.ri(); List<Node> seq = new ArrayList<>(n); Deque<Node> dq = new ArrayDeque<>(n); end = new Node(null, -1); dq.addLast(end); for (int i = 0; i < n; i++) { int x = in.ri(); while (true) { Node last = dq.peekLast(); if (last.nextChild != x) { dq.removeLast(); continue; } last.nextChild++; dq.addLast(new Node(dq.peekLast(), x)); break; } seq.add(dq.peekLast()); } this.out = out; for (Node node : seq) { print(node); out.println(); } } void print(Node root) { if (root.p != end) { print(root.p); out.append('.'); } out.append(root.index); } } static class FastInput { private final InputStream is; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int ri() { return readInt(); } public int readInt() { boolean rev = false; skipBlank(); if (next == '+' || next == '-') { rev = next == '-'; next = read(); } int val = 0; while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } return rev ? val : -val; } 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); } } static class Node { Node p; int index; int nextChild = 1; public Node(Node p, int index) { this.p = p; this.index = index; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 32 << 10; private final Writer os; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(int c) { cache.append(c); afterWrite(); return this; } public FastOutput println() { return append('\n'); } public FastOutput flush() { try { // boolean success = false; // if (stringBuilderValueField != null) { // try { // char[] value = (char[]) stringBuilderValueField.get(cache); // os.write(value, 0, cache.length()); // success = true; // } catch (Exception e) { // } // } // if (!success) { os.append(cache); // } os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; public class Paint_The_Numbers { public static void main(String[] args) { Scanner scan = new Scanner(System.in); ArrayList<Integer> paint = new ArrayList<Integer>(); int num = scan.nextInt(); for(int i = 0; i < num;i++) paint.add(scan.nextInt()); Collections.sort(paint); int counter = 0; //System.out.println(paint); while(paint.size()!=0) { num = paint.remove(0); for(int i = 0; i<paint.size();i++) { if(paint.get(i)%num==0) { paint.remove(i--); } } counter++; } System.out.println(counter); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.awt.*; public class A { static Comparator<Point> cmp = new Comparator<Point>() { public int compare(Point a, Point b) { if(a.x < b.x) return -1; else if(a.x > b.x) return 1; return 0; } }; public static void main(String args[]) { Scanner scan = new Scanner(System.in); while(scan.hasNextInt()) { int n = scan.nextInt(); int k = scan.nextInt(); Point[] a = new Point[n]; for(int i=0;i < n;i++) { a[i] = new Point(); a[i].x = scan.nextInt(); a[i].y = scan.nextInt(); } Arrays.sort(a, cmp); int rtn = 0; ArrayList<Double> ans = new ArrayList<Double>(); for(int i=0;i < n;i++) { //Left double lb = a[i].x - (a[i].y / 2.0) - k; double pos = lb + (k/2.0); boolean good = true; for(int j=0;j < ans.size();j++) if(Math.abs(ans.get(j) - pos) < 0.0000001) good = false; if(good && (i == 0 || a[i-1].x + (a[i-1].y / 2.0) <= lb)) { rtn++; ans.add(pos); } double rb = a[i].x + (a[i].y / 2.0) + k; pos = rb - (k/2.0); good = true; for(int j=0;j < ans.size();j++) if(Math.abs(ans.get(j) - pos) < 0.0000001) good = false; if(good && (i == n-1 || a[i+1].x - (a[i+1].y / 2.0) >= rb)) { rtn++; ans.add(pos); } } System.out.println(rtn); } } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=998244353; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } void work() { int n=ni(); mod=nl(); long[] dp1=new long[401]; long[][] dp2=new long[n+1][n+1]; long[][] C=new long[401][401]; for(int j=0;j<=400;j++){ for(int i=0;i<=j;i++){ if(i==0||j==i){ C[i][j]=1; }else{ C[i][j]=(C[i-1][j-1]+C[i][j-1])%mod; } } } for(int i=1;i<=400;i++){ for(int j=0;j<i;j++){ dp1[i]=(dp1[i]+C[j][i-1])%mod; } } for(int i=1;i<=n;i++){ dp2[i][i]=dp1[i]; } for(int i=1;i<=n;i++){ for(int j=1;j<i;j++){ for(int k=1;k<j;k++){ dp2[i][j]=dp2[i][j]+((((dp2[i-k-1][j-k]*dp1[k])%mod)*C[k][j])%mod); dp2[i][j]%=mod; } } } long ret=0; for(int j=1;j<=n;j++){ ret=(ret+dp2[n][j])%mod; } out.println(ret); } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w}); graph[(int)e].add(new long[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private String ns() { return in.next(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } return A; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { while(st==null || !st.hasMoreElements())//回车,空行情况 { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); System.out.println(n/2*3); } }
constant
84_A. Toy Army
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; public class Main { public static StreamTokenizer in; public static PrintStream out; public static BufferedReader br; public static String readString() throws IOException { in.nextToken(); return in.sval; } public static double readDouble() throws IOException { in.nextToken(); return in.nval; } public static int readInt() throws IOException { in.nextToken(); return (int) in.nval; } public static String readLine() throws IOException { return br.readLine(); } public static int genans(String ss) { int n = ss.length(); char[] s = ss.toCharArray(); int res = 0; while (true) { int firstT = -1; for (int i=0; i<n; i++) if (s[i]=='T') { firstT = i; break; } int lastH = -1; for (int i=n-1; i>=0; i--) if (s[i]=='H') { lastH=i; break; } if (firstT<lastH) { res++; s[firstT] = 'H'; s[lastH] = 'T'; } else break; } return res; } public static void main(String[] args) throws IOException { in = new StreamTokenizer(new InputStreamReader (System.in) ); br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintStream(System.out); readLine(); String s = readLine(); int n = s.length(); String kk = s; int ans = n*100; for (int tr=0; tr<n+2; tr++) { String kk2 = ""; for (int i=1; i<n; i++) kk2 = kk2 +kk.charAt(i); kk2 = kk2 + kk.charAt(0); kk = kk2; int cur = genans(kk); //out.println(kk+" "+cur); if (cur<ans) ans = cur; } out.println(ans); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.*; import java.util.*; public class a { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); long n = input.nextLong(); if(n == 1) out.println(5); else out.println(25); out.close(); } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) 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()); } } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.StreamTokenizer; import java.lang.reflect.Array; import java.util.Arrays; public class a { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //BufferedReader input = new BufferedReader(new FileReader("input.txt")); //BufferedWriter output = new BufferedWriter(new FileWriter("output.txt")); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); StreamTokenizer in = new StreamTokenizer(input); in.nextToken(); int n = (int)in.nval; int[] mas = new int[n]; for (int i = 0; i < n; i++) { in.nextToken(); mas[i] = (int)in.nval; } Arrays.sort(mas); int min = mas[0]; int i = 1; while ((i < n)&&(min == mas[i])) { i++; } if (i < n) { output.write(Integer.toString(mas[i])); } else { output.write("NO"); } input.close(); output.close(); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class C43 implements Runnable { public Scanner in; public PrintWriter out; final static String TASK_NAME = ""; C43() throws IOException { in = new Scanner( System.in ); // in = new StreamTokenizer( new InputStreamReader( System.in ) ); out = new PrintWriter( System.out ); } void close() throws IOException { out.close(); } public void run() { try { solve(); close(); } catch ( Exception e ) { e.printStackTrace(); } } public void solve() throws IOException { int n = in.nextInt(); char[] c = in.next().toCharArray(); int t = 0; for ( int i = 0; i < n; i ++ ) { if ( c[i] == 'T' ) { t ++; } } int ct = 0; for ( int i = 0; i < t; i ++ ) { if ( c[i] == 'T' ) { ct ++; } } int r = 0; for ( int i = 0; i < n; i ++ ) { r = Math.max( r, ct ); if ( c[i] == 'T' ) { ct --; } if ( c[( i + t ) % n] == 'T' ) { ct ++; } } out.println( t - r ); } public static void main( String[] args ) throws IOException { new Thread( new C43() ).start(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { //<editor-fold desc="input parse" defaultstate="collapsed"> private static StringTokenizer st; private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static long nextLong() { return Long.parseLong(st.nextToken()); } private static int nextInt() { return Integer.parseInt(st.nextToken()); } private static double nextDouble() { return Double.parseDouble(st.nextToken()); } private static short nextShort() { return Short.parseShort(st.nextToken()); } private static byte nextByte() { return Byte.parseByte(st.nextToken()); } private static void initTokenizer() throws Exception { st = new StringTokenizer(reader.readLine()); } //</editor-fold> public static void main(String[] args) throws Exception { initTokenizer(); int n = nextInt(); int a = nextInt(); int b = nextInt(); int[] h = new int[n]; initTokenizer(); for (int i = 0; i < n; i++) { h[i] = nextInt(); } Arrays.sort(h); System.out.print(h[b] - h[b - 1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author Mostafa */ public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); System.out.println((n/2) *3); } }
constant
84_A. Toy Army
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main { static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out,true); static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static int nextInt() throws Exception { if(st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return Integer.parseInt(st.nextToken()); } public static long nextLong() throws Exception { if(st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return Long.parseLong(st.nextToken()); } public static void main(String[] args) throws Exception { HashSet<Integer> set = new HashSet<>(); int n = nextInt(); int k = nextInt(); int[] m = new int[n]; int[] d = new int[n]; for(int i = 0;i < n;i++) m[i] = nextInt(); int l = -1; int r = -1; for(int i = 0;i < n;i++) { set.add(m[i]); d[i] = set.size(); if(d[i] == k) { r = i; break; } } if(r == -1) { out.println("-1 -1"); return; } for(int i = r;i >= 0;i--) { set.remove(m[i]); if(set.size() == 0) { l = i; break; } } out.println((l+1)+" "+(r+1)); } }
linear
224_B. Array
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: vaibhav mittal * Date: 23/6/12 * Time: 1:15 AM * To change this template use File | Settings | File Templates. */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); long n = in.nextLong(); out.println(0 + " " + 0 + " " + n); in.close(); out.close(); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /* public class _909C { } */ public class _909C { int mod = (int) 1e9 + 7; public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper in = new InputHelper(inputStream); // actual solution int n = in.readInteger(); char[] a = new char[n]; for (int i = 0; i < n; i++) { a[i] = in.read().charAt(0); } int[][][] dp = new int[2][n + 1][2]; dp[0][0][0] = dp[0][0][1] = 1; for (int i = 1; i < n; i++) { for (int j = n; j >= 0; j--) { if (a[i - 1] == 's') { dp[1][j][0] = dp[1][j][1] = dp[0][j][1]; } else { if (j > 0) dp[1][j][0] = dp[1][j][1] = dp[0][j - 1][0]; } } for (int j = 0; j <= n; j++) { dp[0][j][0] = dp[1][j][0]; dp[0][j][1] = dp[1][j][1]; dp[1][j][0] = 0; dp[1][j][1] = 0; } for (int j = n - 1; j >= 0; j--) { dp[0][j][1] += dp[0][j + 1][1]; dp[0][j][1] %= mod; } } System.out.println(dp[0][0][1]); // end here } public static void main(String[] args) throws FileNotFoundException { (new _909C()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
quadratic
909_C. Python Indentation
CODEFORCES
import static java.util.Arrays.*; import static java.lang.Math.*; import java.util.*; import java.io.*; public class A implements Runnable { public static void main(String [] args) throws IOException { new Thread(null, new A(), "", 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 N, T; void solve() throws IOException { StringTokenizer st = tokens(); N = nextInt(st); T = nextInt(st); T *= 2; ArrayList<Pair> list = new ArrayList<Pair>(); for(int i = 0; i < N; i++) { st = tokens(); int c = nextInt(st), L = nextInt(st); c *= 2; L *= 2; list.add(new Pair(c - L / 2, c + L / 2)); } Collections.sort(list); HashSet<Integer> set = new HashSet<Integer>(); for(int i = 0; i < list.size(); i++) { if(i == 0 || list.get(i).x - list.get(i - 1).y >= T) { set.add(list.get(i).x - T / 2); } if(i == list.size() - 1 || list.get(i + 1).x - list.get(i).y >= T) { set.add(list.get(i).y + T / 2); } } System.out.println(set.size()); } class Pair implements Comparable<Pair> { int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair p) { if(x != p.x) return x - p.x; return y - p.y; } } 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)); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.*; public class bender { static long[] dx = new long[]{0, 1, 0, -1}; static long[] dy = new long[]{-1, 0, 1, 0}; static long n, x, y, c; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("bender.in")); StringTokenizer dxdync = new StringTokenizer(in.readLine()); n = Long.parseLong(dxdync.nextToken()); x = Long.parseLong(dxdync.nextToken()); y = Long.parseLong(dxdync.nextToken()); c = Long.parseLong(dxdync.nextToken()); long a = 0; long b = c; while(a < b){ long m = (a + b)/2; long[] dxn = new long[4]; long[] dyn = new long[4]; for(int d = 0; d < 4; d++){ dxn[d] = x + dx[d] * m; dyn[d] = y + dy[d] * m; } long ret = (m+1)*(m+1) + m*m; ret -= h(1 - dyn[0]); ret -= h(dyn[2] - n); ret -= h(dxn[1] - n); ret -= h(1 - dxn[3]); ret += q(1 - dyn[0] - (n-x+1)); ret += q(1 - dyn[0] - x); ret += q(dyn[2] - n - (n - x + 1)); ret += q(dyn[2] - n - (x)); if (ret < c) a = m + 1; else b = m; } System.out.println(a); } public static long h(long x) { if (x <= 0) return 0; return 2*q(x) - x; } private static long q(long x){ if (x <= 0) return 0; return x*(x+1)/2; } }
logn
256_B. Mr. Bender and Square
CODEFORCES
/** * Created by Ariana Herbst on 12/29/17. */ import java.util.*; import java.io.*; /** * Created by Ariana Herbst on 12/29/17 */ public class GB2017C { static int n, r; static int[] x; static Map<Integer, Double> horo; public static void main(String[] args) { FastScanner sc = new FastScanner(); StringBuilder sb = new StringBuilder(); n = sc.nextInt(); r = sc.nextInt(); x = new int[n]; horo = new HashMap<Integer, Double>(); for (int x = 0; x <= r*2; x++) { double y = 2.0 *Math.sqrt(r * r - (r - x/2.0) * (r - x/2.0)); horo.put(x, y); } for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); } List<Double> y = new ArrayList<Double>(); for (int i = 0; i < n; i++) { double max = r; for (int j = 0; j < y.size(); j++) { int dx = intersects(i, j); if (dx >= 0) { double dy = horo.get(dx); max = Math.max(max, dy + y.get(j)); } } y.add(max); } for (int i = 0; i < n; i++) { sb.append(y.get(i) + " "); } System.out.println(sb); } static int intersects(int i, int j) { if (Math.abs(x[i] - x[j]) <= 2*r) { return 2*r - Math.abs(x[i] - x[j]); } else return -1; } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; /** * @author Vaibhav Mittal */ public class Main { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int testCases = 1; Task solver = new Task(); for (int i = 1; i <= testCases; ++i) solver.solve(in, out); out.close(); } } class Task { public void solve(Scanner in, PrintWriter out) { int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int[] complexity = new int[n]; for (int i = 0; i < n; ++i) complexity[i] = in.nextInt(); Arrays.sort(complexity); out.println(complexity[b] - complexity[b - 1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class A { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); int vis[] = new int[n]; Arrays.fill(vis, -1); int c = 0; for (int i = 0; i < n; i++) { if (vis[i] != -1) continue; c++; for (int j = i; j < n; j++) { if (vis[j] == -1 && a[j] % a[i] == 0) { vis[j] = c; } } } pw.println(c); pw.close(); } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class CF1515E extends PrintWriter { CF1515E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1515E o = new CF1515E(); o.main(); o.flush(); } void main() { int n = sc.nextInt(); int md = sc.nextInt(); int k = (n + 1) / 2; int[][] dp = new int[k + 1][n + 1]; dp[0][0] = 1; for (int h = 1; h <= k; h++) for (int l = h; l <= n - h + 1; l++) dp[h][l] = (int) ((dp[h][l - 1] * 2L + dp[h - 1][l - 1]) * h % md); int ans = 0; for (int h = 1; h <= k; h++) ans = (ans + dp[h][n - h + 1]) % md; println(ans); } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.*; public class ed817Q3 { public static void main(String[] args){ InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t = 1; for(int zxz=0;zxz<t;zxz++){ // my code starts here long n = in.nextLong(); long s = in.nextLong(); long start=0,end=n; long ans=n+1; while(start<=end){ long mid = start+(end-start)/2; if(mid-digitSum(mid)>=s){ ans = mid; end = mid-1; } else{ start=mid+1; } } System.out.println(n-ans+1); // my code ends here } } static int digitSum(long n){ int sum=0; while(n>0){ sum+=n%10; n=n/10; } return sum; } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.*; import java.util.*; public class A { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; String FInput=""; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } catch (NullPointerException e) { line=null; } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; new A(filePath); } public void readFInput() { for(;;) { try { readNextLine(); FInput+=line+" "; } catch(Exception e) { break; } } inputParser = new StringTokenizer(FInput, " "); } public A(String inputFile) { openInput(inputFile); readNextLine(); int n=NextInt(); int a=NextInt(); int b=NextInt(); int ret=0; readNextLine(); int [] p = new int[n]; for(int i=0; i<n; i++) { p[i]=NextInt(); } Arrays.sort(p); int id=0,cnt=0; while(id<n&&cnt<b) { cnt++; id++; } if(id<n) { ret=p[id]-p[id-1]; } System.out.print(ret); closeInput(); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Scanner; public class TaxiDriversAndLyft2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long n = scanner.nextLong(); long m = scanner.nextLong(); long[] people = new long[(int) (n+m)]; int[] taxiDrivers = new int[(int) (n+m)]; for(int i = 0;i< (n+m); i++) { people[i] = scanner.nextLong(); } for(int i = 0;i< (n+m); i++) { taxiDrivers[i] = scanner.nextInt(); } int lastTaxiDriverIndex = -1; long[] riderCountArray = new long[(int) (m)]; long[] a1 = new long[(int)n]; long[] b1 = new long[(int)m]; int j=0, k=0; for(int i = 0;i< (n+m); i++) { if(taxiDrivers[i] == 0) { a1[j] = people[i]; j++; } else { b1[k] = people[i]; k++; } } int l = 0, q=0; for(int i=0;i<j;i++) { while ((l<m-1 && m>1) && Math.abs(a1[i] - b1[l]) > Math.abs(a1[i] - b1[l+1])) { l++; } riderCountArray[l]++; } for(int i = 0;i< (m); i++) { System.out.print(riderCountArray[i]+" "); } } }
linear
1075_B. Taxi drivers and Lyft
CODEFORCES
import java.util.*; public class Main { public static void main(String args[]) { (new Main()).solve(); } void solve() { Scanner cin = new Scanner(System.in); while( cin.hasNextInt() ) { int n = cin.nextInt(); int arr[] = new int[n]; for(int i=0; i<n; ++i) { arr[i] = cin.nextInt(); } Arrays.sort(arr); int ret[] = new int[n]; ret[0] = 1; for(int i=0; i<n-1; ++i) { ret[i + 1] = arr[i]; } if( arr[n - 1] == 1 ) { ret[n - 1] = 2; } String glue = ""; for(int i=0; i<n; ++i) { System.out.print(glue + ret[i]); glue = " "; } System.out.println(); } } }
nlogn
135_A. Replacement
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class A { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); // Scanner scan = new Scanner(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 d = Integer.parseInt(st.nextToken()); st = new StringTokenizer(bf.readLine()); int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); int ans = 2; for(int i=0; i<n-1; i++) { int diff = a[i+1]-a[i]; if(diff == 2*d) ans++; else if(diff > 2*d) ans += 2; } System.out.println(ans); // int n = scan.nextInt(); // out.close(); System.exit(0); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.util.HashMap; import java.util.Scanner; public class Solution { public static void main(String [] args){ Scanner in = new Scanner(System.in); String ins = in.nextLine(); HashMap <String,Integer> sub = new HashMap<String,Integer>(); for (int i=0;i<ins.length();i++){ for (int j=i+1;j<=ins.length();j++){ String key = ins.substring(i,j); if (sub.containsKey(key)){ sub.put(key,sub.get(key)+1); } else { sub.put(key,1); } } } int max = 0; for (String key:sub.keySet()){ if (sub.get(key) >= 2 && key.length() > max){ max = key.length(); } } System.out.print(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; public class c { public static void main(String[] args) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in), 1); String s = r.readLine(); int n = Integer.parseInt(s); String s2 = r.readLine(); StringTokenizer st = new StringTokenizer(s2," "); int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = Integer.parseInt(st.nextToken()); Arrays.sort(a); if (a[n - 1] == 1) a[n - 1] = 2; else {a[n - 1] = 1; Arrays.sort(a);} for (int i = 0; i < n; i++) System.out.println(a[i]); } }
nlogn
135_A. Replacement
CODEFORCES
import java.util.*; import java.io.*; public class A { static class T { public int s,p; } public static void main(String args[]) throws Exception { InputReader sc=new InputReader(System.in); int n=sc.readInt(),k=sc.readInt(),i,j,z; T m[]=new T[n]; for(i=0;i<n;i++) {m[i]=new T();m[i].s=sc.readInt();m[i].p=sc.readInt();} for(i=0;i<n;i++) for(j=i+1;j<n;j++) if(m[i].s<m[j].s){z=m[i].s;m[i].s=m[j].s;m[j].s=z;z=m[i].p;m[i].p=m[j].p;m[j].p=z;} for(i=0;i<n;i++) for(j=i+1;j<n;j++) if(m[i].s==m[j].s&&m[i].p>m[j].p){z=m[i].s;m[i].s=m[j].s;m[j].s=z;z=m[i].p;m[i].p=m[j].p;m[j].p=z;} k--;int s=m[k].s,p=m[k].p,res=0; for(i=0;i<n;i++){if(m[i].s==s&&m[i].p==p)res++;} System.out.println(res); } } class InputReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } 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 readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return readString(); } }
nlogn
166_A. Rank List
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Stack; public class Main { static void debug(Object... args) { System.out.println(Arrays.deepToString(args)); } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int T = Integer.parseInt(br.readLine()); while (T-- > 0) { int N = Integer.parseInt(br.readLine()); Stack<LN> nodes = new Stack<>(); int a0 = Integer.parseInt(br.readLine()); LN root = new LN(1, 0, ""); nodes.add(root); pw.println(root); for (int i = 0; i < N - 1; i++) { int ai = Integer.parseInt(br.readLine()); while (!nodes.isEmpty()) { LN nn = nodes.pop(); if (ai == 1) { LN e = new LN(1, nn.depth + 1, nn.toString()); nodes.add(nn); nodes.add(e); pw.println(e); break; } else if (nn.lv == ai - 1) { LN e = new LN(ai, nn.depth, nn.base); nodes.add(e); pw.println(e); break; } } } } pw.flush(); } static class LN { int lv; int depth; String base; public LN(int lv, int depth, String prev) { this.lv = lv; this.depth = depth; base = prev; } @Override public String toString() { StringBuilder bob = new StringBuilder(base); if (depth > 0) { bob.append("."); } bob.append(lv); return bob.toString(); } } }
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.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int d = in.nextInt(); int[] x = new int[n + 1]; int ans = 2; for (int i = 1; i <= n; i++) x[i] = in.nextInt(); for (int i = 1; i < n; i++) { ans += (x[i + 1] - x[i] >= 2 * d) ? (x[i + 1] - x[i] == 2 * d ? 1 : 2) : 0; } out.print(ans); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 9/16/11 * Time: 1:27 PM * To change this template use File | Settings | File Templates. */ import java.io.*; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.HashSet; import java.util.Queue; import java.util.StringTokenizer; public class TaskC extends Thread { public TaskC() { try { this.input = new BufferedReader(new FileReader("input.txt")); this.output = new PrintWriter("output.txt"); this.setPriority(Thread.MAX_PRIORITY); } catch (Throwable e) { System.exit(666); } } private void solve() throws Throwable { int n = nextInt(); int m = nextInt(); int k = nextInt(); Queue<Integer> qX = new ArrayDeque<Integer>(); Queue<Integer> qY = new ArrayDeque<Integer>(); boolean [][]was = new boolean[n][m]; for (int i = 0; i < k; ++i) { int x = nextInt() - 1, y = nextInt() - 1; qX.add(x); qY.add(y); was[x][y] = true; } int lastX = -1, lastY = -1; while (!qX.isEmpty()) { lastX = qX.poll(); lastY = qY.poll(); for (int i = 0; i < dx.length; ++i) { int nextX = lastX + dx[i], nextY = lastY + dy[i]; if (nextX < n && nextY < m && nextX >= 0 && nextY >= 0 && !was[nextX][nextY]) { qX.add(nextX); qY.add(nextY); was[nextX][nextY] = true; } } } ++lastX; ++lastY; output.println(lastX + " " + lastY); } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new TaskC().start(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } static final int PRIME = 3119; static final int[]dx = {1, -1, 0, 0}, dy = {0, 0, -1, 1}; private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
cubic
35_C. Fire Again
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Washoum */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; inputClass in = new inputClass(inputStream); PrintWriter out = new PrintWriter(outputStream); APaintTheNumbers solver = new APaintTheNumbers(); solver.solve(1, in, out); out.close(); } static class APaintTheNumbers { public void solve(int testNumber, inputClass sc, PrintWriter out) { int n = sc.nextInt(); Integer[] tab = new Integer[n]; for (int i = 0; i < n; i++) { tab[i] = sc.nextInt(); } Arrays.sort(tab); boolean[] done = new boolean[n]; int ans = 0; for (int i = 0; i < n; i++) { if (!done[i]) { ans++; done[i] = true; for (int j = i + 1; j < n; j++) { if (!done[j] && tab[j] % tab[i] == 0) { done[j] = true; } } } } out.println(ans); } } static class inputClass { BufferedReader br; StringTokenizer st; public inputClass(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Code implements Runnable { public static void main(String[] args) throws IOException { new Thread(new Code()).start(); } private void solve() throws IOException { int n = nextInt(), m = nextInt(); if(n > m) { n ^= m; m ^= n; n ^= m; } int[][][] dp = new int[41][64][64]; for(int i = 0; i < 41; ++i) for(int j = 0; j < 64; ++j) for(int k = 0; k < 64; ++k) dp[i][j][k] = Integer.MAX_VALUE / 2; for(int i = 0; i < 64; ++i) dp[0][0][i] = countBit(i); for(int i = 1; i <= m; ++i) { for(int cur = 0; cur < 64; ++cur) { for(int next = 0; next < 64; ++next) { for(int prev = 0; prev < 64; ++prev) { if(!isBad(prev, cur, next, n)) { dp[i][cur][next] = min(dp[i][cur][next], dp[i - 1][prev][cur] + countBit(next)); } } } } } int ans = Integer.MAX_VALUE; for(int i = 0; i < 64; ++i) ans = min(ans, dp[m][i][0]); writer.println(n * m - ans); } private boolean isBit(int bits, int pos) { return pos < 0 ? false : ((bits & (1 << pos)) != 0); } private boolean isBad(int prev, int cur, int next, int count) { for(int i = 0; i < count; ++i) if(!(isBit(cur, i - 1) || isBit(cur, i) || isBit(cur, i + 1) || isBit(prev, i) || isBit(next, i))) return true; return false; } private int countBit(int bits) { int ans = 0; for(int i = 0; i < 6; ++i) ans += (bits & (1 << i)) > 0 ? 1 : 0; return ans; } private class Pair<E extends Comparable, V extends Comparable> implements Comparable<Pair<E, V>> { public Pair(E first, V second) { this.first = first; this.second = second; } @Override public int compareTo(Pair<E, V> obj) { if(first == obj.first) return second.compareTo(obj.second); return first.compareTo(obj.first); } @Override public boolean equals(Object obj) { Pair other = (Pair)obj; return first.equals(other.first) && second.equals(other.second); } public E first; public V second; } @Override public void run() { try { if(in.equals("")) reader = new BufferedReader(new InputStreamReader(System.in)); else reader = new BufferedReader(new FileReader(in)); if(out.equals("")) writer = new PrintWriter(new OutputStreamWriter(System.out)); else writer = new PrintWriter(new FileWriter(out)); solve(); } catch(IOException e) { e.printStackTrace(); } finally { try { reader.close(); writer.close(); } catch(IOException e) { e.printStackTrace(); } } } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private float nextFloat() throws IOException { return Float.parseFloat(nextToken()); } private String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(reader.readLine()); return st.nextToken(); } private String in = "", out = ""; private BufferedReader reader; private PrintWriter writer; private StringTokenizer st; }
np
111_C. Petya and Spiders
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); System.out.println(n/2*3); } }
constant
84_A. Toy Army
CODEFORCES
import javafx.util.Pair; import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] arr = new int[n]; int chet = 0; for (int i = 0; i < n; i++) { arr[i]=scanner.nextInt(); for (int j = 0; j < i; j++) { if (arr[j]>arr[i]) chet^=1; } } n = scanner.nextInt(); for (int i = 0; i < n; i++) { int l = scanner.nextInt(); int r = scanner.nextInt(); if ((((r-l+1)/2)&1)!=0){ chet^=1; } if (chet==1){ System.out.println("odd"); }else{ System.out.println("even"); } } } }
quadratic
911_D. Inversion Counting
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_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author xwchen */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); String s = in.next(); int[] cnt = new int[26]; int[] cnt2 = new int[26]; int j = 0; int res = n; HashSet<Character> set = new HashSet<Character>(); for (char c : s.toCharArray()) { set.add(c); } int m = set.size(); for (int i = 0; i < n; ++i) { if (Character.isLowerCase(s.charAt(i))) { cnt[s.charAt(i) - 'a']++; } else { cnt2[s.charAt(i) - 'A']++; } while (isOK(cnt, cnt2, m)) { res = Math.min(res, i - j + 1); if (Character.isLowerCase(s.charAt(j))) { cnt[s.charAt(j) - 'a']--; } else { cnt2[s.charAt(j) - 'A']--; } ++j; } } out.println(res); } boolean isOK(int[] cnt, int[] cnt2, int m) { int c = 0; for (int i = 0; i < 26; ++i) { if (cnt[i] > 0) { ++c; } } for (int i = 0; i < 26; ++i) { if (cnt2[i] > 0) { ++c; } } return c >= m; } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.*; public class ErrorCorrectSystem { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String a = scan.next(); String b = scan.next(); int[][] mismatch = new int[26][26]; for(int i = 0; i < 26; i++) Arrays.fill(mismatch[i], -1); int[][] pair = new int[2][26]; for(int i = 0; i < 2; i++) Arrays.fill(pair[i], -1); int hd = 0; for(int i = 0; i < n; i++) { if(a.charAt(i) != b.charAt(i)) { hd++; mismatch[a.charAt(i)-'a'][b.charAt(i)-'a'] = i; pair[0][a.charAt(i)-'a'] = i; pair[1][b.charAt(i)-'a'] = i; } } for(int i = 0; i < 26; i++) { for(int j = i+1; j < 26; j++) { if(mismatch[i][j] > -1 && mismatch[j][i] > -1) { System.out.println(hd-2); System.out.println((mismatch[i][j]+1)+" "+(mismatch[j][i]+1)); return; } } } for(int i = 0; i < n; i++) { if(a.charAt(i) != b.charAt(i)) { //try a gets b's letter if(pair[0][b.charAt(i)-'a'] > -1) { System.out.println(hd-1); System.out.println((i+1)+" "+(pair[0][b.charAt(i)-'a']+1)); return; } } } System.out.println(hd); System.out.println("-1 -1"); } }
linear
527_B. Error Correct System
CODEFORCES
import java.util.*; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n= sc.nextInt(); int x= (int)Math.sqrt(n) ; int a[] = new int[n+5]; for(int i=1,o=n,j;i<=n;i+=x) for(j=(int)Math.min(i+x-1,n);j>=i;a[j--]=o--); for(int i=1;i<=n;i++)System.out.print(a[i]+" "); System.out.println(); } }
linear
1017_C. The Phone Number
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); long n = in.nextLong(); long k = in.nextLong(); long res = solve(n, k); System.out.println(res); } private static long solve(long n, long k) { return solveEq(1, -3 - 2 * n, n * n + n - 2 * k); } private static long solveEq(long a, long b, long c) { long delta = b * b - 4 * a * c; return (-b - (long)Math.sqrt(delta)) / (2 * a); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.*; import java.util.*; public class Main { static BufferedReader f; static StringTokenizer st; public static void main (String [] args) throws Exception { // Use BufferedReader rather than RandomAccessFile; it's much faster f = new BufferedReader(new java.io.InputStreamReader(System.in)); long unixTime = System.currentTimeMillis(); long l=nextLong(); long r=nextLong(); String ll=Long.toBinaryString(l); String rr=Long.toBinaryString(r); System.err.println(ll); System.err.println(rr); System.err.println(Long.parseLong(rr,2)); int len=0; if(ll.length()!=rr.length()){ len=Math.max(ll.length(),rr.length()); }else{ //same for(int i=0;i<ll.length();i++){ if(ll.charAt(i)!=rr.charAt(i)){ len=ll.length()-i; break; } } } System.err.println(len); //long out=0; StringBuffer s=new StringBuffer(); for(int i=0;i<len;i++){ //out+=Math.pow(2, i); s.append(1); } if(len==0){ System.out.println(0); }else{ System.out.println(Long.parseLong(s.toString(),2)); } // System.out.println("Time elapsed (ms): "+(System.currentTimeMillis()-unixTime)); System.exit(0); // don't omit this! } //Library static long nextLong() throws Exception{ return Long.parseLong(next()); } static int nextInt() throws Exception { return Integer.parseInt(next()); } static String next() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(f.readLine()); } return st.nextToken(); } } class ii{ int a; int b; public ii(int a, int b){ this.a=a; this.b=b; } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.util.*; public class IQ { public static void main(String[] args) { Scanner sc=new Scanner(System.in); ArrayList<Integer> e=new ArrayList<Integer>(); ArrayList<Integer> o=new ArrayList<Integer>(); int size=sc.nextInt(); for(int w=0;w<size;w++) { int x=sc.nextInt(); if(x%2==0)e.add(w+1); else o.add(w+1); } if(e.size()==1)System.out.println(e.get(0)); else System.out.println(o.get(0)); } }
linear
25_A. IQ test
CODEFORCES
import java.util.*; public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int[] a=new int[1010]; while(in.hasNext()){ int n=in.nextInt(); String s=in.next(); int sum=0; for(int i=0;i<n;++i){ if(s.charAt(i)=='H'){ a[i]=1; ++sum; } else a[i]=0; } int min=10010; for(int i=0;i<n-sum;++i){ int count=0; for(int j=i+sum;j<n;++j){ if(a[j]==1)++count; } for(int j=0;j<i;++j){ if(a[j]==1)++count; } if(count<min)min=count; } sum=n-sum; for(int i=0;i<n-sum;++i){ int count=0; for(int j=i+sum;j<n;++j){ if(a[j]==0)++count; } for(int j=0;j<i;++j){ if(a[j]==0)++count; } if(count<min)min=count; } System.out.println(min); } } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.*; import java.util.*; import java.util.function.Function; public class Main { static int N; static int[] U, V; static int[] A; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); N = sc.nextInt(); U = new int[N-1]; V = new int[N-1]; for (int i = 0; i < N - 1; i++) { U[i] = sc.nextInt()-1; V[i] = sc.nextInt()-1; } A = sc.nextIntArray(N, -1); System.out.println(solve() ? "Yes" : "No"); } static boolean solve() { if( A[0] != 0 ) return false; int[][] G = adjB(N, U, V); Map<Integer, Integer> parents = new HashMap<>(); for (Node node : orderFromRoot(N, G, 0)) { parents.put(node.a, node.parent); } ArrayDeque<Integer> q = new ArrayDeque<>(); for (int next : G[0]) { q.add(0); } int idx = 1; while(!q.isEmpty()) { int p = q.poll(); int a = A[idx++]; if( parents.get(a) != p ) { return false; } for (int next : G[a]) { if( next == p ) continue; q.add(a); } } return true; } static int[][] adjB(int n, int[] from, int[] to) { int[][] adj = new int[n][]; int[] cnt = new int[n]; for (int f : from) { cnt[f]++; } for (int t : to) { cnt[t]++; } for (int i = 0; i < n; i++) { adj[i] = new int[cnt[i]]; } for (int i = 0; i < from.length; i++) { adj[from[i]][--cnt[from[i]]] = to[i]; adj[to[i]][--cnt[to[i]]] = from[i]; } return adj; } static Node[] orderFromRoot(int N, int[][] G, int root) { ArrayDeque<Node> q = new ArrayDeque<>(); Node[] ret = new Node[N]; int idx = 0; q.add(new Node(-1, root)); while(!q.isEmpty()) { Node n = q.poll(); ret[idx++] = n; for (int next : G[n.a]) { if( next == n.parent ) continue; q.add(new Node(n.a, next)); } } return ret; } static class Node { int parent, a; public Node(int parent, int a) { this.parent = parent; this.a = a; } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
nlogn
1037_D. Valid BFS?
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class A implements Runnable { static BufferedReader in; static PrintWriter out; static StringTokenizer st; static Random rnd; void solve() throws IOException { int n = nextInt(); long k = nextLong(); if (k == 1) { out.println(n); } else { TreeMap<Long, ArrayList<Integer>> numbers = new TreeMap<Long, ArrayList<Integer>>(); for (int i = 0; i < n; i++) { long m = nextLong(); int howMuch = 0; while (m % k == 0) { m /= k; ++howMuch; } if (!numbers.containsKey(m)) { numbers.put(m, new ArrayList<Integer>()); } numbers.get(m).add(howMuch); } int res = 0; for (ArrayList<Integer> oneGroup : numbers.values()) { res += parseOneGroup(oneGroup); } out.println(res); } } private int parseOneGroup(ArrayList<Integer> oneGroup) { Collections.sort(oneGroup); int res = 0, prevValue = Integer.MIN_VALUE; for (int i = 0; i < oneGroup.size(); i++) { int curValue = oneGroup.get(i); if (prevValue + 1 != curValue) { ++res; prevValue = curValue; } } return res; } public static void main(String[] args) { new A().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); rnd = new Random(); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(42); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class EhabAndAnotherAnotherXorProblem implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { int initial = ask(0, 0); int a = 0, b = 0; if (initial == 0) { for (int i = 0; i < 30; i++) { int response = ask(1 << i, 0); if (response == -1) { a |= (1 << i); } } b = a; } else { for (int i = 29; i >= 0; i--) { int response = ask(a | (1 << i), b | (1 << i)); if (response != initial) { if (response == 1) { b |= (1 << i); } else { a |= (1 << i); } initial = ask(a, b); } else { response = ask(a | (1 << i), b); if (response == -1) { a |= (1 << i); b |= (1 << i); } } } } answer(a, b); } private int ask(int c, int d) { out.printf("? %d %d\n", c, d); out.flush(); return in.ni(); } private void answer(int a, int b) { out.printf("! %d %d\n", a, b); out.flush(); } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (EhabAndAnotherAnotherXorProblem instance = new EhabAndAnotherAnotherXorProblem()) { instance.solve(); } } }
logn
1088_D. Ehab and another another xor problem
CODEFORCES
import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { Scanner c=new Scanner(System.in); int N=c.nextInt(); int A[]=new int[N]; for(int i=0;i<N;i++) { A[i]=c.nextInt(); } Arrays.sort(A); int sum=0; for(int i=0;i<N;i++) { sum+=A[i]; } int my=0; int coins=0; for(int i=N-1;i>=0;i--) { coins++; //include coin i my+=A[i]; if(my>sum-my) { System.out.println(coins); break; } } } } //must declare new classes here
nlogn
160_A. Twins
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception { //System.setIn(new FileInputStream("1")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } private static void solve() throws Exception { int n = nextInt(); boolean[] use = new boolean[500]; ArrayList<Integer> a = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int v = nextInt(); if (!use[250 + v]) { use[250 + v] = true; a.add(v); } } Collections.sort(a); if (a.size() < 2) { out.println("NO"); } else { out.println(a.get(1)); } } static BufferedReader in; static PrintWriter out; static StringTokenizer st; static String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextString()); } static double nextDouble() throws IOException { return Double.parseDouble(nextString()); } }
nlogn
22_A. Second Order Statistics
CODEFORCES