src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
/** * Created with IntelliJ IDEA. * User: Venky */ import java.io.*; import java.util.StringTokenizer; public class Main { static void solve() throws IOException { String str = br.readLine(); StringBuffer sb1 = new StringBuffer(str); StringBuffer sb2 = new StringBuffer(str); StringBuffer sb3 = new StringBuffer(str); sb1.deleteCharAt(sb1.length()-1); sb2.deleteCharAt(sb2.length()-2); int n1 = Integer.parseInt(sb1.toString()); int n2 = Integer.parseInt(sb2.toString()); int n3 = Integer.parseInt(sb3.toString()); out.println(Math.max(n1, Math.max(n2, n3))); } static BufferedReader br; static StringTokenizer st; static PrintWriter out; public static void main(String[] args) throws IOException { InputStream input = System.in; br = new BufferedReader(new InputStreamReader(input)); out = new PrintWriter(System.out); solve(); out.close(); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class P015A { public static void main(String[] args) { Scanner inScanner = new Scanner(System.in); int n = inScanner.nextInt(); int t = inScanner.nextInt(); House[] houses = new House[n]; for (int i = 0; i < n; i++) houses[i] = new House(inScanner.nextInt(), inScanner.nextInt()); Arrays.sort(houses); int sum = 2; for (int i = 1; i < n; i++) { double space = houses[i].leftX - houses[i - 1].rightX; if (space >= t) sum++; if (space > t) sum++; } System.out.println(sum); } private static class House implements Comparable<House> { int x; double leftX; double rightX; public House(int x, int size) { super(); this.x = x; leftX = x - (double) size / 2; rightX = x + (double) size / 2; } @Override public int compareTo(House o) { return x - o.x; } } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; public class a { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); double w = in.nextDouble(); int tot = 2; Interval[] houses = new Interval[n]; for(int i=0; i<n; i++) { double center = in.nextDouble(); double wid = in.nextDouble(); houses[i] = new Interval(center-wid/2,center+wid/2); } Arrays.sort(houses); for(int i=1; i<n; i++) { double dist = houses[i].s - houses[i-1].e; if(dist+1e-6 >= w) { tot+=2; if(Math.abs(w-dist) < 1e-6) tot--; } } System.out.println(tot); } } class Interval implements Comparable<Interval> { double s, e; Interval(double a, double b) { s=a; e=b; } public int compareTo(Interval i) { return (int)Math.signum(s-i.s); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; public class Blah { public static void main(String args[]) { Scanner c = new Scanner(System.in); String number = c.nextLine(); int i = Integer.parseInt(number); if (i == 1) { System.out.println("NO"); return; } String line = c.nextLine(); String[] arr = line.split(" "); int[] array = new int[i]; for (int j = 0; j < i; j++) { array[j] = Integer.parseInt(arr[j]); } int min = array[0]; int second = 0; boolean thing = false; for (int j = 0; j < i; j++) { if (!thing && array[j] > min) { second = array[j]; thing = true; } if (array[j] < min) { second = min; min = array[j]; thing = true; } else if (thing && array[j] > min && array[j] < second) second = array[j]; } if (!thing) System.out.println("NO"); else System.out.println(second); return; } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.*; import java.util.*; public class Solution { static boolean canWinFromOneMove(char []s,int k) { int prefix=0; int n=s.length; for(int i=0;i<n && s[i]==s[0];i++) prefix++; int suffix=0; for(int i=n-1;i>=0 && s[i]==s[n-1];i--) suffix++; return s[0]==s[n-1] && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(),k=sc.nextInt(); char []s=sc.next().toCharArray(); if(canWinFromOneMove(s, k)) { System.out.println("tokitsukaze"); return; } int []suff=new int [n+1]; suff[n-1]=1; for(int i=n-2;i>=0;i--) { suff[i]=1+(s[i+1]==s[i]?suff[i+1]:0); } for(int i=n-2;i>=0;i--) suff[i]=Math.max(suff[i], suff[i+1]); int max=0,curr=0; boolean draw=false; int ones=0; for(int i=0;i+k<=n;i++) { // one int prefix=ones==i?k+ones:max; int suffix=i+k==n?k:s[i+k]=='1' && suff[i+k]==n-(i+k)?k+suff[i+k]:suff[i+k]; char first=i==0?'1':s[0],last=i+k==n?'1':s[n-1]; boolean zero=first==last && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n; // zero prefix=ones==0?k+ones:max; suffix=i+k==n?k:s[i+k]=='0' && suff[i+k]==n-(i+k)?k+suff[i+k]:suff[i+k]; first=i==0?'0':s[0]; last=i+k==n?'0':s[n-1]; boolean one=first==last && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n; if(!zero || !one) { // System.err.println(i+1); draw=true; } if(s[i]=='1') ones++; if(i>0 && s[i]==s[i-1] ) curr++; else curr=1; max=Math.max(max, curr); } out.println(draw?"once again":"quailty"); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
linear
1190_C. Tokitsukaze and Duel
CODEFORCES
import java.util.Arrays; import java.util.Locale; import java.util.Scanner; public class Fish { public static void main(String[] args) { Scanner in = new Scanner(System.in); in.useLocale(Locale.US); int n = in.nextInt(); double[] dp = new double[1 << n]; Arrays.fill(dp, 0); dp[(1 << n) - 1] = 1;//? double[][] prob = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { prob[i][j] = in.nextDouble(); } } for (int t = (1 << n) - 1; t >= 0; t--) { int k = Integer.bitCount(t); for (int i = 0; i < n; i++) { if ((t & (1 << i)) > 0) { for (int j = 0; j < n; j++) { if ((t & (1 << j)) > 0) { if (i != j) { dp[t - (1 << j)] += dp[t] * prob[i][j] / (k*(k-1)/2); } } } } } } for (int i = 0; i < n; i++) { System.out.print(dp[1 << i] + " "); } } }
np
16_E. Fish
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SFly { public static void main(String[] args) throws IOException { BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); int planet = Integer.parseInt(lector.readLine()); int ini = Integer.parseInt(lector.readLine()); double peso = ini; int[] desp = new int[planet]; int[] ater = new int[planet]; String[] temp = lector.readLine().split(" "); for(int i=0; i<planet; i++) { desp[i] = Integer.parseInt(temp[i]); if(desp[i] == 1) { System.out.println(-1); lector.close(); return; } } temp = lector.readLine().split(" "); for(int i=0; i<planet; i++) { ater[i] = Integer.parseInt(temp[i]); if(ater[i] == 1) { System.out.println(-1); lector.close(); return; } } temp = null; int i=planet-1; peso = (peso*ater[0])/(ater[0]-1); while(i>0) { peso = (peso*desp[i])/(desp[i]-1); peso = (peso*ater[i])/(ater[i]-1); i--; } peso = (peso*desp[0])/(desp[0]-1); peso = peso - ini; System.out.println(peso); lector.close(); } }
linear
1010_A. Fly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { public static void main(String[] args){ FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(); int[] a = new int[n+1]; for(int i = 1; i <= n; i++) a[i] = scan.nextInt(); BIT bit = new BIT(n); int p = 0; for(int i = 1; i <= n; i++) { p ^= bit.atOrAbove(a[i])&1; bit.add(a[i], 1); } int m = scan.nextInt(); for(int i = 0; i < m; i++) { int l = scan.nextInt(), r = scan.nextInt(); int s = r-l+1; int in = s*(s-1)/2; if((in&1) == 1) p ^= 1; out.println(p==0?"even":"odd"); } out.close(); } static class BIT { int[] a; int n; public BIT(int n) { this.n = n; a = new int[n+1]; } public void add(int i, int val) { while(i <= n) { a[i] += val; i += i & -i; } } public int sum(int j) { int res = 0; for(int i = j; i >= 1; i -= (i & -i)) res += a[i]; return res; } public int sum(int i, int j) { return sum(j)-sum(i-1); } public int atOrAbove(int index) { int sub = 0; if (index > 0) sub = sum(index-1); return sum(n) - sub; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n){ long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextDoubleArray(int n){ double[] a = new double[n]; for(int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char[][] nextGrid(int n, int m){ char[][] grid = new char[n][m]; for(int i = 0; i < n; i++) grid[i] = next().toCharArray(); return grid; } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(),r=in.nextInt(); double[] x=new double[n]; for(int i=0; i<n; i++) x[i]=in.nextInt(); double[] y=new double[n]; for(int i=0; i<n; i++) { y[i]=r; for(int j=0; j<i; j++) { if(Math.abs(x[j]-x[i])<=2*r) { y[i]=Math.max(y[i], y[j]+Math.sqrt(4*r*r-(x[i]-x[j])*(x[i]-x[j]))); } } } for(int i=0; i<n; i++) System.out.print(y[i]+" "); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; /* height == 2, width == 3 2 3 2 1 1 1 1 1 1 1 */ public class D { public static void main(String[] args) { FastScanner fs=new FastScanner(); int h=fs.nextInt(), w=fs.nextInt(), k=fs.nextInt(); PrintWriter out=new PrintWriter(System.out); if (k%2==1) { for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { if (x!=0) out.print(" "); out.print(-1); } out.println(); } out.close(); return; } k/=2; int[][] rightCost=new int[w-1][h]; int[][] downCost=new int[w][h-1]; for (int y=0; y<h; y++) for (int x=0; x<w-1; x++) rightCost[x][y]=fs.nextInt(); for (int y=0; y<h-1; y++) for (int x=0; x<w; x++) downCost[x][y]=fs.nextInt(); long[][] dp=new long[w][h]; long[][] dpNext=new long[w][h]; for (int i=0; i<k; i++) { for (int x=0; x<w; x++) { for (int y=0; y<h; y++) { long ans=(long)1e18; if (x!=0) ans=Math.min(ans, dp[x-1][y]+rightCost[x-1][y]); if (y!=0) ans=Math.min(ans, dp[x][y-1]+downCost[x][y-1]); if (x!=w-1) ans=Math.min(ans, dp[x+1][y]+rightCost[x][y]); if (y!=h-1) ans=Math.min(ans, dp[x][y+1]+downCost[x][y]); dpNext[x][y]=ans; } } dp=dpNext; dpNext=new long[w][h]; } //TODO: double answer for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { if (x!=0) out.print(" "); out.print(2*dp[x][y]); } out.println(); } out.close(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; public class E { public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { readInput(); out.close(); } static long[][] dp; static int n; static long m; static long pow(long b, long e) { if (e== 0) return 1; long r= pow(b,e/2); r = r * r % m; if ((e&1)==1) return r *b%m; return r; } static long modinv(long a) {return pow(a,m-2);} static long solve(int len, int num) { if (len == -1 && num == -1) return 1; if (num < 0 || len <= 0) return 0; if (dp[len][num] == -1) { dp[len][num] = 0; for (int i = 0; i < len; i++) { if (i == 1) continue; long sol = pow[len-i-1]*solve(i-1,num-1)%m; sol = sol * faci[len-i]% m; dp[len][num] += sol; dp[len][num] %= m; } } return dp[len][num]; } static long[] fac, faci, pow; public static void readInput() throws IOException { // br = new BufferedReader(new FileReader(".in")); // out = new PrintWriter(new FileWriter(".out")); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); m = Long.parseLong(st.nextToken()); fac = new long[500]; pow = new long[500]; faci = new long[fac.length]; fac[0] = pow[0] = 1; faci[0] = modinv(fac[0]); for (int i = 1; i < fac.length; i++) { fac[i] = fac[i-1]*i%m; faci[i] = modinv(fac[i]); pow[i] = pow[i-1] * 2 % m; } dp = new long[n+1][n+1]; for (long[] a: dp) Arrays.fill(a, -1); // Number of ways to make a segment of length x is 2^(x-1) // DP: Given position I. long ans =0 ; for (int i = 0 ; i <= n/2+1; i++) { //System.out.println(i + ": " + solve(n,i) + " " + (n-i) + " " + (i)); long sol = solve(n,i) * fac[n-i]; sol %= m; ans += sol; } out.println(ans%m); } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.io.* ; import java.util.* ; import java.text.* ; import java.math.* ; import static java.lang.Math.min ; import static java.lang.Math.max ; public class Codeshefcode{ public static void main(String[] args) throws IOException{ // Solver Machine = new Solver() ; // Machine.Solve() ; // Machine.Finish() ; new Thread(null,new Runnable(){ public void run(){ Solver Machine = new Solver() ; try{ Machine.Solve() ; Machine.Finish() ; }catch(Exception e){ e.printStackTrace() ; System.out.flush() ; System.exit(-1) ; }catch(Error e){ e.printStackTrace() ; System.out.flush() ; System.exit(-1) ; } } },"Solver",1l<<27).start() ; } } class Mod{ static long mod=1000000007 ; static long d(long a,long b){ return (a*MI(b))%mod ; } static long m(long a,long b){ return (a*b)%mod ; } static private long MI(long a){ return pow(a,mod-2) ; } static long pow(long a,long b){ if(b<0) return pow(MI(a),-b) ; long val=a ; long ans=1 ; while(b!=0){ if((b&1)==1) ans = (ans*val)%mod ; val = (val*val)%mod ; b/=2 ; } return ans ; } } class pair implements Comparable<pair>{ int x ; int y ; pair(int x,int y){ this.x=x ; this.y=y ;} public int compareTo(pair p){ return (this.x<p.x ? -1 : (this.x>p.x ? 1 : (this.y<p.y ? -1 : (this.y>p.y ? 1 : 0)))) ; } } class Solver{ Reader ip = new Reader(System.in) ; PrintWriter op = new PrintWriter(System.out) ; public void Solve() throws IOException{ int n = ip.i() ; int a[] = new int[n] ; for(int i=0 ; i<n ; i++) a[i] = ip.i() ; int num=0 ; for(int i=0 ; i<n ; i++) for(int j=(i+1) ; j<n ; j++) if(a[i]>a[j]) num++ ; num%=2 ; int m = ip.i() ; while(m--!=0){ int l = ip.i() ; int r = ip.i() ; int d = (r-l+1) ; int mod = d%4 ; int bit ; if(mod<=1) bit=0 ; else bit=1 ; num+=bit ; num%=2 ; pln(num==1 ? "odd" : "even") ; } } void Finish(){ op.flush(); op.close(); } void p(Object o){ op.print(o) ; } void pln(Object o){ op.println(o) ; } } class mylist extends ArrayList<Integer>{} class myset extends TreeSet<Integer>{} class mystack extends Stack<Integer>{} class mymap extends TreeMap<Long,Integer>{} class Reader { BufferedReader reader; StringTokenizer tokenizer; Reader(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer("") ; } String s() throws IOException { while (!tokenizer.hasMoreTokens()){ tokenizer = new StringTokenizer( reader.readLine()) ; } return tokenizer.nextToken(); } int i() throws IOException { return Integer.parseInt(s()) ; } long l() throws IOException{ return Long.parseLong(s()) ; } double d() throws IOException { return Double.parseDouble(s()) ; } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author cunbidun */ 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); BSportMafia solver = new BSportMafia(); solver.solve(1, in, out); out.close(); } static class BSportMafia { private InputReader in; private OutputWriter out; public void solve(int testNumber, InputReader in, OutputWriter out) { this.in = in; this.out = out; long n = in.nextInt(); long k = in.nextInt(); for (long i = 1; i * (i + 1) / 2 + i <= n + k; i++) { if (i * (i + 1) / 2 + i == n + k) { out.println(n - i); return; } } } } static class InputReader extends InputStream { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class OutputWriter { private final PrintWriter out; public OutputWriter(OutputStream outputStream) { out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.out = new PrintWriter(writer); } public void close() { out.close(); } public void println(long i) { out.println(i); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.Scanner; public class Pipeline { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long k = sc.nextLong(); sc.close(); if (k * (k - 1) / 2 + 1 < n) { System.out.println(-1); } else { long l = -1, r = k; while (r - l > 1) { long m = (r + l) / 2; if (cantidadPosible(k, m) >= n) { r = m; } else { l = m; } } System.out.println(r); } } private static long cantidadPosible(long k, long usadas) { return (k * (k - 1) / 2 + 1 - (k - usadas) * (k - usadas - 1) / 2); } }
logn
287_B. Pipeline
CODEFORCES
import static java.math.BigInteger.*; import static java.util.Arrays.*; import java.io.*; import java.lang.reflect.*; import java.util.*; public class A { final int MOD = (int)1e9 + 7; final double eps = 1e-12; final int INF = (int)1e9; public A () { int N = sc.nextInt(); int K = sc.nextInt(); Long [] A = sc.nextLongs(); sort(A); Set<Long> S = new HashSet<Long>(); for (long a : A) { if (a % K == 0 && S.contains(P * (a/K))) continue; S.add(P*a); } int res = S.size(); exit(res); } long P = probablePrime(50, new Random()).longValue(); //////////////////////////////////////////////////////////////////////////////////// /* Dear hacker, don't bother reading below this line, unless you want to help me debug my I/O routines :-) */ static MyScanner sc = new MyScanner(); static class MyScanner { public String next() { newLine(); return line[index++]; } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { line = null; return readLine().split(" "); } public char [] nextChars() { return next().toCharArray(); } public Integer [] nextInts() { String [] L = nextStrings(); Integer [] res = new Integer [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } public Long [] nextLongs() { String [] L = nextStrings(); Long [] res = new Long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } public Double [] nextDoubles() { String [] L = nextStrings(); Double [] res = new Double [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Double.parseDouble(L[i]); return res; } public String [] next (int N) { String [] res = new String [N]; for (int i = 0; i < N; ++i) res[i] = sc.next(); return res; } public Integer [] nextInt (int N) { Integer [] res = new Integer [N]; for (int i = 0; i < N; ++i) res[i] = sc.nextInt(); return res; } public Long [] nextLong (int N) { Long [] res = new Long [N]; for (int i = 0; i < N; ++i) res[i] = sc.nextLong(); return res; } public Double [] nextDouble (int N) { Double [] res = new Double [N]; for (int i = 0; i < N; ++i) res[i] = sc.nextDouble(); return res; } public String [][] nextStrings (int N) { String [][] res = new String [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextStrings(); return res; } public Integer [][] nextInts (int N) { Integer [][] res = new Integer [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextInts(); return res; } public Long [][] nextLongs (int N) { Long [][] res = new Long [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextLongs(); return res; } public Double [][] nextDoubles (int N) { Double [][] res = new Double [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextDoubles(); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error(e); } } private final BufferedReader r; MyScanner () { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = readLine().split(" "); index = 0; } } } static void print(Object o, Object... a) { printDelim(" ", o, a); } static void cprint(Object o, Object... a) { printDelim("", o, a); } static void printDelim (String delim, Object o, Object... a) { pw.println(build(delim, o, a)); } static void exit (Object o, Object... a) { print(o, a); exit(); } static void exit () { pw.close(); System.out.flush(); System.err.println("------------------"); System.err.println("Time: " + ((millis() - t) / 1000.0)); System.exit(0); } void NO() { throw new Error("NO!"); } //////////////////////////////////////////////////////////////////////////////////// static String build(String delim, Object o, Object... a) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : a) append(b, p, delim); return b.toString().trim(); } static void append(StringBuilder b, Object o, String delim) { if (o.getClass().isArray()) { int L = Array.getLength(o); for (int i = 0; i < L; ++i) append(b, Array.get(o, i), delim); } else if (o instanceof Iterable<?>) { for (Object p : (Iterable<?>)o) append(b, p, delim); } else b.append(delim).append(o); } //////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new A(); exit(); } static void start() { t = millis(); } static PrintWriter pw = new PrintWriter(System.out); static long t; static long millis() { return System.currentTimeMillis(); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class F11141 { static class Solver { ArrayList<int[]> ranges[]; HashMap<Long, Integer> hm = new HashMap<>(); int id(long s) { if (!hm.containsKey(s)) hm.put(s, hm.size()); return hm.get(s); } // max disjoint range set in ranges[r] int[] memo; int go(int r) { memo[N] = 0; int last = N; for(int[] a : ranges[r]) { while(a[0] < last) { memo[last - 1] = memo[last]; last--; } memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1])); last = a[0]; } while(0 < last) { memo[last - 1] = memo[last]; last--; } return memo[0]; } ArrayDeque<int[]> ans = new ArrayDeque<>(); void go2(int r) { memo[N] = 0; int last = N; int minAt[] = new int[N], oo = 987654321; Arrays.fill(minAt, oo); for(int[] a : ranges[r]) { minAt[a[0]] = Math.min(minAt[a[0]], a[1] - a[0]); while(a[0] < last) { memo[last - 1] = memo[last]; last--; } memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1])); last = a[0]; } while(0 < last) { memo[last - 1] = memo[last]; last--; } int k = 0; for(; k < N;) { if(minAt[k] == oo || memo[k] != 1 + memo[k + minAt[k] + 1]) k++; else { ans.push(new int[] {k, k + minAt[k]}); k += minAt[k] + 1; } } } @SuppressWarnings("unchecked") Solver() { ranges = new ArrayList[2250001]; for (int i = 0; i < ranges.length; i++) ranges[i] = new ArrayList<>(); } int N, LID; long[] a; void solve(Scanner s, PrintWriter out) { N = s.nextInt(); a = new long[N + 1]; for (int i = 1; i <= N; i++) a[i] = s.nextLong() + a[i - 1]; for (int i = N; i >= 1; i--) for (int j = i; j <= N; j++) { int x = id(a[j] - a[i - 1]); ranges[x].add(new int[] { i - 1, j - 1 }); } int best = 0, bid = -1; memo = new int[N + 1]; Arrays.sort(ranges, (a, b) -> b.size() - a.size()); for(int i = 0; i < ranges.length; i++, LID++) { if(ranges[i].size() <= best) break; int ans = go(i); if(ans > best) { best = ans; bid = i; } } // backtrack on bid out.println(best); go2(bid); while(!ans.isEmpty()) { int[] c = ans.pop(); out.println(++c[0] + " " + ++c[1]); } } } public static void main(String[] args) { Scanner s = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(); solver.solve(s, out); out.close(); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.*; import java.util.*; public class Main { class node{ int data; node next; public node(int val){ data=val; next=null; } } class linkedlist{ node start; node end; int size; int turn; public linkedlist(){ start=null; end=null; size=0; } void add(int val){ if(size==0){ node t=new node(val); start=t; end=t; size++; } else{ node t=new node(val); end.next=t; end=end.next; size++; } } void myfunc(){ if(start.data>start.next.data){ // System.out.println("me ni hu"); node t=new node(start.next.data); start.next=start.next.next; end.next=t; end=end.next; } else{ // System.out.println("me hu"); int t=start.data; start=start.next; add(t); size--; } } int findmax(){ int m=0; node temp=start; for(int i=0;i<size;i++){ if(temp.data>m){ m=temp.data; } temp=temp.next; } return m; } void display(){ node temp=start; for(int i=0;i<size;i++){ System.out.print(temp.data+" "); temp=temp.next; } System.out.println(""); } } linkedlist l; public Main(){ l=new linkedlist(); } public static void main(String [] argv) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); Main ma=new Main(); String[] l1=in.readLine().split(" "); int n=Integer.parseInt(l1[0]); int q=Integer.parseInt(l1[1]); String[] ar=in.readLine().split(" "); int a1=Integer.parseInt(ar[0]); int b1=Integer.parseInt(ar[1]); for(int i=0;i<n;i++){ ma.l.add(Integer.parseInt(ar[i])); } int m=ma.l.findmax(); int[][] pair=new int[n][2]; int t=0; for(int i=0;i<n;i++){ if(ma.l.start.data==m) break; ma.l.myfunc(); pair[t][0]=ma.l.start.data; pair[t][1]=ma.l.start.next.data; t++; } int rl[]=new int[n]; node temp=ma.l.start; for(int i=0;i<n;i++){ rl[i]=temp.data; temp=temp.next; } for(int i=0;i<q;i++){ long a=Long.parseLong(in.readLine()); if(a==1){ System.out.println(a1 + " " + b1); } else{ if(a<=t+1){ System.out.println(pair[(int)(a-2)][0]+" "+pair[(int)(a-2)][1]); } else{ if((a-t)%(n-1)==0){ System.out.println(rl[0]+" "+rl[n-1]); } else{ System.out.println(rl[0]+" "+rl[(int)((a-t)%(n-1))]); } } } } } }
linear
1179_A. Valeriy and Deque
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayDeque; import java.util.Arrays; public class Main { private static StreamTokenizer in; private static PrintWriter out; private static int nextInt() throws Exception { in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } public static void main(String[] args) throws Exception { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); int n = nextInt(); int[] a = new int[n]; for (int i=0; i<n; i++) a[i] = nextInt(); Arrays.sort(a); int u = a[0]; for (int i=0; i<n; i++) if (a[i]>u) { out.println(a[i]); out.flush(); return; } out.println("NO"); out.flush(); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); TreeSet<Integer> set = new TreeSet<Integer>(); for(int i=0;i<n;i++){ set.add(sc.nextInt()); } if(set.size() >= 2) System.out.println(set.toArray()[1]); else System.out.println("NO"); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.*; import java.util.StringTokenizer; /** * Author: Maksim Novik * Date: 30.06.12 * Time: 22:34 */ public class Round125ProblemA { public static void main(String[] args) { InputStream in = System.in; OutputStream out = System.out; InputReader reader = new InputReader(in); PrintWriter writer = new PrintWriter(out); solve(reader, writer); writer.close(); } static void solve(InputReader in, PrintWriter out) { long fib = in.nextLong(); out.write("" + 0 + " " + 0 + " " + fib); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import sun.reflect.generics.tree.Tree; import java.io.*; import java.util.*; public class A2 { static Scanner in; static int next() throws Exception {return in.nextInt();}; // static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} // static BufferedReader in; static PrintWriter out; public static void main(String[] args) throws Exception { in = new Scanner(System.in); // in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = next(), a = next(), b = next(); int h[] = new int[n]; for (int i = 0;i < n;i++) h[i] = next(); Arrays.sort(h); int res = h[b] - h[b-1]; out.println(res); out.println(); out.close(); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class G1 { static final int mod = (int) (1e9 + 7); static final int UNCALC = -1; static int[][][] memo; static int n, t[], genre[]; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); t = new int[n]; int T = sc.nextInt(); genre = new int[n]; for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); genre[i] = sc.nextInt(); } memo = new int[4][1 << n][T+1]; for (int[][] a : memo) for (int[] b : a) Arrays.fill(b, UNCALC); out.println(dp(0, 0, T)); out.flush(); out.close(); } static int dp(int last, int mask, int rem) { if (rem==0) return 1; if (memo[last][mask][rem] != UNCALC) return memo[last][mask][rem]; int cnt = 0; for (int i = 0; i < n; i++) { if (genre[i] == last || t[i] > rem || (mask & 1 << i) != 0) continue; cnt = (cnt + dp(genre[i], mask | 1 << i, rem - t[i]))%mod; } return memo[last][mask][rem] = cnt; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.InputMismatchException; import java.util.LinkedList; public class D { static LinkedList<Integer>[] E; static int[] M; static boolean[] visited; static int n; static int center; public static boolean match(int x) { if (visited[x]) return false; visited[x] = true; for (int y : E[x]) if (y != center && (M[y] == -1 || match(M[y]))) { M[y] = x; return true; } return false; } public static int maxMatch() { int res = 0; Arrays.fill(M, -1); for (int i = 0; i < n; i++) { Arrays.fill(visited, false); if (i != center && match(i)) res++; } return res; } public static void main(String[] args) { InputReader in = new InputReader(System.in); n = in.readInt(); int m = in.readInt(); E = new LinkedList[n]; M = new int[n]; boolean[][] C = new boolean[n][n]; visited = new boolean[n]; for (int i = 0; i < n; i++) E[i] = new LinkedList<Integer>(); for (int i = 0; i < m; i++) { int x = in.readInt() - 1; int y = in.readInt() - 1; C[x][y] = true; E[x].add(y); } int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int res = 0; int all = 0; for (int j = 0; j < n; j++) if (j != i) { all += E[j].size(); if (!C[i][j]) res++; if (!C[j][i]) res++; else all--; } if (!C[i][i]) res++; center = i; int match = maxMatch(); res += (all - match) + (n - match - 1); min = Math.min(min, res); } System.out.println(min); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int 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) { 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; } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.util.Scanner; public class ReallyBigNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long s = sc.nextLong(); long m = s; while(m-digitAdd(m)<s && m<=n){ m++; } System.out.println(Math.max(n-m+1, 0)); } private static int digitAdd(long s){ int sum = 0; for(long i = 0,j=1L;i<(int)Math.log10(s)+1; i++,j*=10){ sum += (s/j)%10; } return sum; } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.math.BigInteger; import java.util.*; public class A { private static Scanner in; final int M = 1000000009; public void run() { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int z = n - m; if (z >= n / k) { System.out.println(m); return; } int f = n - k * z; int ans = BigInteger.ONE.shiftLeft(f / k + 1).remainder(BigInteger.valueOf(M)).intValue(); System.out.println(((ans + M - 2L) * k + (f % k + (k - 1) * z)) % M); } public static void main(String[] args) { Locale.setDefault(Locale.US); in = new Scanner(System.in); new A().run(); in.close(); } }
logn
338_A. Quiz
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class Task1b { static int[] fromRC (String data) { int pos = data.indexOf('C'); int res[] = new int[2]; res[0] = Integer.parseInt(data.substring(1, pos)); res[1] = Integer.parseInt(data.substring(pos + 1)); return res; } static int[] fromXC (String data) { int pos = 0; int res[] = new int[2]; res[0] = res[1] = 0; while (data.charAt(pos) >= 'A' && data.charAt(pos) <= 'Z') { res[1] *= 26; res[1]++; res[1] += data.charAt(pos) - 'A'; pos++; } res[0] = Integer.parseInt(data.substring(pos)); return res; } static String toRC (int[] data) { return String.format("R%dC%d", data[0], data[1]); } static String toXC (int[] data) { StringBuilder sb = new StringBuilder(); while (data[1] > 0) { data[1]--; sb.append((char)('A' + data[1] % 26)); data[1] /= 26; } sb = sb.reverse(); sb.append(data[0]); return sb.toString(); } /** * @param args */ public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); for (int i = 0; i < n; i++) { String s = br.readLine(); if ((s.charAt(0) == 'R') && (s.charAt(1) >= '0' && s.charAt(1) <= '9') && (s.indexOf('C') != -1)) { System.out.println(toXC(fromRC(s))); } else { System.out.println(toRC(fromXC(s))); } } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long l = sc.nextLong(), r = sc.nextLong(); if (l % 2 == 0 && r - l >= 2) { System.out.println(l + " " + (l + 1) + " " + (l + 2)); } else if (l % 2 == 1 && r - l >= 3) { System.out.println(l + 1 + " " + (l + 2) + " " + (l + 3)); } else { System.out.println(-1); } } }
constant
483_A. Counterexample
CODEFORCES
import java.io.*; import java.util.*; public class digits { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long k = Long.parseLong(br.readLine()); long temp = 9 * (int)Math.pow(10,0); int count = 0; long initial = 0; while(k > temp) { count++; initial = temp; temp += 9 * (long)Math.pow(10,count)*(count+1); } long index = (k-initial-1)%(count+1); long num = (long)Math.pow(10,count) + (k-initial-1)/(count+1); System.out.println((num+"").charAt((int)index)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; // Petya and Spiders // 2012/08/16 public class P111C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int h, w; void run(){ h=sc.nextInt(); w=sc.nextInt(); solve(); } void solve(){ n=w*h; g=new long[n]; int[] dx={0, 0, -1, 1}; int[] dy={-1, 1, 0, 0}; for(int y=0; y<h; y++){ for(int x=0; x<w; x++){ for(int k=0; k<4; k++){ int x2=x+dx[k]; int y2=y+dy[k]; if(x2>=0&&x2<w&&y2>=0&&y2<h){ g[y*w+x]|=1L<<(y2*w+x2); } } } } mds=(1L<<n)-1; mds(0, 0, 0); println((n-Long.bitCount(mds))+""); } int n; long[] g; long mds; void mds(long choosed, long removed, long covered){ if(Long.bitCount(choosed)>=Long.bitCount(mds)) return; if(covered==((1L<<n)-1)){ mds=choosed; return; } long s=covered; for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); s|=(1L<<i)|g[i]; } if(s!=((1L<<n)-1)) return; int k=-1; for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); if((covered>>>i&1)==1){ if(Long.bitCount(g[i]&~covered)==0){ mds(choosed, removed|(1L<<i), covered); return; }else if(Long.bitCount(g[i]&~covered)==1 &&(g[i]&~covered&~removed)!=0){ mds(choosed, removed|(1L<<i), covered); return; } }else{ if(Long.bitCount(g[i]&~removed)==0){ mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]); return; }else if(Long.bitCount(g[i]&~removed)==1 &&((g[i]&~removed)|(g[i]&~covered))==(g[i]&~removed)){ int j=Long.numberOfTrailingZeros(g[i]&~removed); mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered |(1L<<j)|g[j]); return; } } if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)) k=i; } if(k==-1) return; mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]); mds(choosed, removed|(1L<<k), covered); } void println(String s){ System.out.println(s); } void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } public static void main(String[] args){ Locale.setDefault(Locale.US); new P111C().run(); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.util.*; import java.io.*; public class Fish { static double[][] prob= new double[18][18]; static double[][] dp= new double[2][1<<18]; static ArrayList<Integer>[] adj= new ArrayList[1<<18]; static int n; public static void init() { for(int i=0; i<(1<<18); i++) adj[i]= new ArrayList<Integer>(); for(int i=0; i<(1<<18); i++) for(int j=0; j<18; j++) if(((i>>j)&1)==1) adj[i].add(i^(1<<j)); } public static double value(int cur, int next) { int i=0; int z= cur^next; double p=0; int alive= Integer.bitCount(cur); while((z>>i)!=1) i++; for(int k=0; k<n; k++) if( ((next>>k)&1)==1) p+= prob[k][i]; p/= alive*(alive-1)/2; return p; } public static void main(String[] args)throws Exception { Scanner scan= new Scanner(System.in); init(); n=scan.nextInt(); int m= (1<<n)-1; for(int i=0; i<n; i++) for(int j=0; j<n; j++) prob[i][j]= scan.nextDouble(); dp[0][m]=1; for(int i=0; i<(n-1); i++) { for(int j=0; j<=m; j++) if(dp[i%2][j]>0) for(Integer next: adj[j]) dp[(i+1)%2][next]+= value(j,next)*dp[i%2][j]; Arrays.fill(dp[i%2],0); } for(int i=0; i<n; i++) { if(i!=0) System.out.print(" "); System.out.printf("%.6f",dp[(n-1)%2][1<<i]); } } }
np
16_E. Fish
CODEFORCES
import java.util.*; public class prob { public static long ans(long x, long y, long p) { long r = 1; x = x % p; while (y > 0) { if((y & 1)==1) r = (r * x) % p; y = y >> 1; x = (x * x) % p; } return r; } public static void main (String[] args) throws java.lang.Exception { Scanner scan = new Scanner(System.in); long x = scan.nextLong(); long k = scan.nextLong(); long v = 1000000007L; if(x>0){ long p = ((2*x)-1)%v; long a = ans(2L,k,v); long b = (p*a)%v; System.out.println((b+1)%v); } else{ System.out.println(0); } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.*; public class inversioncounting { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] permutation = new int[n]; for (int i = 0; i < n; i++) { permutation[i] = sc.nextInt(); } int m = sc.nextInt(); int[][] reverse = new int[m][2]; for (int i = 0; i < m; i++) { reverse[i][0] = sc.nextInt(); reverse[i][1] = sc.nextInt(); } int counter = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (permutation[i] > permutation[j]) { counter++; } } } boolean bayus = true; if (counter % 2 == 1) { bayus = false; } for (int i = 0; i < m; i++) { int bobib = reverse[i][1] - reverse[i][0] + 1; int bafry = nChoose2(bobib); if (bafry%2 == 1) { bayus = !bayus; } if (bayus) { System.out.println("even"); } else { System.out.println("odd"); } } } private static int nChoose2 (int n) { return (n * (n-1)) / 2; } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class bhaa { InputStream is; PrintWriter o; /////////////////// CODED++ BY++ ++ ++ ++ BHAVYA++ ARORA++ ++ ++ ++ FROM++ JAYPEE++ INSTITUTE++ OF++ INFORMATION++ TECHNOLOGY++ //////////////// ///////////////////////// Make it work, make it right, make it fast. Make it work, make it right, make it fast. Make it work, make it right, make it fast. Make it work, make it right, make it fast. ///////////////// boolean chpr(int n) { if(n==1) { return true; }if(n==2) { return true; } if(n==3) { return true; } if(n%2==0) { return false; } if(n%3==0) { return false; } int w=2; int i=5; while(i*i<=n) { if(n%i==0) { return false; } i+=w; w=6-w; } return true; } void solve() { int n=ni(); int k=ni(); int rr=2*n; int gr=5*n; int br=8*n; o.println((long)(Math.ceil(rr*1.0/k)+Math.ceil(gr*1.0/k)+Math.ceil(br*1.0/k))); } //---------- I/O Template ---------- public static void main(String[] args) { new bhaa().run(); } void run() { is = System.in; o = new PrintWriter(System.out); solve(); o.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] nia(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } long[] nla(int n) { long a[] = new long[n]; for(int i = 0; i < n; i++) { a[i] = nl(); } return a; } int [][] nim(int n) { int mat[][]=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { mat[i][j]=ni(); } } return mat; } long [][] nlm(int n) { long mat[][]=new long[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { mat[i][j]=nl(); } } return mat; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } void piarr(int arr[]) { for(int i=0;i<arr.length;i++) { o.print(arr[i]+" "); } o.println(); } void plarr(long arr[]) { for(int i=0;i<arr.length;i++) { o.print(arr[i]+" "); } o.println(); } void pimat(int mat[][]) { for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { o.print(mat[i][j]); } o.println(); } } void plmat(long mat[][]) { for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { o.print(mat[i][j]); } o.println(); } } //////////////////////////////////// template finished ////////////////////////////////////// }
constant
1080_A. Petya and Origami
CODEFORCES
//coded by : ariefianto17 | Reza Ariefianto import java.io.*; import java.util.*; import java.math.*; public class Main { public static void main (String[]args) { Scanner read = new Scanner (new BufferedInputStream (System.in)); int n = read.nextInt(); int[]arr = new int[n]; int sum=0; int sum2=0; int coin=0; for(int i=0;i<n;i++) { arr[i] = read.nextInt(); sum+=arr[i]; } Arrays.sort(arr); for(int i=n-1;i>=0;i--) { sum2+=arr[i]; sum-=arr[i]; coin++; if(sum2>sum) break; } System.out.println(coin); } }
nlogn
160_A. Twins
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main implements Runnable { // //////////////////////////////////////////////////////////////////// // Solution private int n; private int nn; private int[][] D; private int[] dp; private int[] prev; private void solve() throws Throwable { int xs = nextInt(), ys = nextInt(); n = nextInt(); int[][] pts = new int[n][2]; for (int i = 0; i < n; i++) { pts[i][0] = nextInt(); pts[i][1] = nextInt(); } D = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { D[i][i] = 2 * (sqr(pts[i][0] - xs) + sqr(pts[i][1] - ys)); } else { D[i][j] = sqr(pts[i][0] - xs) + sqr(pts[i][1] - ys) + sqr(pts[i][0] - pts[j][0]) + sqr(pts[i][1] - pts[j][1]) + sqr(pts[j][0] - xs) + sqr(pts[j][1] - ys); } } } nn = 1 << n; dp = new int[nn]; prev = new int[nn]; Arrays.fill(dp, -1); Arrays.fill(prev, -1); dp[0] = 0; Dp(nn - 1); pw.println(dp[nn - 1]); pw.print(0); for (int p = nn - 1; p != -1 && prev[p] != -1; p = prev[p]) { int vv = p ^ prev[p]; for (int j = 0; j < n; j++) { int jj = 1 << j; if ((vv & jj) == 0) continue; pw.print(' '); pw.print(j + 1); } pw.print(" 0"); } pw.println(); } private int Dp(int i) { if (dp[i] != -1) return dp[i]; int ans = 107374182, p = -1; int j1 = 1, pos1 = 0; for (; pos1 < n && j1 < nn; j1 *= 2, pos1++) { if ((i & j1) == 0) continue; int a = D[pos1][pos1] + Dp(i ^ j1); if (a < ans) { ans = a; p = i ^ j1; } int j2 = j1 * 2, pos2 = pos1 + 1; for (; pos2 < n && j2 < nn; j2 *= 2, pos2++) { if ((i & j2) == 0) continue; a = D[pos1][pos2] + Dp(i ^ (j1 | j2)); if (a < ans) { ans = a; p = i ^ (j1 | j2); } } break; } dp[i] = ans; prev[i] = p; return ans; } private int sqr(int i) { return i * i; } // //////////////////////////////////////////////////////////////////// // Utility functions PrintWriter pw; BufferedReader in; StringTokenizer st; void initStreams() throws FileNotFoundException { //System.setIn(new FileInputStream("1")); in = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); } String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextString()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextString()); } static Throwable sError; public static void main(String[] args) throws Throwable { // Thread t = new Thread(null, new Main(), "1", 1 << 27); // t.start(); // t.join(); new Main().run(); if (sError instanceof OutOfMemoryError) { throw sError; } // if (sError != null) { // throw sError; // } } public void run() { try { initStreams(); solve(); } catch (Throwable e) { sError = e; } finally { if (pw != null) pw.close(); } } }
np
8_C. Looking for Order
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; public class RENAMETHISBITCH { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { int n = sc.nextInt(); BigInteger m = sc.nextBigInteger(); System.out.println(m.mod(BigInteger.valueOf(2).pow(n))); } catch (Exception e) { e.printStackTrace(); } } }
constant
913_A. Modular Exponentiation
CODEFORCES
import java.lang.*; import java.util.*; import java.io.*; public class Challenge { public static void main(String[] args) throws java.lang.Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(in, out); out.close(); } } class TaskA { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); if (n == 1) { out.println("1"); } else if (n == 2) { out.println("2"); } else if (n == 3) { out.println("6"); } else if (n%2 > 0) { out.println(1L * n * (n-1) * (n-2)); } else if (n%3 == 0) { out.println(1L * (n-1) * (n-2) * (n-3)); } else { out.println(1L * n * (n-1) * (n-3)); } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer==null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
constant
235_A. LCM Challenge
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class C { public static void main(String[] args) { FastScanner fs=new FastScanner(); int nBoxes=fs.nextInt(); long[] sums=new long[nBoxes]; HashMap<Long, Integer> boxOf=new HashMap<>(); int[][] boxes=new int[nBoxes][]; long total=0; for (int i=0; i<nBoxes; i++) { int size=fs.nextInt(); boxes[i]=new int[size]; for (int j=0; j<size; j++) { boxes[i][j]=fs.nextInt(); boxOf.put((long)boxes[i][j], i); sums[i]+=boxes[i][j]; } total+=sums[i]; } if (total%nBoxes!=0) { System.out.println("No"); return; } long target=total/nBoxes; int[][] masks=new int[nBoxes][]; ArrayList<Integer>[][] maskLoops=new ArrayList[nBoxes][]; for (int i=0; i<nBoxes; i++) { masks[i]=new int[boxes[i].length]; maskLoops[i]=new ArrayList[boxes[i].length]; for (int j=0; j<maskLoops[i].length; j++) maskLoops[i][j]=new ArrayList<>(); inner:for (int j=0; j<boxes[i].length; j++) { long startVal=boxes[i][j], lookingFor=target-(sums[i]-startVal); maskLoops[i][j].add((int)lookingFor); int mask=1<<i; while (lookingFor!=startVal) { if (!boxOf.containsKey(lookingFor)) continue inner; int nextBox=boxOf.get(lookingFor); //if we have already used this box, it won't work if ((mask&(1<<nextBox))!=0) continue inner; mask|=1<<nextBox; lookingFor=target-(sums[nextBox]-lookingFor); /*if (lookingFor!=startVal) */maskLoops[i][j].add((int)lookingFor); } // System.out.println("Mask loops for box: "+i+" starting at "+startVal+" gives "+); //otherwise it worked masks[i][j]=mask; } } boolean[] possible=new boolean[1<<nBoxes]; int[] maskFrom=new int[1<<nBoxes]; int[] indexToUse=new int[1<<nBoxes]; possible[0]=true; for (int mask=1; mask<1<<nBoxes; mask++) { int lowestBit=Integer.numberOfTrailingZeros(Integer.lowestOneBit(mask)); /* for (int i:masks[lowestBit]) { if ((mask&i)==i && possible[mask^i]) { possible[mask]=true; break; } } */ for (int i=0; i<masks[lowestBit].length; i++) { int m=masks[lowestBit][i]; if ((mask&m)==m && possible[mask^m]) { possible[mask]=true; maskFrom[mask]=mask^m; indexToUse[mask]=i; break; } } } if (!possible[(1<<nBoxes)-1]) { System.out.println("No"); return; } System.out.println("Yes"); ArrayList<ArrayList<Integer>> loops=new ArrayList<>(); int mask=(1<<nBoxes)-1; while (mask!=0) { // System.out.println("At mask: "+Integer.toBinaryString(mask)); int lowestBit=Integer.numberOfTrailingZeros(Integer.lowestOneBit(mask)); loops.add(maskLoops[lowestBit][indexToUse[mask]]); mask=maskFrom[mask]; } // System.out.println("Loops: "+loops); int[] takeFrom=new int[nBoxes]; int[] boxGiveTo=new int[nBoxes]; for (ArrayList<Integer> loop:loops) { for (int i=0; i<loop.size(); i++) { int cur=loop.get(i), next=loop.get((i+1)%loop.size()); int curBox=boxOf.get((long)cur), nextBox=boxOf.get((long)next); takeFrom[nextBox]=next; boxGiveTo[nextBox]=curBox; } } for (int i=0; i<nBoxes; i++) { System.out.println(takeFrom[i]+" "+(boxGiveTo[i]+1)); } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
np
1242_C. Sum Balance
CODEFORCES
import java.io.*; import java.util.*; import java.util.stream.Collectors; import java.math.*; public class E1 { static byte[] buf = new byte[1<<26]; static int bp = -1; public static void main(String[] args) throws IOException { /**/ DataInputStream in = new DataInputStream(System.in); /*/ DataInputStream in = new DataInputStream(new FileInputStream("src/e.in")); /**/ in.read(buf, 0, 1<<26); int t = nni(); for (int z = 0; z < t; z++) { int n = nni(); int m = nni(); int[][] mat = new int[n][m]; int[] rmax = new int[n]; int tot = 0; HashSet<Integer> care = new HashSet<>(); for (int i = 0; i < n; i++) { PriorityQueue<Integer> cols = new PriorityQueue<>(); for (int j = 0; j < m; j++) { mat[i][j] = nni(); cols.add(-(mat[i][j]*2000+j)); rmax[i] = Math.max(rmax[i], mat[i][j]); } tot += rmax[i]; for (int j = 0; j < Math.min(m, n); j++) care.add((-cols.poll())%2000); } List<Integer> cal = care.stream().sorted().collect(Collectors.toList()); int ret = tot; if (Math.min(m, n)==1) { System.out.println(ret); } else if (Math.min(m, n)==2) { for (int a = 0; a < cal.size(); a++) { int la = cal.get(a); for (int d = 0; d < cal.size(); d++) { if (d==a) continue; int ld = cal.get(d); for (int i = 0; i < n; i++) { int tret = 0; for (int x = 0; x < n; x++) { tret += Math.max(mat[x][ld], mat[(i+x)%n][la]); } ret = Math.max(ret, tret); } } } System.out.println(ret); } else if (Math.min(m, n)==3) { for (int a = 0; a < cal.size(); a++) { int la = cal.get(a); for (int b = a+1; b < cal.size(); b++) { int lb = cal.get(b); for (int d = 0; d < cal.size(); d++) { if (d==a) continue; if (d==b) continue; int ld = cal.get(d); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int tret = 0; for (int x = 0; x < n; x++) { tret += Math.max(mat[x][ld], Math.max(mat[(i+x)%n][la], mat[(j+x)%n][lb])); } ret = Math.max(ret, tret); } } } } } System.out.println(ret); } else if (Math.min(m, n)==4) { for (int a = 0; a < cal.size(); a++) { int la = cal.get(a); for (int b = a+1; b < cal.size(); b++) { int lb = cal.get(b); for (int c = b+1; c < cal.size(); c++) { int lc = cal.get(c); for (int d = 0; d < cal.size(); d++) { if (d==a) continue; if (d==b) continue; if (d==c) continue; int ld = cal.get(d); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { int tret = 0; for (int x = 0; x < n; x++) { tret += Math.max(mat[x][ld], Math.max(mat[(i+x)%n][la], Math.max(mat[(j+x)%n][lb], mat[(k+x)%n][lc]))); } ret = Math.max(ret, tret); } } } } } } } System.out.println(ret); } } } public static int nni() { int ret = 0; byte b = buf[++bp]; while (true) { ret = ret*10+b-'0'; b = buf[++bp]; if (b<'0'||b>'9') { while (buf[bp+1]=='\r'||buf[bp+1]=='\n'||buf[bp+1]==' ') {++bp;} break; } } return ret; } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; import java.math.*; public class task { public static void main(String args[]) { Scanner a = new Scanner(System.in); while(a.hasNext()) { int n = a.nextInt(); int m = a.nextInt(); if(n == 0 && m == 0) break; boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = a.nextInt(); int y = a.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) if (adj[i][j]) --res; for (int i = 0; i < n; ++i) { long[][] dp = new long[n - i][1 << (n - i)]; dp[0][0] = 1; for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { if (dp[j][mask] != 0) { for (int k = 0; k < n - i; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) dp[k][mask | (1 << k)] += dp[j][mask]; } } } if (((mask >> 0) & 1) != 0) { res += dp[0][mask]; } } } System.out.println(res/2); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Dasha { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out), pw2 = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int n=sc.nextInt(); int[] arr=new int[101]; for(int i=0;i<n;i++) arr[sc.nextInt()]++; boolean [] vis=new boolean[101]; int c=0; for(int i=1;i<=100;i++){ if(!vis[i]&&arr[i]>0){ c++; for(int j=i+i;j<=100;j+=i) vis[j]=true; } } pw.println(c); pw.flush(); } public static <E> void print2D(E[][] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { pw.println(arr[i][j]); } } } public static int digitSum(String s) { int toReturn = 0; for (int i = 0; i < s.length(); i++) toReturn += Integer.parseInt(s.charAt(i) + " "); return toReturn; } public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static long pow(long a, long pow) { return pow == 0 ? 1 : pow % 2 == 0 ? pow(a * a, pow >> 1) : a * pow(a * a, pow >> 1); } public static long sumNum(long a) { return a * (a + 1) / 2; } public static int gcd(int n1, int n2) { return n2 == 0 ? n1 : gcd(n2, n1 % n2); } public static long factorial(long a) { return a == 0 || a == 1 ? 1 : a * factorial(a - 1); } public static void sort(int arr[]) { shuffle(arr); Arrays.sort(arr); } public static void shuffle(int arr[]) { Random rnd = new Random(); for (int i = arr.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); int temp = arr[index]; arr[index] = arr[i]; arr[i] = temp; } } public static Double[] solveQuadratic(double a, double b, double c) { double result = (b * b) - 4.0 * a * c; double r1; if (result > 0.0) { r1 = ((double) (-b) + Math.pow(result, 0.5)) / (2.0 * a); double r2 = ((double) (-b) - Math.pow(result, 0.5)) / (2.0 * a); return new Double[]{r1, r2}; } else if (result == 0.0) { r1 = (double) (-b) / (2.0 * a); return new Double[]{r1, r1}; } else { return new Double[]{null, null}; } } 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(); } } static class pair<E1, E2> implements Comparable<pair> { E1 x; E2 y; pair(E1 x, E2 y) { this.x = x; this.y = y; } @Override public int compareTo(pair o) { return x.equals(o.x) ? (Integer) y - (Integer) o.y : (Integer) x - (Integer) o.x; } @Override public String toString() { return x + " " + y; } public double pointDis(pair p1) { return Math.sqrt(((Integer) y - (Integer) p1.y) * ((Integer) y - (Integer) p1.y) + ((Integer) x - (Integer) p1.x) * ((Integer) x - (Integer) p1.x)); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package a_vtoray_poriadkovay_statistika; import java.util.Arrays; import java.util.Scanner; /** * * @author kal1sha */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic hereSc int n, i; boolean status = false; int answer; Scanner in = new Scanner(System.in); n = in.nextInt(); int a[] = new int[n]; for (i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); answer = a[0]; for (i = 1; i < n; i++) { if (a[i] != answer) { answer = a[i]; status = true; i = n + 1; } } if (status) { System.out.println(answer); } else { System.out.println("NO"); } } }
nlogn
22_A. Second Order Statistics
CODEFORCES
//package fourninetysixDiv3; import java.util.HashMap; import java.util.Scanner; public class Median_Segments_general { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int m = s.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } System.out.println(func(n, m, arr)-func(n, m+1, arr)); } public static long func(int n,int m,int[] arr) { HashMap<Long, Integer> map = new HashMap<>(); map.put((long) 0, 1); long sum = 0; long res = 0; long add=0; for(int i=0;i<n;i++) { if(arr[i]<m) { sum--; if(map.containsKey(sum)) { add-=map.get(sum); } } else { if(map.containsKey(sum)) { add+=map.get(sum); } sum++; } res+=add; if(map.containsKey(sum)) { map.put(sum, map.get(sum)+1); } else { map.put(sum,1); } } return res; } }
nlogn
1005_E1. Median on Segments (Permutations Edition)
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class P113A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintStream out = System.out; //CODING TAIM int n = sc.nextInt(); int k = sc.nextInt(); List<Team> l = new ArrayList<Team>(); for (int i = 0; i < n; i++) { l.add(new Team(sc.nextInt(), sc.nextInt())); } Collections.sort(l, new Comparator<Team>() { public int compare(Team a, Team b) { if (a.s == b.s) return a.t - b.t; return b.s - a.s; } }); int f = k - 1; int la = k - 1; Team p = l.get(k - 1); while (la < n && l.get(la).s == p.s && l.get(la).t == p.t) la++; while ( f >= 0 && l.get(f).s == p.s && l.get(f).t == p.t) f--; out.println(la - f - 1); } static class Team { int s; int t; public Team(int a, int b) { s = a; t = b; } } }
nlogn
166_A. Rank List
CODEFORCES
//package global14; import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Queue; public class B { InputStream is; FastWriter out; String INPUT = ""; void solve() { for(int T = ni();T > 0;T--)go(); } void go() { int n = ni(); if(n % 2 == 0){ int u = (int)Math.sqrt(n/2); if(u*u == n/2){ out.println("YES"); return; } } if(n % 4 == 0){ int u = (int)Math.sqrt(n/4); if(u*u == n/4){ out.println("YES"); return; } } out.println("NO"); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new B().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.util.*; public class AA{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=0; if(sc.hasNextInt()) { t=sc.nextInt(); } while(t>0) { t--; int n=sc.nextInt(); String ans="NO"; if(n%2==0) { int p=n/2; if(Math.ceil(Math.sqrt((double)p)) == Math.floor(Math.sqrt((double)p))){ ans="YES"; } else { if(n%4==0) { p=n/4; if(Math.ceil(Math.sqrt((double)p)) == Math.floor(Math.sqrt((double)p))){ ans="YES"; } } } } System.out.println(ans); } } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
//package GoodBye2017; import java.io.*; import java.util.*; public class c { public static void main(String[] args) throws Exception{ new c(new Reader()); } public c(Reader rr) throws IOException{ int n=rr.ni(); double r=rr.nd(); HashMap<Integer, Double> disk=new HashMap<Integer, Double>(); for(int i=0; i<n; i++){ int next=rr.ni(); if(disk.isEmpty()){ disk.put(next, r); System.out.print(r+" "); } else{ double high=r; for(Map.Entry<Integer, Double> it: disk.entrySet()){ if(2*r<next-it.getKey()) continue; double tempHigh=pyth(Math.abs(next-it.getKey()),r*2)+it.getValue(); if(tempHigh>high){ high=tempHigh; } } disk.put(next, high); System.out.print(high+" "); } } } public double pyth(double a, double c){ return Math.sqrt(Math.pow(c, 2)-Math.pow(a, 2)); } static class Reader{ private DataInputStream din; private byte[] buffer=new byte[1024]; private int bufP, bytR; public Reader() throws IOException{ din=new DataInputStream(System.in); bufP=bytR=0; } public Reader(String file) throws IOException{ din=new DataInputStream(new FileInputStream(file)); bufP=bytR=0; } private String rl() throws IOException{ byte[] buf=new byte[1024]; int cnt=0, c; while((c=read())!=-1){ if(c=='\n') break; buf[cnt++]=(byte)c; } return new String(buf, 0, cnt); } private int ni() throws IOException{ int num=0; byte c=read(); while(c<=' ') c=read(); boolean neg=(c=='-'); if(neg) c=read(); do{ num=num*10+c-'0'; } while((c=read())>='0'&&c<='9'); if(neg) return -num; return num; } private long nl() throws IOException{ long num=0; byte c=read(); while(c<=' ') c=read(); boolean neg=(c=='-'); if(neg) c=read(); do{ num=num*10+c-'0'; } while((c=read())>='0'&&c<='9'); if(neg) return -num; return num; } private double nd() throws IOException{ return Double.parseDouble(ns()); } private char nc() throws IOException{ return (char)next(); } private String ns() throws IOException{ int c=next(); StringBuilder sb=new StringBuilder(); while(!(isChar(c))){ sb.appendCodePoint(c); c=read(); } return sb.toString(); } private char[] ns(int n) throws IOException{ char[] buf=new char[n]; int c=next(), r=0; while(r<n&&!(isChar(c))){ buf[r++]=(char)c; c=next(); } return n==r?buf:Arrays.copyOf(buf, r); } private char[][] nm(int n, int m) throws IOException{ char[][] map=new char[n][]; for(int i=0; i<n; i++) map[i]=ns(m); return map; } private int[] na(int n) throws IOException{ int[] a=new int[n]; for(int i=0; i<n; i++) a[i]=ni(); return a; } private boolean isChar(int c) throws IOException{ return !(c>=33&&c<=126); } private int next() throws IOException{ int c; while((c=read())!=-1&&isChar(c)); return c; } private byte read() throws IOException{ if(bufP==bytR){ bytR=din.read(buffer, bufP=0, 1024); if(bytR==-1) buffer[0]=-1; } return buffer[bufP++]; } public void close() throws IOException{ if(din==null) return; din.close(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * @Author: * @Date: 2021/4/23 23:55 */ public class ExplorerSpace { static int n; static int m; static int k; static int [][] rows; static int [][] cols; static int max; static int orix; static int oriy; static int [][] dirs = new int[][]{{0,1},{0,-1},{1,0},{-1,0}}; static int [][][][][] mem; public static void main(String[] args) { FastScanner fs = new FastScanner(); n = fs.nextInt(); m =fs.nextInt(); k = fs.nextInt(); rows = new int[n][m-1]; cols = new int[n-1][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m-1; j++){ rows[i][j] = fs.nextInt(); } } for(int i = 0; i < n-1; i++){ for(int j = 0; j < m; j++){ cols[i][j] = fs.nextInt(); } } int [][][] res = new int[100][n][m]; for(int o = 2; o <= k; o+=2){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ res[o][i][j] = 0x3f3f3f3f; if(i>0){ res[o][i][j] = Math.min(res[o][i][j], res[o-2][i-1][j] + 2*cols[i-1][j]); } if(i+1<n){ res[o][i][j] = Math.min(res[o][i][j], res[o-2][i+1][j] + 2 * cols[i][j]); } if(j>0){ res[o][i][j] = Math.min(res[o][i][j], res[o-2][i][j-1] + 2 * rows[i][j-1]); } if(j+1<m){ res[o][i][j] = Math.min(res[o][i][j], res[o-2][i][j+1] + 2 * rows[i][j]); } } } } for(int i = 0; i < n; i++){ for(int j = 0; j < m;j ++){ if(k%2==1){ System.out.print(-1+" "); }else{ System.out.print(res[k][i][j] + " "); } } System.out.println(); } } // static void dfs(int x, int y,int cur, int left){ // if(x<0||x>=n||y<0||y>=m){ // return; // } // if(left==0&&x==orix&&y==oriy){ // max = Math.min(max,cur); // return; // } // if(left<=0){ // return; // } // if(cur>=max){ // return; // } // if(x+1<n){ // dfs(x+1,y,cur+cols[x][y],left-1); // } // if(x-1>=0){ // dfs(x-1,y,cur+cols[x-1][y],left-1); // } // if(y+1<m){ // dfs(x,y+1,cur+rows[x][y],left-1); // } // if(y-1>=0){ // dfs(x,y-1,cur+rows[x][y-1],left-1); // } // // } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while (!st.hasMoreTokens()){ 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()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.math.BigInteger; import javax.naming.BinaryRefAddr; public class acm { public static BigInteger n; public static BigInteger TWO = new BigInteger("2"); public static BigInteger solve(BigInteger x, BigInteger y, BigInteger c) { BigInteger res = (c.add(BigInteger.ONE)).multiply(c.add(BigInteger.ONE)); res = res.add(c.multiply(c)); BigInteger k; //up k = c.subtract(x.subtract(BigInteger.ONE)); if(k.compareTo(BigInteger.ZERO) > 0) res = res.subtract(k.multiply(k)); //left k = c.subtract(y.subtract(BigInteger.ONE)); if(k.compareTo(BigInteger.ZERO) > 0) res = res.subtract(k.multiply(k)); //down k = c.subtract(n.subtract(x)); if(k.compareTo(BigInteger.ZERO) > 0) res = res.subtract(k.multiply(k)); //right k = c.subtract(n.subtract(y)); if(k.compareTo(BigInteger.ZERO) > 0) res = res.subtract(k.multiply(k)); //upleft k = c.subtract(x.add(y).subtract(BigInteger.ONE)); if(k.compareTo(BigInteger.ZERO) > 0) res = res.add(k.multiply(k.add(BigInteger.ONE)).divide(TWO)); //upright k = c.subtract(x.add(n).subtract(y)); if(k.compareTo(BigInteger.ZERO) > 0) res = res.add(k.multiply(k.add(BigInteger.ONE)).divide(TWO)); //dwleft k = c.subtract(y.add(n).subtract(x)); if(k.compareTo(BigInteger.ZERO) > 0) res = res.add(k.multiply(k.add(BigInteger.ONE)).divide(TWO)); //dwleft k = c.subtract(n.subtract(x).add(n.subtract(y)).add(BigInteger.ONE)); if(k.compareTo(BigInteger.ZERO) > 0) res = res.add(k.multiply(k.add(BigInteger.ONE)).divide(TWO)); return res; } public static void main(String[] args) {TWO = new BigInteger("2"); Scanner in = new Scanner(System.in); n = new BigInteger(in.next()); BigInteger x = new BigInteger(in.next()); BigInteger y = new BigInteger(in.next()); BigInteger c = new BigInteger(in.next()); BigInteger left = new BigInteger("0"); BigInteger right = new BigInteger("1000000000000"); while(left.compareTo(right) < 0) { BigInteger val = left.add(right).divide(TWO); if(solve(x, y, val).compareTo(c) >= 0) right = val; else left = val.add(BigInteger.ONE); } System.out.println(left); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; public class Solution { public static void main(String[] args)throws IOException { FastReader in=new FastReader(System.in); int t=in.nextInt(); StringBuilder sb=new StringBuilder(); int i,j,tc=0; while(tc++<t) { int n=in.nextInt(); int arr[]=new int[n]; for(i=0;i<n;i++) arr[i]=in.nextInt(); int ans[]=new int[n+4]; ans[0]=1; int pos=0; sb.append("1\n"); for(i=1;i<n;i++){ if(arr[i]==arr[i-1]+1){ ans[pos]=ans[pos]+1; } else if(arr[i]==1){ pos++; ans[pos]=1; } else{ while(ans[pos]!=arr[i]-1) pos--; ans[pos]=ans[pos]+1; } for(j=0;j<=pos;j++){ if(j<pos) sb.append(ans[j]).append("."); else sb.append(ans[j]).append("\n"); } } } System.out.println(sb); } } class Node { int setroot, dist; public Node(int setroot, int dist){ this.setroot = setroot; this.dist = dist; } @Override public String toString() { return String.format(setroot + ", " + dist); } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; public class Beta22PA { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int minimum = 200, second = 200; for(int i=0; i<n; i++) { int temp = scan.nextInt(); if(temp<minimum) { second = minimum; minimum = temp; } else if(temp>minimum&&temp<second) { second = temp; } } if(second>100) { System.out.println("NO"); } else { System.out.println(second); } } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.PrintWriter; import java.util.*; public class D { static Scanner sc; static PrintWriter out; public static void main(String[] args) throws Exception { sc = new Scanner(System.in); out = new PrintWriter(System.out); //int t = sc.nextInt(); for(int i=0; i<1; i++) { solve(); } out.flush(); } static void solve() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int[][] a = new int[n][m-1]; int[][] b = new int[n-1][m]; for(int i=0 ;i<n; i++) { for(int j=0; j<m-1; j++) { a[i][j] = sc.nextInt(); } } for(int i=0 ;i<n-1; i++) { for(int j=0; j<m; j++) { b[i][j] = sc.nextInt(); } } if(k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j > 0) out.print(" "); out.print("-1"); } out.println(); } return; } int[][] prev = new int[n][m]; k /= 2; for(int l=0; l<k; l++) { int[][] next = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { next[i][j] = Integer.MAX_VALUE; if(i>0) { next[i][j] = Math.min(next[i][j], prev[i-1][j] + b[i-1][j]); } if(i+1<n) { next[i][j] = Math.min(next[i][j], prev[i+1][j] + b[i][j]); } if(j>0) { next[i][j] = Math.min(next[i][j], prev[i][j-1] + a[i][j-1]); } if(j+1<m) { next[i][j] = Math.min(next[i][j], prev[i][j+1] + a[i][j]); } } } prev = next; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j > 0) out.print(" "); out.print(prev[i][j] * 2); } out.println(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class _817C { static long sum = 0; static long BSearch2(long st, long end, long lim) { if (st > end) return 0; long mid = (st + end) >> 1; if (mid - sumDigit(mid) >= lim) { sum = mid; return BSearch2(st, mid - 1, lim); } if (mid - sumDigit(mid) < lim) return BSearch2(mid + 1, end, lim); return 0; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); long s = Long.parseLong(st.nextToken()); long n = Long.parseLong(st.nextToken()); BSearch2(1, s, n); if (sum == 0) System.out.println("0"); else System.out.println(s - sum + 1); } static long sumDigit(long z) { String s = "" + z; int c = 0; for (int i = 0; i < s.length(); i++) c += s.charAt(i); return c - s.length() * 0x30; } }
logn
817_C. Really Big Numbers
CODEFORCES
/** * Created by IntelliJ IDEA. * User: aircube * Date: 11.01.11 * Time: 4:14 * To change this template use File | Settings | File Templates. */ import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.Exchanger; public class Template { BufferedReader br; PrintWriter out; StringTokenizer st; public static void main(String[] args) throws IOException { new Template().run(); } void run() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); st = null; out = new PrintWriter(System.out); solve(); br.close(); out.close(); } double dm[]; double a[][]; boolean fil[]; int p[]; int n; // x & (x - 1) // 10 // void solve() throws IOException { n = nextInt(); a = new double[n][n]; for(int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { a[i][j] = nextDouble(); } dm = new double[1 << n]; dm[(1 << n) - 1] = 1; for(int mask = (1 << n) - 1; mask >= 1; --mask) { int c = Integer.bitCount(mask); if (c == 1) continue ; double p = 2.0 / (double)(c - 1) / (double) c; for(int i = 0; i < n; ++i) { for (int j =0 ; j < n; ++j) { if (i != j && (mask & (1 << i)) > 0 && (mask & (1 << j)) > 0) { dm[mask ^ (1 << j)] += a[i][j] * dm[mask] * p; } } } } for(int i = 0; i < n; ++i) { out.print(dm[1 << i] + " "); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }
np
16_E. Fish
CODEFORCES
import java.util.Scanner; public class Main2 { public static void main(String args[]){ Scanner input = new Scanner(System.in); String st = input.nextLine(); System.out.println(bank(st)); } public static int bank(String st){ StringBuilder sb = new StringBuilder(st); int st1 = Integer.parseInt(sb.substring(0,st.length()-2)+sb.substring(st.length()-1,st.length())); int st2 = Integer.parseInt(sb.substring(0,st.length()-1)); int st3 = Integer.parseInt(st); return Math.max(st3,Math.max(st1, st2)); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.util.*; public class Main { static int mod = 1000000007; static int size = 200000; static long[] fac = new long[size]; static long[] finv = new long[size]; static long[] inv = new long[size]; static int INF = Integer.MAX_VALUE; public static void main(String[] args){ Scanner scanner = new Scanner(System.in); String[] s = new String[2]; for(int i = 0; i < 2; i++){ s[i] = scanner.next(); } int n = s[0].length(); char[][] c = new char[2][n]; for(int i = 0; i < 2; i++){ for(int j = 0; j < n; j++){ c[i][j] = s[i].charAt(j); } } int count = 0; for(int i = 0; i < n-1; i++){ if(c[0][i] == '0' && c[1][i] == '0' && c[0][i+1] == '0'){ c[0][i] = 'X'; c[1][i] = 'X'; c[0][i+1] = 'X'; count++; } if(c[0][i] == '0' && c[1][i] == '0' && c[1][i+1] == '0'){ c[0][i] = 'X'; c[1][i] = 'X'; c[1][i+1] = 'X'; count++; } if(c[0][i] == '0' && c[0][i+1] == '0' && c[1][i+1] == '0'){ c[0][i] = 'X'; c[0][i+1] = 'X'; c[1][i+1] = 'X'; count++; } if(c[0][i+1] == '0' && c[1][i+1] == '0' && c[1][i] == '0'){ c[1][i] = 'X'; c[0][i+1] = 'X'; c[1][i+1] = 'X'; count++; } } System.out.println(count); } public static boolean isPrime(int n){ if(n == 1) return false; if(n == 2 || n == 3) return true; for(int i = 2; i <= Math.sqrt(n); i++){ if(n % i == 0) return false; } return true; } // tar の方が数字が大きいかどうか static boolean compare(String tar, String src) { if (src == null) return true; if (src.length() == tar.length()) { int len = tar.length(); for (int i = 0; i < len; i++) { if (src.charAt(i) > tar.charAt(i)) { return false; } else if (src.charAt(i) < tar.charAt(i)) { return true; } } return tar.compareTo(src) > 0 ? true : false; } else if (src.length() < tar.length()) { return true; } else if (src.length() > tar.length()) { return false; } return false; } public static class Edge{ int to; Edge(int to){ this.to = to; } } public static void swap(long a, long b){ long tmp = 0; if(a > b){ tmp = a; a = b; b = tmp; } } static class Pair implements Comparable<Pair>{ int first, second; Pair(int a, int b){ first = a; second = b; } @Override public boolean equals(Object o){ if (this == o) return true; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return first == p.first && second == p.second; } @Override public int compareTo(Pair p){ return first == p.first ? second - p.second : first - p.first; //firstで昇順にソート //return (first == p.first ? second - p.second : first - p.first) * -1; //firstで降順にソート //return second == p.second ? first - p.first : second - p.second;//secondで昇順にソート //return (second == p.second ? first - p.first : second - p.second)*-1;//secondで降順にソート } } //繰り返し二乗法 public static long pow(long x, long n){ long ans = 1; while(n > 0){ if((n & 1) == 1){ ans = ans * x; ans %= mod; } x = x * x % mod; n >>= 1; } return ans; } public static long div(long x, long y){ return (x*pow(y, mod-2))%mod; } //fac, inv, finvテーブルの初期化、これ使う場合はinitComb()で初期化必要 public static void initComb(){ fac[0] = finv[0] = inv[0] = fac[1] = finv[1] = inv[1] = 1; for (int i = 2; i < size; ++i) { fac[i] = fac[i - 1] * i % mod; inv[i] = mod - (mod / i) * inv[(int) (mod % i)] % mod; finv[i] = finv[i - 1] * inv[i] % mod; } } //nCk % mod public static long comb(int n, int k){ return fac[n] * finv[k] % mod * finv[n - k] % mod; } //n! % mod public static long fact(int n){ return fac[n]; } //(n!)^-1 with % mod public static long finv(int n){ return finv[n]; } static class UnionFind { int[] parent; public UnionFind(int size) { parent = new int[size]; Arrays.fill(parent, -1); } public boolean unite(int x, int y) { x = root(x); y = root(y); if (x != y) { if (parent[y] < parent[x]) { int tmp = y; y = x; x = tmp; } parent[x] += parent[y]; parent[y] = x; return true; } return false; } public boolean same(int x, int y) { return root(x) == root(y); } public int root(int x) { return parent[x] < 0 ? x : (parent[x] = root(parent[x])); } public int size(int x) { return -parent[root(x)]; } } public static int upperBound(int[] array, int value) { int low = 0; int high = array.length; int mid; while( low < high ) { mid = ((high - low) >>> 1) + low; // (high + low) / 2 if( array[mid] <= value ) { low = mid + 1; } else { high = mid; } } return low; } public static final int lowerBound(final int[] arr, final int value) { int low = 0; int high = arr.length; int mid; while (low < high){ mid = ((high - low) >>> 1) + low; //(low + high) / 2 (オーバーフロー対策) if (arr[mid] < value) { low = mid + 1; } else { high = mid; } } return low; } //n,mの最大公約数 public static long gcd(long n, long m){ if(m > n) return gcd(m,n); if(m == 0) return n; return gcd(m, n%m); } //3要素のソート private class Pair2 implements Comparable<Pair2> { String s; int p; int index; public Pair2(String s, int p, int index) { this.s = s; this.p = p; this.index = index; } public int compareTo(Pair2 other) { if (s.equals(other.s)) { return other.p - this.p; } return this.s.compareTo(other.s); } } //c -> intに変換 public static int c2i(char c){ if('A' <= c && c <= 'Z'){ return c - 'A'; }else{ return c - 'a' + 26; } } // int -> charに変換 public static char i2c(int i){ if(0 <= i && i < 26){ return (char)(i + 'A'); }else{ return (char)(i + 'a' - 26); } } }
constant
991_D. Bishwock
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 Liavontsi Brechka */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static @SuppressWarnings("Duplicates") class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int m = in.nextInt(); int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[i] > a[j]) count = (count + 1) % 2; } } StringBuilder res = new StringBuilder(); int l, r; while (m-- > 0) { l = in.nextInt() - 1; r = in.nextInt() - 1; count = count ^ (((r - l + 1) * (r - l) / 2) % 2); res.append(count == 1 ? "odd" : "even").append('\n'); } out.print(res); } } static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public int[] nextIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; ++i) { array[i] = nextInt(); } return array; } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; 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); E2VrashayaStolbciUslozhnennayaVersiya solver = new E2VrashayaStolbciUslozhnennayaVersiya(); solver.solve(1, in, out); out.close(); } static class E2VrashayaStolbciUslozhnennayaVersiya { public void solve(int testNumber, Scanner in, PrintWriter out) { int tn = in.nextInt(); for (int t = 0; t < tn; t++) { int n = in.nextInt(); int m = in.nextInt(); Col[] a = new Col[m]; for (int i = 0; i < m; i++) { a[i] = new Col(n); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[j].a[i] = in.nextInt(); if (a[j].a[i] > a[j].max) { a[j].max = a[j].a[i]; } } } Arrays.sort(a, (o1, o2) -> o2.max - o1.max); if (m > n) { m = n; } for (int i = 0; i < m; i++) { a[i].calcMask(); } int[][] dp = new int[m + 1][1 << n]; Arrays.fill(dp[0], -1); dp[0][0] = 0; for (int i = 0; i < m; i++) { for (int msk = 0; msk < (1 << n); msk++) { dp[i + 1][msk] = dp[i][msk]; for (int sub = msk; sub > 0; sub = (sub - 1) & msk) { int v = dp[i][msk ^ sub] + a[i].mask[sub]; if (v > dp[i + 1][msk]) { dp[i + 1][msk] = v; } } } } out.println(dp[m][(1 << n) - 1]); } } class Col { int n; int[] a; int[] mask; int max; public Col(int n) { this.n = n; a = new int[n]; } void calcMask() { mask = new int[1 << n]; for (int i = 0; i < (1 << n); i++) { for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < n; k++) { if (((1 << k) & i) != 0) { sum += a[(j + k) % n]; } } if (sum > mask[i]) { mask[i] = sum; } } } } } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class A { final String filename = new String("A").toLowerCase(); void solve() throws Exception { int n = nextInt(); int[] a = new int[n]; int m = -1; for (int i = 0; i < n; i++) { a[i] = nextInt(); if (m == -1 || a[i] > a[m]) { m = i; } } if (a[m] == 1) a[m] = 2; else a[m] = 1; Arrays.sort(a); for (int i = 0; i < n; i++) { out.print(a[i] + " "); } } void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // in = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } BufferedReader in; StringTokenizer st; PrintWriter out; String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(nextToken()); } long nextLong() throws Exception { return Long.parseLong(nextToken()); } double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } public static void main(String[] args) { new A().run(); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; 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); TaskE2 solver = new TaskE2(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskE2 { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); TaskE2.Column[] columns = new TaskE2.Column[m]; for (int i = 0; i < m; ++i) columns[i] = new TaskE2.Column(new int[n]); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { columns[j].vals[i] = in.nextInt(); } } for (int i = 0; i < m; ++i) columns[i].initMax(); Arrays.sort(columns, new Comparator<TaskE2.Column>() { public int compare(TaskE2.Column o1, TaskE2.Column o2) { return o2.max - o1.max; } }); if (columns.length > n) { columns = Arrays.copyOf(columns, n); } out.println(solveOne(columns)); } private int solveOne(TaskE2.Column[] columns) { int n = columns[0].vals.length; int[] best = new int[1 << n]; int[] next = new int[1 << n]; int[] tmp = new int[1 << n]; for (TaskE2.Column c : columns) { System.arraycopy(best, 0, next, 0, best.length); for (int rot = 0; rot < n; ++rot) { System.arraycopy(best, 0, tmp, 0, best.length); for (int i = 0, pos = rot; i < n; ++i, ++pos) { if (pos >= n) pos = 0; int val = c.vals[pos]; for (int j = 0; j < tmp.length; ++j) if ((j & (1 << i)) == 0) { tmp[j ^ (1 << i)] = Math.max(tmp[j ^ (1 << i)], tmp[j] + val); } } for (int j = 0; j < tmp.length; ++j) { next[j] = Math.max(next[j], tmp[j]); } } int[] aa = best; best = next; next = aa; } return best[best.length - 1]; } static class Column { int[] vals; int max; public Column(int[] vals) { this.vals = vals; } void initMax() { max = 0; for (int x : vals) max = Math.max(max, x); } } } 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()); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class A { /** * @param args */ public static void main(String[] args) { HomeWorks hw = new HomeWorks(); hw.sol(); hw.print(); } } class HomeWorks { HomeWorks(){ Scanner scr = new Scanner(System.in); n = scr.nextInt(); a = scr.nextInt(); b = scr.nextInt(); h = new int[n]; for (int i = 0; i < n; i++){ h[i] = scr.nextInt(); } scr.close(); } void sol() { Arrays.sort(h); int Vasya = h[b-1]; int Petya = h[b]; ans = Petya - Vasya; if (ans < 0){ ans = 0; } } void print(){ PrintWriter pw = new PrintWriter(System.out); pw.println(ans); pw.flush(); pw.close(); } int ans; int[] h; int n; int a; int b; }
nlogn
169_A. Chores
CODEFORCES
/* * * @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya) * Dhirubhai Ambani Institute of Information And Communication Technology * */ import java.util.*; import java.io.*; import java.lang.*; public class Code3 { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); long x = in.nextLong(); long k = in.nextLong(); if(x==0) pw.println(0); else { long mul = modularExponentiation(2L, k, mod); x = (x%mod * 2L%mod)%mod; x = (x%mod - 1L%mod + mod)%mod; x = (x%mod * mul%mod)%mod; x = (x%mod + 1%mod)%mod; pw.print(x); } pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final 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 String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(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; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/13/11 * Time: 6:10 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.io.IOException; public class DarkAssembly extends Thread { public DarkAssembly() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } class Senator { int loyalty; int level; public Senator(int level, int loyalty) { this.level = level; this.loyalty = loyalty; } } private static double doIt(Senator[] senators, int A) { double probability = .0; for (int mask = 0; mask < (1 << senators.length); ++mask) { int sum = A; double current = 1.0; for (int i = 0; i < senators.length; ++i) { if ((mask & (1 << i)) != 0) { current *= .01 * senators[i].loyalty; } else { current *= .01 * (100 - senators[i].loyalty); sum += senators[i].level; } } if (getOnes(mask) > senators.length / 2) { probability += current; } else { probability += current * (double)A / sum; } } return probability; } private static double go(Senator []senators, int candies, int A, int current) { if (current == senators.length) { return doIt(senators, A); } else { double result = go(senators, candies, A, current + 1); if (candies > 0 && senators[current].loyalty < 100) { senators[current].loyalty += 10; result = Math.max(result, go(senators, candies - 1, A, current)); senators[current].loyalty -= 10; } return result; } } static int getOnes(int mask) { int result = 0; while (mask != 0) { mask &= mask - 1; ++result; } return result; } public void run() { try { int n = nextInt(); int k = nextInt(); int A = nextInt(); Senator[] senators = new Senator[n]; for (int i = 0; i < n; ++i) { senators[i] = new Senator(nextInt(), nextInt()); } output.printf("%.10f", go(senators, k, A, 0)); output.flush(); output.close(); } catch (Throwable e) { System.err.println(e.getMessage()); System.err.println(Arrays.deepToString(e.getStackTrace())); } } public static void main(String[] args) { new DarkAssembly().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()); } private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
105_B. Dark Assembly
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author @Ziklon */ 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); ABirthday solver = new ABirthday(); solver.solve(1, in, out); out.close(); } static class ABirthday { public void solve(int testNumber, InputReader in, OutputWriter out) { long N = in.readLong(), M = in.readLong(), K = in.readLong(), L = in.readLong(); long ans = ((L + K) - 1) / M + 1; if (ans * M > N || ans * M - K < L) out.printLine(-1); else out.printLine(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 close() { writer.close(); } public void printLine(long i) { writer.println(i); } public void printLine(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
constant
1068_A. Birthday
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class A15 { static StreamTokenizer in; static PrintWriter out; static int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } static String nextString() throws IOException { in.nextToken(); return in.sval; } public static void main(String[] args) throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); int n = nextInt(), t = nextInt(); int[] x = new int[n]; int[] a = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt(); a[i] = nextInt(); } int ans = 0; for (int i = 0; i < n; i++) { boolean left = true, right = true; for (int j = 0; j < n; j++) if (x[j] < x[i] && a[i] + 2*t + a[j] >= 2*Math.abs(x[i] - x[j])) left = false; else if (x[j] > x[i] && a[i] + 2*t + a[j] > 2*Math.abs(x[i] - x[j])) right = false; if (left) ans++; if (right) ans++; } out.println(ans); out.flush(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class Main { static BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer tok; static boolean hasNext() { while(tok==null||!tok.hasMoreTokens()) try{ tok=new StringTokenizer(in.readLine()); } catch(Exception e){ return false; } return true; } static String next() { hasNext(); return tok.nextToken(); } static long nextLong() { return Long.parseLong(next()); } static int nextInt() { return Integer.parseInt(next()); } static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) { Map<Integer,Integer> map = new HashMap(); map.put(0,1); int n = nextInt(); int m = nextInt(); int index = -1; int a[] = new int[n]; for(int i=0;i<n;i++){ a[i]=nextInt(); if(a[i]==m) index=i; } int sum = 0; for(int i=0;i<index;i++){ if (a[i]<m) sum--; else sum++; if (map.containsKey(sum)){ map.put(sum,map.get(sum)+1); }else { map.put(sum,1); } } long ans = 0; for(int i=index;i<n;i++){ if (a[i]<m) sum--; else if(a[i]>m) sum++; if (map.containsKey(sum)) ans+=map.get(sum); if (map.containsKey(sum-1)) ans+=map.get(sum-1); } out.print(ans); out.flush(); } }
nlogn
1005_E1. Median on Segments (Permutations Edition)
CODEFORCES
//package round15; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class A { static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static int nextInt() throws IOException{ in.nextToken(); return (int)in.nval; } static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException{ int n = nextInt(), t = nextInt(), x[] = new int[n], a[] = new int[n]; for (int i=0; i<n; i++){ x[i] = nextInt(); a[i] = nextInt(); } for (int i=0; i<n-1; i++) for (int j=i+1; j<n; j++) if (x[i] > x[j]){ int p = x[i]; x[i] = x[j]; x[j] = p; p = a[i]; a[i] = a[j]; a[j] = p; } double l[] = new double[n]; double r[] = new double[n]; for (int i=0; i<n; i++){ l[i] = x[i]-a[i]/2.0; r[i] = x[i]+a[i]/2.0; } int res = 2; for (int i=1; i<n; i++){ if (Math.abs(l[i]-r[i-1]-t) < 0.000001) res++; else if (l[i]-r[i-1] > t) res += 2; } out.println(res); out.flush(); } }
nlogn
15_A. Cottage Village
CODEFORCES
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here long n,s,p; Scanner in=new Scanner(System.in); n=in.nextLong(); s=in.nextLong(); if(n==1 && s<=1) { System.out.print(n-1); } else if(s<n) { if(s%2!=0) {System.out.print(s/2);} else {System.out.print(s/2-1);} } else if(s==n) { if(s%2==0) {System.out.println((n/2)-1);} else {System.out.println(n/2);} } else if(s<=(2*n-1)) { System.out.print((2*n+1-s)/2); } else { System.out.print(0); } } }
constant
1023_B. Pair of Toys
CODEFORCES
import java.util.Scanner; public class Task5d { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); double a = sc.nextDouble(); double v = sc.nextDouble(); double l = sc.nextDouble(); double d = sc.nextDouble(); double w = sc.nextDouble(); double t = 0; if (w >= v) { double t1 = v / a; double s1 = a * t1 * t1 / 2; if (s1 > l) { t = Math.sqrt(2 * l / a); } else { t = t1 + (l - s1) / v; } } else { double t2 = Math.sqrt(2 * d / a); if (a * t2 <= w) { double t1 = v / a; double s1 = a * t1 * t1 / 2; if (s1 > l) { t = Math.sqrt(2 * l / a); } else { t = t1 + (l - s1) / v; } } else { double tup = v / a; double tdown = (v - w) / a; double sup = a * tup * tup / 2; double sdown = v * tdown - a * tdown * tdown / 2; if (sup + sdown <= d) { double tmax = (d - sup - sdown) / v; t = tup + tmax + tdown; } else { double tw = w / a; double sw = a * tw * tw / 2; double sl = (d - sw) / 2; double dis = w * w + 2 * a * sl; double tu1 = (- w - Math.sqrt(dis)) / a; if (tu1 < 0) { tu1 = (- w + Math.sqrt(dis)) / a; } t = tw + 2 * tu1; } double sreup = w * tdown + a * tdown * tdown / 2; if (sreup <= l - d) { t += tdown; t += (l - d - sreup) / v; } else { double dis = w * w - 2 * a * (d - l); double tu1 = (- w - Math.sqrt(dis)) / a; if (tu1 < 0) { tu1 = (- w + Math.sqrt(dis)) / a; } t += tu1; } } } System.out.println(t); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { static class Task { int NN = 1000001; int MOD = 1000000007; int INF = 2000000000; long INFINITY = 2000000000000000000L; public void solve(InputReader in, PrintWriter out) { long k = in.nextLong(); for(long mul = 1,d=1;;mul*=10,++d) { if(k > 9*mul*d) { k -= 9*mul*d; } else { for(long i=1;i<=9;++i) { if(k > mul*d) { k -= mul*d; } else { --k; long num = k / d; k %= d; String str = String.valueOf(num); while(str.length() < d - 1) { str = "0" + str; } str = String.valueOf(i) + str; out.println(str.charAt((int) k));return; } } } } } } static void prepareIO(boolean isFileIO) { //long t1 = System.currentTimeMillis(); Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); //out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); //fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Array { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); /* if ( k == 1 ){ System.out.println("1 1"); return; } */ int last[] = new int[100001]; int distinct = 0; for ( int i = 0 ; i < n ; ++i ) { int t = in.nextInt(); if ( last[t] == 0 ) ++distinct; last[t] = i+1; if ( distinct == k ) { int min = i+1; for ( int j = 0 ; j < last.length ; ++j ) { if ( last[j] != 0 ) min = min>last[j]?last[j]:min; } System.out.println(min+" "+(i+1)); return; } } System.out.println("-1 -1"); } }
linear
224_B. Array
CODEFORCES
import java.io.*; import java.util.*; public class Main { private static void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); String[] sa = new String[n]; for (int i = 0; i < n; i++) { sa[i] = in.next(); } Set<Integer> switches = new HashSet<>(); for (int i = 0; i < m; i++) { int cnt = 0, swtch = -1; for (int j = 0; j < n; j++) { if (sa[j].charAt(i) == '1') { cnt++; swtch = j; if (cnt > 1) break; } } if (cnt == 1) { switches.add(swtch); } } out.print(switches.size() == n ? "NO" : "YES"); } private static void shuffleArray(int[] array) { int index; Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { index = random.nextInt(i + 1); if (index != i) { array[index] ^= array[i]; array[i] ^= array[index]; array[index] ^= array[i]; } } } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); solve(in, out); in.close(); out.close(); } private static class InputReader { private BufferedReader br; private StringTokenizer st; InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); st = null; } String nextLine() { String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } String next() { while (st == null || !st.hasMoreTokens()) { String line = nextLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } private static class OutputWriter { BufferedWriter bw; OutputWriter(OutputStream os) { bw = new BufferedWriter(new OutputStreamWriter(os)); } void print(int i) { print(Integer.toString(i)); } void println(int i) { println(Integer.toString(i)); } void print(long l) { print(Long.toString(l)); } void println(long l) { println(Long.toString(l)); } void print(double d) { print(Double.toString(d)); } void println(double d) { println(Double.toString(d)); } void print(boolean b) { print(Boolean.toString(b)); } void println(boolean b) { println(Boolean.toString(b)); } void print(char c) { try { bw.write(c); } catch (IOException e) { e.printStackTrace(); } } void println(char c) { println(Character.toString(c)); } void print(String s) { try { bw.write(s); } catch (IOException e) { e.printStackTrace(); } } void println(String s) { print(s); print('\n'); } void close() { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
quadratic
985_B. Switches and Lamps
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1177b { public static void main(String[] args) throws IOException { long k = rl(), n = -1; for (long l = 0, r = k; l <= r; ) { long m = l + (r - l) / 2; if (f(m) < k) { n = m + 1; l = m + 1; } else { r = m - 1; } } k -= f(n - 1); char[] s = Long.toString(n).toCharArray(); prln(s[(int) k - 1]); close(); } static long f(long x) { if (x < 10) { return x; } long pow10 = 1, cnt = 1; while (x >= pow10 * 10) { pow10 *= 10; ++cnt; } return cnt * (x - pow10 + 1) + f(pow10 - 1); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // graph util static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static void pryesno(boolean b) {prln(b ? "yes" : "no");}; static void pryn(boolean b) {prln(b ? "Yes" : "No");} static void prYN(boolean b) {prln(b ? "YES" : "NO");} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();}}
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; public class A { FastScanner in; PrintWriter out; void solve() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); int res = 0; for (int i = 0; i < n; i++) { boolean ok = false; for (int j = 0; j < i; j++) { if (a[i] % a[j] == 0) { ok = true; } } if (!ok) { res++; } } out.println(res); } 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(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int a = input.nextInt(); int b = input.nextInt(); int x[] = new int[n]; for (int i=0; i<n; i++) x[i]=input.nextInt(); Arrays.sort(x); int y[] = new int[n]; for (int i=0; i<n; i++) y[i]=x[n-i-1]; System.out.println(y[a-1]-y[a]); } }
nlogn
169_A. Chores
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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int inv = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (a[j] > a[i]) { inv++; } } } int m = in.nextInt(); for (int i = 0; i < m; i++) { int l = in.nextInt(); int r = in.nextInt(); int s = (r - l + 1) * (r - l) / 2; inv = (inv + s) % 2; out.println(inv % 2 == 0 ? "even" : "odd"); } } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
quadratic
911_D. Inversion Counting
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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { static final long MODULO = (int) (1e9 + 7); public void solve(int testNumber, Scanner in, PrintWriter out) { long x = in.nextLong(); long k = in.nextLong(); if (x == 0) { out.println(0); } else { long e = modPow(2, k, MODULO); long y = 2 * x - 1; long w = ((e % MODULO) * (y % MODULO)) % MODULO; long z = (w + 1) % MODULO; out.println(z); } } private long modPow(long a, long b, long m) { if (b == 0) return 1 % m; if (b == 1) return a % m; long res = modPow(a, b / 2, m); res = (res * res) % m; if (b % 2 == 1) res = (res * a) % m; return res; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class q5 { public static void main(String[] args) throws IOException { Reader.init(System.in); PrintWriter out=new PrintWriter(System.out); long n=Reader.nextInt(); long k=Reader.nextLong(); long v=8*n+8*k+4; long v2=(long) Math.sqrt(v); long v3=2*n+2; //long v4=(v3+v2)/2; long v5=(v3-v2)/2; out.println(v5); out.flush(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init() throws IOException { reader = new BufferedReader( new FileReader("detect.in")); tokenizer = new StringTokenizer(""); } static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String nextLine() throws IOException{ return reader.readLine(); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
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.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FElongatedMatrix solver = new FElongatedMatrix(); solver.solve(1, in, out); out.close(); } } static class FElongatedMatrix { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int m = in.readInt(); int[][] mat = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mat[i][j] = in.readInt(); } } int[][] minDist = new int[n][n]; SequenceUtils.deepFill(minDist, (int) 1e9); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { minDist[i][j] = Math.min(minDist[i][j], Math.abs(mat[i][k] - mat[j][k])); } } } int[][] minDistBetweenHeadAndTail = new int[n][n]; SequenceUtils.deepFill(minDistBetweenHeadAndTail, (int) 1e9); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 1; k < m; k++) { minDistBetweenHeadAndTail[i][j] = Math.min(minDistBetweenHeadAndTail[i][j], Math.abs(mat[i][k] - mat[j][k - 1])); } } } Log2 log2 = new Log2(); BitOperator bo = new BitOperator(); int[][][] dp = new int[1 << n][n][n]; for (int i = 1; i < (1 << n); i++) { if (i == Integer.lowestOneBit(i)) { dp[i][log2.floorLog(i)][log2.floorLog(i)] = (int) 1e9; continue; } for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (bo.bitAt(i, j) == 0) { continue; } for (int t = 0; t < n; t++) { dp[i][j][k] = Math.max(dp[i][j][k], Math.min(dp[bo.setBit(i, j, false)][t][k], minDist[j][t])); } } } } int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ans = Math.max(ans, Math.min(dp[(1 << n) - 1][i][j], minDistBetweenHeadAndTail[j][i])); } } out.println(ans); } } static class SequenceUtils { public static void deepFill(Object array, int val) { if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof int[]) { int[] intArray = (int[]) array; Arrays.fill(intArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFill(obj, val); } } } } static class Log2 { public int floorLog(int x) { return 31 - Integer.numberOfLeadingZeros(x); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class BitOperator { public int bitAt(int x, int i) { return (x >> i) & 1; } public int setBit(int x, int i, boolean v) { if (v) { x |= 1 << i; } else { x &= ~(1 << i); } return x; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.SortedSet; import java.util.Set; import java.util.NavigableSet; import java.io.IOException; import java.util.InputMismatchException; import java.io.InputStreamReader; import java.util.TreeSet; import java.io.Writer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Niyaz Nigmatullin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int k = in.nextInt(); char[] c = in.next().toCharArray(); NavigableSet<Integer> ones = new TreeSet<>(); NavigableSet<Integer> zeros = new TreeSet<>(); for (int i = 0; i < n; i++) { if (c[i] == '0') zeros.add(i); else ones.add(i); } if (ones.isEmpty() || zeros.isEmpty() || ones.last() - ones.first() + 1 <= k || zeros.last() - zeros.first() + 1 <= k) { out.println("tokitsukaze"); return; } if (check(ones, n, k) && check(zeros, n, k)) { out.println("quailty"); return; } out.println("once again"); } private boolean check(NavigableSet<Integer> ones, int n, int k) { for (int i = 0; i + k <= n; i++) { int left = ones.first(); int right = ones.last(); if (left >= i) { left = ones.higher(i + k - 1); } if (right < i + k) { right = ones.lower(i); } if (right - left + 1 > k) { return false; } } return true; } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } static class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } public String next() { StringBuilder sb = new StringBuilder(); int c = read(); while (isWhiteSpace(c)) { c = read(); } if (c < 0) { return null; } while (c >= 0 && !isWhiteSpace(c)) { sb.appendCodePoint(c); c = read(); } return sb.toString(); } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } } }
linear
1190_C. Tokitsukaze and Duel
CODEFORCES
/* Roses are red Memes are neat All my test cases time out Lmao yeet */ import java.util.*; import java.io.*; public class x1185G1b { static long MOD = 1000000007L; public static void main(String args[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int T = Integer.parseInt(st.nextToken()); Song[] arr = new Song[N]; for(int i=0; i < N; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken())-1; arr[i] = new Song(a, b); } //bitmask long[][] dp = new long[1 << N][3]; Arrays.fill(dp[0], 1L); for(int mask=0; mask < dp.length; mask++) { for(int i=0; i < N; i++) if((mask & (1 << i)) == 0) { Song c = arr[i]; //continue all dp if mask == 0 if(mask == 0 && c.t <= T) { dp[mask|(1 << i)][c.g]++; dp[mask|(1 << i)][c.g] %= MOD; } //continue dp if not same genre else { for(int gen=0; gen < 3; gen++) if(gen != c.g) { dp[mask|(1 << i)][c.g] += dp[mask][gen]; dp[mask|(1 << i)][c.g] %= MOD; } //optimize? } } } long res = 0L; for(int mask=1; mask < dp.length; mask++) for(int i=0; i < 3; i++) { int sum = 0; for(int b=0; b < N; b++) if((mask & (1 << b)) > 0) sum += arr[b].t; if(sum == T) res = (res+dp[mask][i])%MOD; } System.out.println(res); } } class Song { public int t; public int g; public Song(int a, int b) { t = a; g = b; } } //cheerios are good for your heart, but are they good for your brain?
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class BetaRound16_E implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new BetaRound16_E(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { 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"); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } // solution double[] p; int n; double[][] a; void solve() throws IOException { n = readInt(); a = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = readDouble(); } } p = new double[1 << n]; Arrays.fill(p, -1); p[(1 << n) - 1] = 1; for (int i = 0; i < n; i++) { out.printf("%.12f ", p(1 << i)); } } double p(int mask) { if (p[mask] != -1) return p[mask]; double ans = 0; for (int eaten = 0; eaten < n; eaten++) { int prev = mask | (1 << eaten); if (prev != mask) { for (int eats = 0; eats < n; eats++) { if ((mask & (1 << eats)) != 0) { ans += a[eats][eaten] * p(prev); } } } } int bc = Integer.bitCount(mask); int norm = bc * (bc + 1) / 2; return p[mask] = ans / norm; } }
np
16_E. Fish
CODEFORCES
import java.util.StringTokenizer; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.io.IOException; import java.io.BufferedReader; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.ArrayList; public class p3 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } byte nextByte() { return Byte.parseByte(next()); } short nextShort() { return Short.parseShort(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader fr=new FastReader(); byte t=fr.nextByte(); while(t-->0) { short n=fr.nextShort(); short a[]=new short [n]; for (short i=-1;++i<n;) a[i]=fr.nextShort(); String s="1"; System.out.println(s); for(short i=0;++i<n;) { if(a[i]==1) { s+=".1"; System.out.println(s); } else if(a[i]==a[i-1]+1) { int c=s.lastIndexOf("."); s=s.substring(0,c+1)+a[i]; System.out.println(s); } else { for(;;) { s=s.substring(0,s.lastIndexOf(".")); int c=s.lastIndexOf("."); int b=Integer.parseInt(s.substring(c+1,s.length())); if(b+1==a[i]) { s=s.substring(0,c+1)+a[i]; System.out.println(s); break; } } } } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class A { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); String str[] = reader.readLine().split(" "); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(str[i]); } Arrays.sort(a); int k = 0; for (int i = 0; i < n; i++) { if (a[i] == 0){ continue; } for (int j = i + 1; j < n; j++) { if (a[j] % a[i] == 0){ a[j] = 0; } } k++; } System.out.println(k); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Locale; import java.util.StringTokenizer; public class Main { private void solve() throws IOException { int n = nextInt(); int x = nextInt(); int y = nextInt(); int c = nextInt(); int lux = x; int luy = y + 1; int rux = x + 1; int ruy = y; int ldx = x - 1; int ldy = y; int rdx = x; int rdy = y - 1; int k = 1; int res = 0; while (k < c) { lux--; luy--; rux--; ruy++; rdx++; rdy++; ldx++; ldy--; int p = 0; p += lu(x - 1, luy, lux, y, n); p += ru(x, ruy, rux, y + 1, n); p += ld(x, ldy, ldx, y - 1, n); p += rd(x + 1, rdy, rdx, y, n); k += p; res++; } println(res); } private int lu(int x1, int y1, int x2, int y2, int n) { if (y1 > 0 && x2 > 0) { return x1 - x2 + 1; } else if (y1 > 0 && x2 < 1) { return x1; } else if (y1 < 1 && x2 > 0) { return y2; } else if (x1 - (1 - y1) > 0) { return lu(x1 - (1 - y1), 1, x2, y2, n); } else { return 0; } } private int ru(int x1, int y1, int x2, int y2, int n) { if (y1 <= n && x2 > 0) { return x1 - x2 + 1; } else if (y1 <= n && x2 < 1) { return x1; } else if (y1 > n && x2 > 0) { return n - y2 + 1; } else if (x1 - (y1 - n) > 0) { return ru(x1 - (y1 - n), n, x2, y2, n); } else { return 0; } } private int ld(int x1, int y1, int x2, int y2, int n) { if (y1 > 0 && x2 <= n) { return x2 - x1 + 1; } else if (y1 > 0 && x2 > n) { return n - x1 + 1; } else if (y1 < 1 && x2 <= n) { return y2; } else if (x1 + (1 - y1) <= n) { return ld(x1 + (1 - y1), 1, x2, y2, n); } else { return 0; } } private int rd(int x1, int y1, int x2, int y2, int n) { if (y1 <= n && x2 <= n) { return x2 - x1 + 1; } else if (y1 <= n && x2 > n) { return n - x1 + 1; } else if (y1 > n && x2 <= n) { return n - y2 + 1; } else if (x1 + (y1 - n) <= n) { return rd(x1 + (y1 - n), n, x2, y2, n); } else { return 0; } } private String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(reader.readLine()); } return st.nextToken(); } @SuppressWarnings("unused") private int nextInt() throws IOException { return Integer.parseInt(next()); } @SuppressWarnings("unused") private double nextDouble() throws IOException { return Double.parseDouble(next()); } @SuppressWarnings("unused") private long nextLong() throws IOException { return Long.parseLong(next()); } @SuppressWarnings("unused") private void println(Object o) { writer.println(o); } @SuppressWarnings("unused") private void print(Object o) { writer.print(o); } private BufferedReader reader; private PrintWriter writer; private StringTokenizer st; private void run() throws IOException { long time = System.currentTimeMillis(); Locale.setDefault(Locale.US); reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); writer.close(); System.err.println(System.currentTimeMillis() - time); } public static void main(String[] args) throws IOException { new Main().run(); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
//package round43; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class C { Scanner in; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); char[] x = in.next().toCharArray(); int t = 0; for(int i = 0;i < n;i++){ if(x[i] == 'T'){ t++; } } int min = 9999; for(int i = 0;i < n;i++){ int y = 0; for(int j = i;j < i + t;j++){ if(x[j % n] == 'T'){ y++; } } min = Math.min(min, t - y); } out.println(min); } void run() throws Exception { in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(INPUT); out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new C().run(); } int ni() { return Integer.parseInt(in.next()); } void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.util.*; public class code_1 { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=in.nextInt(); Arrays.sort(a); for(int i=0;i<n-1;i++) { if(a[i]!=-1) { for(int j=i+1;j<n;j++) { if(a[j]%a[i]==0) a[j]=-1; } } } int count=0; for(int i=0;i<n;i++) { if(a[i]!=-1) count++; } System.out.println(count); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; import java.io.InputStream ; import java.util.InputMismatchException; import java.util.ArrayList; public class Main { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); //Scanner sc = new Scanner(); Reader in = new Reader(); Main solver = new Main(); solver.solve(out, in); out.flush(); out.close(); } void solve(PrintWriter out, Reader in) throws IOException{ int n = in.nextInt(); int m = in.nextInt(); int[] vert = new int[n+1]; for(int i=0 ;i<n ;i++) vert[i] = in.nextInt(); vert[n] = (int)1e9; int cnt=0,x,y; ArrayList<Integer> arr = new ArrayList<>(); for(int i=0 ;i<m ;i++) { x = in.nextInt(); y = in.nextInt(); in.nextInt(); if(x==1) arr.add(y); } horz = new int[arr.size()]; for(int i=0 ;i<arr.size();i++) horz[i] = arr.get(i); Arrays.sort(horz); Arrays.sort(vert); int ans = 2*(int)1e5+10; for(int i=0 ;i<=n ;i++){ int lesshorz = bs(vert[i],horz.length); ans = Math.min(ans,i+horz.length-lesshorz-1); } out.println(ans); } static int[] horz; static int bs(int num,int m){ int mid,lo=0,hi=m-1,r=-1; while(lo<=hi){ mid = (lo+hi)/2; if(horz[mid]<num){ lo = mid+1; r = mid; }else{ hi =mid-1; } } return r; } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
nlogn
1075_C. The Tower is Going Home
CODEFORCES
import java.util.*; import java.io.*; public class C{ public static void main(String args[]) throws Exception{ Scanner in = new Scanner(new FileReader("input.txt")); PrintWriter out = new PrintWriter(new File("output.txt")); int N = in.nextInt(); int M = in.nextInt(); int K = in.nextInt(); int[] X = new int[K], Y = new int[K]; for (int i = 0; i < K; i++){ X[i] = in.nextInt(); Y[i] = in.nextInt(); } int d = -1; int a = -1; int b = -1; for (int i = 1; i <= N; i++) for (int j = 1; j <= M; j++){ int h = Integer.MAX_VALUE; for (int p = 0; p < K; p++) h = Math.min(h,Math.abs(i-X[p]) + Math.abs(j-Y[p])); if (h > d){ d = h; a = i; b = j; } } out.print(a + " " + b); out.close(); } }
cubic
35_C. Fire Again
CODEFORCES
// Main Code at the Bottom import java.util.*; import java.io.*; public class Main{ //Fast IO class static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProperty("ONLINE_JUDGE") != null; //env=true; if(!env) { try { br=new BufferedReader(new FileReader("src\\input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } } else br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long MOD=(long)1e9+7; //debug static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Global variables and functions static long memo[]; static long C[][]; static long exp(long a,long x) { if(x==0) return 1; if(x%2==0) return exp((a*a)%MOD,x/2)%MOD; return ((a%MOD)*((exp((a*a)%MOD,x/2))%MOD))%MOD; } static void fill(int n) { C = new long[n+1][n+1]; for(int i = 1; i<=n;i++) C[i][0]=C[i][i]=1; for(int i=2;i<=n;i++) { for(int j=1;j<=n;j++) { C[i][j]=(C[i-1][j]+C[i-1][j-1])%MOD; } } } //Main function(The main code starts from here) public static void main (String[] args) throws java.lang.Exception { int test=1; //test=sc.nextInt(); while(test-->0) { int n = sc.nextInt(); MOD = sc.nextLong(); memo = new long[n+1]; fill(n); long dp[][] = new long[n+5][n+5]; for(int i=1;i<=n;i++) dp[i][i]=exp(2,i-1); for(int i = 2; i <= n; i++) { for(int j = 1; j < i; j++) { for(int k = 1; k <= j; k++) { long val = (dp[i-k-1][j-k]*C[j][k])%MOD; if(memo[k-1] ==0) memo[k-1] = exp(2, k-1); val=(val*memo[k-1])%MOD; dp[i][j]=(dp[i][j]+val)%MOD; } } } long ans = 0; for(int i=0;i<=n;i++) ans=(ans+dp[n][i])%MOD; out.println(ans); } out.flush(); out.close(); } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
///package round_global_14; import java.io.*; import java.util.*; public class B { static class InputReader { BufferedReader buffreader; StringTokenizer strtokenizer; public InputReader(InputStream inputstr) { buffreader = new BufferedReader(new InputStreamReader(inputstr), 1000000);strtokenizer = null; } ////////////////////////////////////////////////////////////////////////////////////////// String next() { while (strtokenizer == null || !strtokenizer.hasMoreTokens()) { try { strtokenizer = new StringTokenizer(buffreader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return strtokenizer.nextToken(); } /////////////////////////////////////////////////////////////////////////////////////////// public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArr(int n){ int[] arr=new int[n]; for (int i=0;i<n;i++){arr[i]=nextInt();} return arr;} public long[] nextLongArr(int n){ long[] arr=new long[n]; for (int i=0;i<n;i++){arr[i]=nextLong();} return arr;} public String[] nextStringArr(int n){ String[] arr=new String[n]; for (int i=0;i<n;i++){arr[i]=next();} return arr;} } static InputReader r = new InputReader(System.in); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args){ int t=r.nextInt(); for (int v=0;v<t;v++){ int n=r.nextInt(); if (n%2==1){ pw.println("NO"); } else{ int x=n/2; boolean check=false; for (int i=1;i<=(int)Math.sqrt(x)+1;i++){ if (i*i*2==x||i*i==x){ pw.println("YES");check=true;break; } } if (!check){ pw.println("NO"); } } } pw.close(); } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(),k=sc.nextInt(); for(int x=0;;x++) { if(2*1L*x+x*1L*(x+1)==2L*(k+n)) { out.println(n-x); break; } } out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
logn
1195_B. Sport Mafia
CODEFORCES
// https://codeforces.com/contest/1497/submission/110250082 import java.io.*; import java.util.*; public class CF1497E2 extends PrintWriter { CF1497E2() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; byte[] bb = new byte[1 << 15]; int i, n; byte getc() { if (i == n) { i = n = 0; try { n = in.read(bb); } catch (IOException e) {} } return i < n ? bb[i++] : 0; } int nextInt() { byte c = 0; while (c <= ' ') c = getc(); int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); } return a; } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1497E2 o = new CF1497E2(); o.main(); o.flush(); } static final int A = 10000000, K = 20; int[] cc = new int[A + 1]; { for (int a = 1; a <= A; a++) cc[a] = a; for (int a = 2; a <= A / a; a++) { int s = a * a; for (int b = s; b <= A; b += s) while (cc[b] % s == 0) cc[b] /= s; } } void main() { int[] pp = new int[A + 1]; Arrays.fill(pp, -1); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int[] aa = new int[n]; for (int i = 0; i < n; i++) aa[i] = cc[sc.nextInt()]; int[] mp = new int[k + 1]; int[] ip = new int[k + 1]; for (int i = 0; i < n; i++) { int a = aa[i]; for (int h = k; h >= 0; h--) { if (pp[a] >= ip[h]) { mp[h]++; ip[h] = i; } if (h > 0 && (mp[h - 1] < mp[h] || mp[h - 1] == mp[h] && ip[h - 1] > ip[h])) { mp[h] = mp[h - 1]; ip[h] = ip[h - 1]; } } pp[a] = i; } println(mp[k] + 1); for (int i = 0; i < n; i++) { int a = aa[i]; pp[a] = -1; } } } }
cubic
1497E2
CODEFORCES
/** * author: derrick20 * created: 3/19/21 11:57 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class E2_SquareFreeDivision2 { static FastScanner sc = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { // generate(); int MAX = (int) 1e7; int[] spf = new int[MAX + 1]; for (int i = 2; i <= MAX; i++) { if (spf[i] == 0) { spf[i] = i; for (int j = i + i; j <= MAX; j += i) { if (spf[j] == 0) { spf[j] = i; } } } } int[] freq = new int[MAX + 1]; int T = sc.nextInt(); while (T-->0) { int N = sc.nextInt(); int K = sc.nextInt(); int[] a = new int[N + 1]; for (int i = 1; i <= N; i++) { a[i] = sc.nextInt(); int canonical = 1; while (a[i] > 1) { int factor = spf[a[i]]; int parity = 0; while (a[i] % factor == 0) { a[i] /= factor; parity ^= 1; } if (parity == 1) { canonical *= factor; } } a[i] = canonical; } int[][] transition = new int[K + 1][N + 1]; // HashMap<Integer, Integer> freq = new HashMap<>(); for (int k = 0; k <= K; k++) { int l = N + 1; int duplicates = 0; for (int r = N; r >= 1; r--) { while (l - 1 >= 1) { int nextDuplicates = duplicates; if (freq[a[l - 1]] >= 1) { nextDuplicates++; } if (nextDuplicates <= k) { duplicates = nextDuplicates; freq[a[l - 1]]++; l--; } else { break; } } transition[k][r] = l; if (--freq[a[r]] >= 1) { duplicates--; } } } int[][] dp = new int[K + 1][N + 1]; int oo = (int) 1e9; for (int[] row : dp) { Arrays.fill(row, oo); } for (int k = 0; k <= K; k++) { dp[k][0] = 0; } for (int r = 1; r <= N; r++) { for (int k = 0; k <= K; k++) { for (int delta = 0; delta <= k; delta++) { dp[k][r] = min(dp[k][r], dp[k - delta][transition[delta][r] - 1] + 1); } } } out.println(dp[K][N]); } out.close(); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private 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); } } char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } int nextInt() { return (int) nextLong(); } long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } double nextDouble() { boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } double cur = nextLong(); if (c != '.') { return neg ? -cur : cur; } else { double frac = nextLong() / cnt; return neg ? -cur - frac : cur + frac; } } String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
cubic
1497E2
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.stream.IntStream; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; 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) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); SquareFreeDivisionHardVersion solver = new SquareFreeDivisionHardVersion(); solver.solve(1, in, out); out.close(); } static class SquareFreeDivisionHardVersion { static final int MAX = 10000001; public void solve(int testNumber, InputReader in, OutputWriter out) { int t = in.nextInt(); int[] d = PrimesAndDivisors.generateDivisors(MAX); int[] reduced = new int[MAX]; for (int i = 1; i < MAX; i++) { int val = i; reduced[i] = 1; while (val != 1) { int prime = d[val], exponent = 0; while (val % prime == 0) { val /= prime; exponent ^= 1; } if (exponent > 0) reduced[i] *= prime; } } int counter = 0; int[] seen = new int[MAX]; for (int jjjj = 0; jjjj < t; jjjj++) { int n = in.nextInt(), k = in.nextInt(); int[] a = in.readIntArray(n); for (int x : a) seen[reduced[x]] = -1; int[][] dp = new int[n + 1][k + 1]; TreeSet<Integer> ts = new TreeSet<>(); int num = 0; for (int i = 0; i < n; i++) { int R = reduced[a[i]]; if (seen[R] != -1) { ts.add(-seen[R]); if (ts.size() > k + 1) ts.remove(ts.last()); num++; } Arrays.fill(dp[i], n + 1); for (int j = num; j <= k; j++) dp[i][j] = 1; seen[R] = i; int u = 0; for (int r : ts) { for (int j = u; j <= k; j++) dp[i][j] = Integer.min(dp[i][j], dp[-r][j - u] + 1); u++; } // System.out.println(i + " " + Arrays.toString(dp[i])); // System.out.println("Treeset : " + ts); } out.println(dp[n - 1][k]); } } } 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[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } 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 int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class PrimesAndDivisors { public static int[] generateDivisors(int n) { int[] divisors = IntStream.range(0, n + 1).toArray(); for (int i = 2; i * i <= n; i++) if (divisors[i] == i) for (int j = i * i; j <= n; j += i) divisors[j] = i; return divisors; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } }
cubic
1497E2
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Solution{ static class Node implements Comparable<Node>{ int sum; int l; int r; Node next; int nb; Node ini; boolean not; public Node(int sum,int l,int r){ this.sum = sum; this.l = l; this.r = r; nb = 0; not = false; ini = null; } @Override public int compareTo(Node node){ if(sum-node.sum!=0) return sum-node.sum; else if(l-node.l!=0) return l-node.l; else return r - node.r; } } public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(st.nextToken()); TreeSet<Node> ts = new TreeSet<Node>(); st = new StringTokenizer(br.readLine()); int[] a = new int[n+1]; for(int i=1;i<=n;i++) a[i] = Integer.parseInt(st.nextToken()); int[] s = new int[n+1]; for(int i=1;i<=n;i++) s[i] = s[i-1] + a[i]; for(int i=1;i<=n;i++){ for(int j=i;j<=n;j++){ ts.add(new Node(s[j]-s[i-1],i,j)); } } int minvalue = -2000*(int)Math.pow(10,5); int maxvalue = 2000*(int)Math.pow(10,5); ts.add(new Node(minvalue,0,0)); ts.add(new Node(maxvalue,0,0)); //System.out.println(minvalue); Node node = ts.higher(ts.first()); int sum = 0; int max = 0; Node m = null; while(node.sum!=maxvalue){ sum = node.sum; while(node.sum==sum){ node = ts.higher(node); } Node var = ts.lower(node); // System.out.println(sum+" "+var.sum); max = 0; while(var.sum==sum){ Node next = ts.higher(new Node(sum,var.r+1,0)); if(max>1+next.nb){ var.nb = max; var.ini = m; } else if(next.ini==null){ var.nb = 1 + next.nb; var.next = next; if(max<var.nb){ max = var.nb; m = var; } }else{ var.nb = 1 + next.nb; var.next = next.ini; if(max<var.nb){ max = var.nb; m = var; } } var = ts.lower(var); //System.out.println(sum+" "+var.sum); } } int k = 0; Node best = new Node(minvalue,0,0); //var = new Node(minvalue,0,0); for(Node var:ts){ if(k<var.nb){ k = var.nb; best = var; if(var.ini!=null) best = var.ini; } } if(k==0) System.out.println("erreur"); else{ out.println(k); sum = best.sum; while(best.sum==sum){ out.println(best.l+" "+best.r); best = best.next; } } out.flush(); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.*; public class Main { static double arr[][]; public static void main(String[] args) { try { Parserdoubt pd=new Parserdoubt(System.in); PrintWriter pw=new PrintWriter(System.out); int fishes=pd.nextInt(); arr=new double[fishes][fishes]; for(int i=0;i<fishes;i++) for(int j=0;j<fishes;j++) arr[i][j]=Double.parseDouble(pd.nextString()); double dp[]=new double[(1<<fishes)]; dp[dp.length-1]=1.0; for(int c=dp.length-1;c>=0;c--) { int count=Integer.bitCount(c); if(count<=1) continue; for(int i=0;i<fishes;i++) for(int j=i+1;j<fishes;j++) { if(((1<<i)&c)!=0&&((1<<j)&c)!=0) { dp[c&~(1<<j)]+=arr[i][j]*dp[c]; dp[c&~(1<<i)]+=arr[j][i]*dp[c]; } } } double s=0.0; for(int i=0;i<fishes;i++) s+=dp[1<<i]; for(int i=0;i<fishes;i++) dp[1<<i]/=s; int i=0; for(i=0;i<fishes-1;i++) pw.printf("%.6f ",dp[1<<i]); pw.printf("%.6f\n",dp[1<<i]); pw.close(); } catch(Exception e) {} } } class Parserdoubt { final private int BUFFER_SIZE = 1 << 17; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parserdoubt(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws Exception { StringBuffer sb=new StringBuffer(""); byte c = read(); while (c <= ' ') c = read(); do { sb.append((char)c); c=read(); }while(c>' '); return sb.toString(); } public char nextChar() throws Exception { byte c=read(); while(c<=' ') c= read(); return (char)c; } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
np
16_E. Fish
CODEFORCES
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.ObjectInputStream.GetField; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import javax.sound.sampled.ReverbType; public class N718 { static PrintWriter out; static Scanner sc; static ArrayList<int[]>q,w,x; static ArrayList<Integer>adj[]; static HashSet<Integer>primesH; static boolean prime[]; //static ArrayList<Integer>a; static HashSet<Long>tmp; static int[][][]dist; static boolean[]v; static int[]a,b,c,d; static Boolean[][]dp; static char[][]mp; static int A,B,n,m,h,ans,sum; //static String a,b; static long oo=(long)1e9+7; public static void main(String[]args) throws IOException { sc=new Scanner(System.in); out=new PrintWriter(System.out); //A(); //B(); //C(); D(); //E(); //F(); //G(); out.close(); } private static void A() throws IOException { int t=ni(); while(t-->0) { long l=nl(); if(l%2050!=0)ol(-1); else { long num=l/2050; int cnt=0; while(num>0) { cnt+=num%10; num/=10; } ol(cnt); } } } static void B() throws IOException { int t=ni(); while(t-->0) { int n=ni(),m=ni(); int[][]a=nmi(n,m); PriorityQueue<int[]>pq=new PriorityQueue<int[]>((u,v)->u[0]-v[0]); ArrayList<Integer>[]nums=new ArrayList[n]; for(int i=0;i<n;i++) { //nums[i]=new ArrayList<Integer>(); for(int j=0;j<m;j++) { ///nums[i].add(a[i][j]); pq.add(new int[] {a[i][j],i}); } } int[][]ans=new int[n][m]; for(int i=0;i<m;i++) { int[]x=pq.poll(); ans[x[1]][i]=x[0]; } int []indices=new int[n]; while(!pq.isEmpty()) { int[]x=pq.poll(); int i=x[1]; while(ans[i][indices[i]]!=0) { indices[i]++; } ans[i][indices[i]]=x[0]; } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { out.print(ans[i][j]+" "); } ol(""); } } } static void C() throws IOException{ int t=1; while(t-->0) { int n=ni(); a=nai(n); int[][]ans=new int[n][n]; for(int i=0;i<n;i++)ans[i][i]=a[i]; for(int i=n-1;i>=0;i--) { int j=i,k=i; int cur=ans[i][i]; cur--; while(cur>0) { j++; if(j>=n||ans[j][k]!=0) { j--; k--; } ans[j][k]=ans[i][i]; cur--; } } for(int i=0;i<n;i++) { for(int j=0;j<=i;j++) { out.print(ans[i][j]+" "); } ol(""); } } } private static Boolean dp(int i, int j) { if(j>sum/2)return false; if(i==x.size()) { return sum/2==j; } if(dp[i][j]!=null)return dp[i][j]; return dp[i][j]=dp(i+1,j+x.get(i)[0])||dp(i+1,j); } static boolean isPrime(long n) { if(n==2)return true; if(n<2||n%2==0)return false; for(long i=3L;i*i<n;i+=2l) { long rem=(n%i); if(rem==0)return false; } return true; } static void D() throws IOException { int t=1; while(t-->0) { int n=ni(),m=ni(),k=ni(); int[][]ans=new int[n][m]; dist=new int[n][m][4]; for(int i=0;i<n;i++)for(int j=0;j>m;j++) Arrays.fill(dist[i][j], Integer.MAX_VALUE); int x; for(int i=0;i<n;i++) { for(int j=0;j<m-1;j++) { dist[i][j][2]=(x=ni()); dist[i][j+1][3]=x; } } for(int i=0;i<n-1;i++) { for(int j=0;j<m;j++) { dist[i][j][1]=(x=ni()); dist[i+1][j][0]=x; } } int[][]nans=new int[n][m]; if(k%2==1) { for(int i=0;i<n;i++)Arrays.fill(ans[i], -1); }else { for(int ii=0;ii<k/2;ii++) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { nans[i][j]=Integer.MAX_VALUE; if(i>0) nans[i][j]=Math.min(nans[i][j], ans[i-1][j]+dist[i-1][j][1]); if(i<n-1) nans[i][j]=Math.min(nans[i][j], ans[i+1][j]+dist[i+1][j][0]); if(j>0) nans[i][j]=Math.min(nans[i][j], ans[i][j-1]+dist[i][j-1][2]); if(j<m-1) nans[i][j]=Math.min(nans[i][j], ans[i][j+1]+dist[i][j+1][3]); } } int[][]tmp=ans; ans=nans; nans=tmp; } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(ans[i][j]!=-1)ans[i][j]*=2; out.print(ans[i][j]+" "); } ol(""); } } } private static int bfs(int i, int j,int k) { boolean [][]vis=new boolean[dist.length][dist[0].length]; Queue<int[]>q=new LinkedList<int[]>(); int mn=Integer.MAX_VALUE; q.add(new int[] {i,j,0,0}); int[]dx=new int[] {-1,1,0,0}; int[]dy=new int[] {0,0,1,-1}; while(!q.isEmpty()) { int []x=q.poll(); vis[x[0]][x[1]]=true; int c=x[2]; if(c>k/2)continue; if(c>0&&k%c==0&&(k/c)%2==0) { mn=Math.min(mn,x[3]*k/c ); } for(int a=0;a<4;a++) { int nx=x[0]+dx[a]; int ny=x[1]+dy[a]; if(valid(nx,ny)&&!vis[nx][ny]) { q.add(new int[] {nx,ny,c+1,x[3]+dist[x[0]][x[1]][a]}); } } } return mn; } private static boolean valid(int nx, int ny) { return nx>=0&&nx<dist.length&&ny>=0&&ny<dist[0].length; } static int gcd (int a, int b) { return b==0?a:gcd (b, a % b); } static void E() throws IOException { int t=ni(); while(t-->0) { } } static void F() throws IOException { int t=ni(); while(t-->0) { } } static void CC() throws IOException { for(int kk=2;kk<21;kk++) { ol(kk+" -------"); int n=kk; int k=n-2; int msk=1<<k; int[]a=new int[k]; for(int i=0;i<a.length;i++)a[i]=i+2; int mx=1; int ms=0; for(int i=1;i<msk;i++) { long prod=1; int cnt=0; for(int j=0;j<a.length;j++) { if(((i>>j)&1)!=0) { prod*=a[j]; cnt++; } } if(cnt>=mx&&prod%n==1) { mx=cnt; ms=i; } } ol(mx==1?mx:mx+1); out.print(1+" "); long pr=1; for(int j=0;j<a.length;j++) { if(((ms>>j)&1)!=0) { out.print(a[j]+" "); pr*=a[j]; } } ol(""); ol("Prod: "+pr); ol(n+"*"+((pr-1)/n)+" + "+1); } } static int ni() throws IOException { return sc.nextInt(); } static double nd() throws IOException { return sc.nextDouble(); } static long nl() throws IOException { return sc.nextLong(); } static String ns() throws IOException { return sc.next(); } static int[] nai(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); return a; } static long[] nal(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = sc.nextLong(); return a; } static int[][] nmi(int n,int m) throws IOException{ int[][]a=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=sc.nextInt(); } } return a; } static long[][] nml(int n,int m) throws IOException{ long[][]a=new long[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=sc.nextLong(); } } return a; } static void o(String x) { out.print(x); } static void ol(String x) { out.println(x); } static void ol(int x) { out.println(x); } static void disp1(int []a) { for(int i=0;i<a.length;i++) { out.print(a[i]+" "); } out.println(); } static class Scanner { StringTokenizer st; BufferedReader br; 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 boolean hasNext() {return st.hasMoreTokens();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static long factorial[],invFactorial[]; static HashSet<Pair> graph[]; static boolean oj = System.getProperty("ONLINE_JUDGE") != null; /****************************************Solutions Begins***************************************/ public static void main (String[] args) throws Exception { String st[]=nl(); int n=pi(st[0]); int input[]=new int[n]; st=nl(); for(int i=0;i<n;i++){ input[i]=pi(st[i]); } int ans=0; Arrays.sort(input); boolean dp[]=new boolean[n]; for(int i=0;i<n;i++){ if(!dp[i]){ ans++; for(int j=input[i];j<=200;j+=input[i]){ for(int k=i;k<n;k++){ if(input[k]==j&&!dp[k])dp[k]=true; } } } } out.println(ans); /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ static String[] nl() throws Exception{ return br.readLine().split(" "); } static String[] nls() throws Exception{ return br.readLine().split(""); } static int pi(String str) { return Integer.parseInt(str); } static long pl(String str){ return Long.parseLong(str); } static double pd(String str){ return Double.parseDouble(str); } /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.000000000000000000000"); out.println(ft.format(d)); } /**************************************Bit Manipulation**************************************************/ static void printMask(long mask){ System.out.println(Long.toBinaryString(mask)); } static int countBit(int mask){ int ans=0; while(mask!=0){ if(mask%2==1){ ans++; } mask/=2; } return ans; } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new HashSet[n]; for(int i=0;i<n;i++){ graph[i]=new HashSet<>(); } } static void addEdge(int a,int b){ graph[a].add(new Pair(b,1)); } static void addEdge(int a,int b,int c){ graph[a].add(new Pair(b,c)); } /*********************************************PAIR********************************************************/ static class PairComp implements Comparator<Pair>{ public int compare(Pair p1,Pair p2){ return p1.u-p2.u; } } static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /******************************************Long Pair*******************************************************/ static class PairCompL implements Comparator<Pairl>{ public int compare(Pairl p1,Pairl p2){ if(p1.u-p2.u<0){ return -1; } else if(p1.u-p2.u>0){ return 1; } else{ if(p1.v-p2.v<0){ return -1; } else if(p1.v-p2.v>0){ return 1; } else{ return 0; } } } } static class Pairl implements Comparable<Pairl> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pairl other = (Pairl) o; return u == other.u && v == other.v; } public int compareTo(Pairl other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o) { if(!oj) System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y) { if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /********************************************End***********************************************************/ }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; public class Main { public static void main(String[] args) throws Exception { // TODO code application logic here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int iTotTerm, i, j, iSml = 0, iPos = 0; iTotTerm = Integer.parseInt(br.readLine()); String seq[]; seq = br.readLine().split(" "); int iSeq[] = new int[iTotTerm]; for (i = 0; i < iTotTerm; i++) { iSeq[i] = Integer.parseInt(seq[i]); } for (i = 0; i < iTotTerm; i++) { iSml = iSeq[i]; iPos = i; for (j = i; j < iTotTerm; j++) { if (iSeq[j] < iSml) { iSml = iSeq[j]; iPos = j; } } iSeq[iPos] = iSeq[i]; iSeq[i] = iSml; if (i != 0 && iSeq[i - 1] != iSeq[i]) { break; } } if (iSml != iSeq[0]) { System.out.print(iSml); } else { System.out.print("NO"); } } }
nlogn
22_A. Second Order Statistics
CODEFORCES