src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.util.*; import java.io.*; public class C{ static PrintWriter out; static InputReader in; public static void main(String args[]){ out = new PrintWriter(System.out); in = new InputReader(); new C(); out.flush(); out.close(); } C(){ int w = solve(); out.print(w == 0 ? "sjfnb" : "cslnb"); } int n; long a[]; int solve(){ n = in.nextInt(); a = new long[n]; long sum = 0; for(int i = 0; i < n; i++)sum += a[i] = in.nextLong(); if(sum == 0){ return 1; } Arrays.sort(a); int c = 0, c0 = 0; long p = -1, max = 0; int f = 0; long t = -1; int pp = -1; for(int i = 0; i < n; i++){ if(a[i] == p){ c++; }else{ if(p == 0)c0 = c; if(c >= 2){f++; t = p; pp = i - 2;} max = Math.max(max, c); p = a[i]; c = 1; } } max = Math.max(max, c); sum = 0; if(c >= 2){f++; t = p; pp = n - 2;} if(max > 2 || c0 > 1 || f > 1)return 1; if(f == 1){ long v = Arrays.binarySearch(a, t - 1); if(v >= 0)return 1; a[pp]--; sum = 1; } p = -1; for(int i = 0; i < n; i++){ sum += a[i] - (p + 1); a[i] = p + 1; p = a[i]; } return 1 - (int)(sum % 2); } public static class InputReader{ BufferedReader br; StringTokenizer st; InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){} } return st.nextToken(); } } }
linear
1190_B. Tokitsukaze, CSL and Stone Game
CODEFORCES
import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import java.io.*; import java.math.*; import java.util.*; @SuppressWarnings("unused") public class A { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); long n = in.nextLong(); System.out.println("0 0 " + n); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; import static java.util.Arrays.*; public class A { private static final int mod = (int)1e9+9; final IOFast io = new IOFast(); long k; boolean ok(long n, long m, long x) { long u = k * x; long val = u; val += (m - u) / (k - 1) * k; if((m - u) % (k - 1) == 0) val -= 1; else val += (m - u) % (k - 1); return val <= n; } long rec(long n, long m, long cur) { long pow = 1; long p = 1000; for(int i = 0; i < p; i++) pow = pow * 2 % mod; while(true) { if(ok(n, m, 0)) { return (m + cur) % mod; } if(!ok(n - p * k, m - p * k, p)) { n -= p * k; m -= p * k; cur = cur * pow % mod; cur += (pow - 1) * 2 * k % mod; cur %= mod; continue; } n -= k; m -= k; cur += k; cur = cur * 2 % mod; // System.err.println(cur); } } public void run() throws IOException { long n = io.nextLong(); long m = io.nextLong(); k = io.nextLong(); io.out.println(rec(n, m, 0)); if(true) return; long low = -1, high = m / k + 1; while(high - low > 1) { long mid = (low + high) / 2; if(!ok(n, m, mid)) { low = mid; } else { high = mid; } // System.err.println(mid + " " + (u + (m - u - k) / (k - 1) * k + k - 1 + (m - u) % (k - 1)) + " " + n); } long pow = powmod(2, high, mod); long score = m - high * k; score = (score + (pow - 1) * 2 * k) % mod; io.out.println(score); } static long powmod(long n, long r, int m) { long res = 1; for(; r != 0; r >>>= 1, n = n * n % m) { if((r&1) == 1) { res = res * n; if(res >= m) { res %= m; } } } return res; } void main() throws IOException { // IOFast.setFileIO("rle-size.in", "rle-size.out"); try { run(); } catch (EndOfFileRuntimeException e) { } io.out.flush(); } public static void main(String[] args) throws IOException { new A().main(); } static class EndOfFileRuntimeException extends RuntimeException { private static final long serialVersionUID = -8565341110209207657L; } static public class IOFast { private BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private PrintWriter out = new PrintWriter(System.out); void setFileIO(String ins, String outs) throws IOException { in = new BufferedReader(new FileReader(ins)); out = new PrintWriter(new FileWriter(outs)); } // private static final int BUFFER_SIZE = 50 * 200000; private static int pos, readLen; private static final char[] buffer = new char[1024 * 8]; private static final char[] str = new char[500000*8*2]; private static boolean[] isDigit = new boolean[256]; private static boolean[] isSpace = new boolean[256]; private static boolean[] isLineSep = new boolean[256]; static { for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; isLineSep['\r'] = isLineSep['\n'] = true; } public int read() throws IOException { if(pos >= readLen) { pos = 0; readLen = in.read(buffer); if(readLen <= 0) { throw new EndOfFileRuntimeException(); } } return buffer[pos++]; } public int nextInt() throws IOException { return Integer.parseInt(nextString()); } public long nextLong() throws IOException { return Long.parseLong(nextString()); } public char nextChar() throws IOException { while(true) { final int c = read(); if(!isSpace[c]) { return (char)c; } } } int reads(char[] cs, int len, boolean[] accept) throws IOException { try { while(true) { final int c = read(); if(accept[c]) { break; } str[len++] = (char)c; } } catch(EndOfFileRuntimeException e) { ; } return len; } public char[] nextLine() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(str, len, isLineSep); try { if(str[len-1] == '\r') { len--; read(); } } catch(EndOfFileRuntimeException e) { ; } return Arrays.copyOf(str, len); } public String nextString() throws IOException { return new String(next()); } public char[] next() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(str, len, isSpace); return Arrays.copyOf(str, len); } public double nextDouble() throws IOException { return Double.parseDouble(nextString()); } } }
logn
338_A. Quiz
CODEFORCES
import java.util.*; public class Paint { public static void main (String srgs[] ){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); TreeSet<Integer> ts=new TreeSet<>(); for(int i=0;i<n;++i){ ts.add(sc.nextInt()); } int x=0; int a[]=new int[ts.size()]; for(int y:ts){ a[x++]=y; } for(int i=0;i<ts.size()-1;++i){ for(int j=i+1;j<ts.size();++j){ if((a[i]!=-1)&&(a[j]!=-1)&&(a[j]%a[i]==0)){ a[j]=-1; } } } int c=0; for(int z:a){ if(z!=-1)++c; } System.out.print(c); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.io.*; import java.text.DecimalFormat; public class Main{ final long mod = (int)1e9+7, IINF = (long)1e19; final int MAX = (int)5e5+1, MX = (int)1e7+1, INF = (int)1e9, root = 3; DecimalFormat df = new DecimalFormat("0.0000000000000"); double eps = 1e-9, PI = 3.141592653589793238462643383279502884197169399375105820974944; static boolean multipleTC = false, memory = false; FastReader in;PrintWriter out; public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); for(int i = 1, T= (multipleTC)?ni():1; i<= T; i++)solve(i); out.flush(); out.close(); } void solve(int TC) throws Exception{ int n = ni(); long d = nl(); long ans = 2; long[] p = new long[n]; for(int i = 0; i< n; i++)p[i] = nl(); for(int i = 1; i< n; i++){ if(p[i]-p[i-1] == 2*d)ans++; else if(p[i]-p[i-1]>2*d)ans+=2; } pn(ans); } int[] reverse(int[] a){ int[] o = new int[a.length]; for(int i = 0; i< a.length; i++)o[i] = a[a.length-i-1]; return o; } int[] sort(int[] a){ if(a.length==1)return a; int mid = a.length/2; int[] b = sort(Arrays.copyOfRange(a,0,mid)), c = sort(Arrays.copyOfRange(a,mid,a.length)); for(int i = 0, j = 0, k = 0; i< a.length; i++){ if(j<b.length && k<c.length){ if(b[j]<c[k])a[i] = b[j++]; else a[i] = c[k++]; }else if(j<b.length)a[i] = b[j++]; else a[i] = c[k++]; } return a; } long[] sort(long[] a){ if(a.length==1)return a; int mid = a.length/2; long[] b = sort(Arrays.copyOfRange(a,0,mid)), c = sort(Arrays.copyOfRange(a,mid,a.length)); for(int i = 0, j = 0, k = 0; i< a.length; i++){ if(j<b.length && k<c.length){ if(b[j]<c[k])a[i] = b[j++]; else a[i] = c[k++]; }else if(j<b.length)a[i] = b[j++]; else a[i] = c[k++]; } return a; } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n(){return in.next();} String nln(){return in.nextLine();} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.util.*; public class codea{ public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int arr[] = new int[n]; for(int i =0;i<n;i++) arr[i]= in.nextInt(); Arrays.sort(arr); int max =0; boolean check[]= new boolean [n]; int count=0; for(int i =0;i<n;i++) { if(!check[i]) { count++; for(int j=i;j<n;j++) { if(arr[j]%arr[i]==0) check[j]=true; } } } System.out.println(count); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /* */ public class C455 { static int N; static final int mod = 1_000_000_007; static int[][] memo; static int[] list; public static void main(String[] args) { FS scan = new FS(System.in); N = scan.nextInt(); list = new int[N]; for(int i=0;i<N;i++) { list[i] = scan.next().equals("s")?0:1; } if(list[N-1] == 1) { System.out.println(0); return; } memo = new int[N+1][N+2]; Arrays.fill(memo[N], 1); int[] sum = new int[N+2]; for(int i=N-1;i>=0;i--) { sum[0] = memo[i+1][0]; for(int j=1;j<sum.length;j++) { sum[j] = sum[j-1] + memo[i+1][j]; sum[j] %= mod; } for(int j=0;j<=N;j++) { if (list[i]==1 && (i==0 || list[i-1]==1)) memo[i][j] = memo[i+1][j+1]; else if(i==0 || list[i-1] == 1) memo[i][j] = memo[i+1][j]; else if (list[i]==1){ // for(int k=0;k<=j;k++) { // memo[i][j] += memo[i+1][k+1]; // } memo[i][j] = sum[j+1] - sum[0] + mod; memo[i][j] %= mod; } else if (list[i]==0) { memo[i][j] = sum[j]; } } } // for(int i=0;i<=N;i++) { // for(int j=0;j<=N;j++) { // System.out.print(memo[i][j]+" "); // } // System.out.println(); // } // System.out.println(); System.out.println(memo[0][0]); } private static class FS { BufferedReader br; StringTokenizer st; public FS(InputStream in) { br = new BufferedReader(new InputStreamReader(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());} } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class test { public static void main(String[] args) { Scanner kb = new Scanner(System.in); int n = kb.nextInt(); int a = kb.nextInt(); int b = kb.nextInt(); int array[] = new int[n]; for (int i = 0; i < n; i++) { array[i] = kb.nextInt(); } Arrays.sort(array); int k = 0; int t1 = 0; int t2 = 0; for (int i = 0; i < b; i++) { t1= array[i]; if(i<n-1){ t2=array[i+1]; k=t2-t1; } else k=0; } System.out.println(k); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.*; public class A { public static void main(String[] args){ FastScanner sc = new FastScanner(); int n = sc.nextInt(); String nStr = Integer.toString(n); String nStr1 = nStr.substring(0, nStr.length() - 1); String nStr2 = nStr.substring(0, nStr.length() - 2) + nStr.charAt(nStr.length() - 1); int result = Math.max(n, Integer.parseInt(nStr1)); result = Math.max(result, Integer.parseInt(nStr2)); System.out.println(result); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.util.*; import java.lang.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.*; import java.math.*; public class Main { public void dfs(ArrayList<Integer>[] graph,int[] visited,int source) { } public static void main(String[] args) throws Exception{ Reader.init(System.in); PrintWriter out = new PrintWriter(System.out); Main mm =new Main(); int n=Reader.nextInt(); int m=Reader.nextInt(); String s=Reader.next(); int[][] count=new int[m][m]; for(int i=1;i<n;i++) { count[s.charAt(i)-'a'][s.charAt(i-1)-'a']++; count[s.charAt(i-1)-'a'][s.charAt(i)-'a']++; } int[] dp=new int[1<<m]; Arrays.fill(dp, Integer.MAX_VALUE/10); for(int i=0;i<m;i++) { dp[1<<i]=0; } for(int i=0;i<(1<<m);i++) { int extra=0; for(int j=0;j<m;j++) { if((i&(1<<j))>0) { for(int k=0;k<m;k++) { if(j!=k && (i&(1<<k))==0) { extra+=count[j][k]; } } } } for(int j=0;j<m;j++) { if((i&(1<<j))==0) { dp[i|(1<<j)]=Math.min(dp[i|(1<<j)], dp[i]+extra); } } } out.println(dp[(1<<m)-1]); out.close(); } } 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("input.txt")); 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() ); } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws IOException { InputReader in = new InputReader(); int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); if (k > n) { System.out.println(-1 + " " + -1); return; } int[] v = new int[100010]; int cnt = 0; for (int i = 0; i < k; i++) { if (v[a[i]] == 0) { cnt++; } v[a[i]]++; } int i = k; while (cnt < k && i < n) { if (v[a[i]] == 0) { cnt++; } v[a[i]]++; i++; } if (cnt != k) { System.out.println(-1 + " " + -1); } else { int st = 0; while (st < n && st < i && v[a[st]] > 1) { v[a[st]]--; st++; } System.out.println((st+1) + " " + (i)); } } static class InputReader { BufferedReader in; StringTokenizer st; public InputReader() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(in.readLine()); } public String next() throws IOException { while (!st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
linear
224_B. Array
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * Problem solution template. * @author Andrew Porokhin, andrew.porokhin@gmail.com */ public class Problem01B implements Runnable { static final long[] x10 = new long[] { 1, 26, 26*26, 26*26*26, 26*26*26*26, 26*26*26*26*26, 26*26*26*26*26*26}; void solve() throws NumberFormatException, IOException { // TODO: Write your code here ... int n = nextInt(); for (int i = 0; i < n; i++) { String t = nextToken().toUpperCase(); StringBuffer rowString = new StringBuffer(t.length()); StringBuffer numb1 = new StringBuffer(t.length()); StringBuffer numb2 = new StringBuffer(t.length()); int stage = 0; for (int j = 0; j < t.length(); j++) {; char charAt = t.charAt(j); if (charAt >= 'A') { if (stage == 0) { rowString.append(charAt); } else { stage++; } } else { if (stage == 0 || stage == 2) stage++; switch (stage) { case 1: numb1.append(charAt); break; case 3: numb2.append(charAt); break; } } } if (stage == 1) { long result = convertString(rowString); System.out.print("R"); System.out.print(numb1.toString()); System.out.print("C"); System.out.println(result); } else { StringBuffer tmp = convertNumber(Long.parseLong(numb2.toString())); System.out.print(tmp.toString()); System.out.println(numb1.toString()); } } } public StringBuffer convertNumber(long n) { StringBuffer sb2 = new StringBuffer(); long nmod26 = n % 26; long ndiv26 = n / 26; while (ndiv26 > 0 || nmod26 > 0) { long tmp = 0; if (nmod26 > 0) { sb2.append((char) ('A' + nmod26 - 1)); tmp = ndiv26; } else { sb2.append('Z'); tmp = ndiv26 - 1; } nmod26 = tmp % 26; ndiv26 = tmp / 26; } return sb2.reverse(); } public long convertString(StringBuffer sb) { long result = 0; for (int i = 0; i < sb.length(); i++) { long l = (sb.charAt(i) - 'A' + 1) * x10[sb.length() - i - 1]; result += l; } return result; } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) { new Problem01B().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } catch (Exception e) { System.exit(9000); } finally { out.flush(); out.close(); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.*; import java.util.StringTokenizer; import static java.lang.Math.abs; /** * 35C * * @author artyom */ public class FireAgain implements Runnable { private BufferedReader in; private PrintWriter out; private StringTokenizer tok; private void solve() throws IOException { int n = nextInt(), m = nextInt(); int[][] sources = readIntMatrix(nextInt(), 2); int max = -1, maxI = 0, maxJ = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int min = Integer.MAX_VALUE; for (int[] source : sources) { int dist = abs(source[0] - i) + abs(source[1] - j); if (dist < min) { min = dist; } } if (min > max) { max = min; maxI = i; maxJ = j; } } } out.print((maxI + 1) + " " + (maxJ + 1)); } //-------------------------------------------------------------- public static void main(String[] args) { new FireAgain().run(); } @Override public void run() { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); tok = null; solve(); in.close(); out.close(); } catch (IOException e) { System.exit(0); } } private String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private int[][] readIntMatrix(int n, int m) throws IOException { int[][] mx = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mx[i][j] = nextInt() - 1; } } return mx; } }
cubic
35_C. Fire Again
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); long num=in.nextLong(); long lcm=1; if(num==2){ System.out.println(2); System.exit(0); }//End if else if(num%2==0&&num%3!=0) lcm=(num)*(num-1)*(num-3); else if(num%2==0&&num%3==0) lcm=(num-1)*(num-2)*(num-3); else if(num%2!=0&&num>2) lcm=num*(num-1)*(num-2); System.out.println(lcm); }//End main() }//End class
constant
235_A. LCM Challenge
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.Arrays; import java.util.Comparator; import java.util.TreeSet; public class Main { public static StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); public static int read() throws IOException { tokenizer.nextToken(); return (int) tokenizer.nval; } public static void main(String[] args) throws IOException { Scanner scanner=new Scanner(System.in); int n=scanner.nextInt(); ArrayList<String> list1=new ArrayList<String>(); ArrayList<String> list2=new ArrayList<String>(); for (int i=0; i<n; i++){ String s=scanner.next(); list1.add(s); } for (int i=0; i<n; i++){ String s=scanner.next(); list2.add(s); } for (int i=0; i<list1.size(); i++){ for (int j=0; j<list2.size(); j++){ if (list1.get(i).equals(list2.get(j))){ list1.remove(i); list2.remove(j); i--; break; } } } System.out.println(list1.size()); } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class ASimpleTask { static StreamTokenizer st; static int nextInt() { try { st.nextToken(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return (int) st.nval; } static int[][] edges; static long[][] dp; public static void main(String[] args) { st = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); int n = nextInt(); int m = nextInt(); edges = new int[n][n]; for (int i = 0; i < m; i++) { int from = nextInt() - 1; int to = nextInt() - 1; edges[from][to] = edges[to][from] = 1; } dp = new long[(1 << n) + 1][n + 1]; for (int mask = 1; mask < (1 << n); mask++) { for (int i = 0; i < n; i++) { if (Integer.bitCount(mask) == 1 && (mask & (1 << i)) != 0) { dp[mask][i] = 1; continue; } if (Integer.bitCount(mask) > 1 && (mask & (1 << i)) != 0 && first(mask, n) != i) { for (int j = 0; j < n; j++) { if (edges[i][j] == 1) { dp[mask][i] += dp[mask ^ (1 << i)][j]; } } } } } long count = 0; for (int mask = 1; mask < (1 << n); mask++) { for (int i = 0; i < n; i++) { if (Integer.bitCount(mask) >= 3 && edges[i][first(mask, n)] != 0) count += dp[mask][i]; } } System.out.println(count / 2); } static int first(int mask, int n) { for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) return i; } return -1; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.InputMismatchException; public class Cf2207C { private static InputReader in = new InputReader(System.in); private static OutputWriter out = new OutputWriter(System.out); private static void solve() throws Exception { int n = in.readInt(); String s = in.readString(); int[] count = new int[200]; boolean[] flag = new boolean[200]; for(int i=0; i<n; ++i){ flag[s.charAt(i)] = true; } int ref = 0; for(int i=0; i<200; ++i){ if(flag[i]){ ref++; } } int total = 0; int min = Integer.MAX_VALUE; int j = 0; for(int i=0; i<n; ++i){ if((j==n)&&(total<ref)){ break; } if(total==ref){ min = Math.min(min,j-i); count[s.charAt(i)]--; if(count[s.charAt(i)]==0){ total--; } continue; } for(;j<n; ++j){ count[s.charAt(j)]++; if(count[s.charAt(j)]==1){ total++; } if(total==ref){ min = Math.min(min,j-i+1); j++; break; } } count[s.charAt(i)]--; if(count[s.charAt(i)]==0){ total--; } } out.println(min); } public static void main(String[] args) throws Exception { solve(); out.close(); } private static class InputReader { private InputStream stream; private byte[] buffer; private int currentIndex; private int bytesRead; public InputReader(InputStream stream) { this.stream = stream; buffer = new byte[16384]; } public InputReader(InputStream stream, int bufferSize) { this.stream = stream; buffer = new byte[bufferSize]; } private int read() throws IOException { if (currentIndex >= bytesRead) { currentIndex = 0; bytesRead = stream.read(buffer); if (bytesRead <= 0) { return -1; } } return buffer[currentIndex++]; } public String readString() throws IOException { int c = read(); while (!isPrintable(c)) { c = read(); } StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (isPrintable(c)); return result.toString(); } public int readInt() throws Exception { int c = read(); int sign = 1; while (!isPrintable(c)) { c = read(); } if (c == '-') { sign = -1; c = read(); } int result = 0; do { if ((c < '0') || (c > '9')) { throw new InputMismatchException(); } result *= 10; result += (c - '0'); c = read(); } while (isPrintable(c)); return sign * result; } public long readLong() throws Exception { int c = read(); int sign = 1; while (!isPrintable(c)) { c = read(); } if (c == '-') { sign = -1; c = read(); } long result = 0; do { if ((c < '0') || (c > '9')) { throw new InputMismatchException(); } result *= 10; result += (c - '0'); c = read(); } while (isPrintable(c)); return sign * result; } public double readDouble() throws Exception { int c = read(); int sign = 1; while (!isPrintable(c)) { c = read(); } if (c == '-') { sign = -1; c = read(); } boolean fraction = false; double multiplier = 1; double result = 0; do { if ((c == 'e') || (c == 'E')) { return sign * result * Math.pow(10, readInt()); } if ((c < '0') || (c > '9')) { if ((c == '.') && (!fraction)) { fraction = true; c = read(); continue; } throw new InputMismatchException(); } if (fraction) { multiplier /= 10; result += (c - '0') * multiplier; c = read(); } else { result *= 10; result += (c - '0'); c = read(); } } while (isPrintable(c)); return sign * result; } private boolean isPrintable(int c) { return ((c > 32) && (c < 127)); } } private static class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; public class B{ static long []sum; static int n; public static void main(String[] args) throws IOException { Scanner sc=new Scanner(); PrintWriter out=new PrintWriter(System.out); n=sc.nextInt(); sum=new long [n+1]; for(int i=1;i<=n;i++) sum[i]=sc.nextInt()+sum[i-1]; HashMap<Long,Integer> map=new HashMap(); ArrayList<int []>[]adj=new ArrayList[n*n+10]; for(int i=0;i<adj.length;i++) adj[i]=new ArrayList(); for(int r=1;r<=n;r++) for(int l=1;l<=n;l++) { if(r<l) continue; long x=sum[r]-sum[l-1]; map.put(x, map.getOrDefault(x, map.size())); adj[map.get(x)].add(new int [] {l,r}); } int ans=0; int bestIdx=0; for(int idx=0;idx<adj.length;idx++) { ArrayList<int[]>list=adj[idx]; if(list.isEmpty()) continue; int curr=1; int R=list.get(0)[1]; for(int i=1;i<list.size();i++) { int []tmp=list.get(i); if(tmp[0]>R) { R=tmp[1]; curr++; } } if(curr>=ans) { ans=curr; bestIdx=idx; } } out.println(ans); ArrayList<int[]>list=adj[bestIdx]; int R=list.get(0)[1]; out.println(list.get(0)[0]+" "+R); for(int i=1;i<list.size();i++) { int []tmp=list.get(i); if(tmp[0]>R) { R=tmp[1]; out.println(tmp[0]+" "+tmp[1]); } } 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()); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import static java.util.Arrays.*; import static java.lang.Math.*; import java.util.*; import java.io.*; public class A implements Runnable { public static void main(String [] args) throws IOException { new Thread(null, new A(), "", 1 << 20).start(); } String file = "input"; BufferedReader input; PrintWriter out; public void run() { try { //input = new BufferedReader(new FileReader(file + ".in")); input = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); solve(); input.close(); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } void solve() throws IOException { ArrayList<Integer> p = new ArrayList<Integer>(); StringTokenizer st = tokens(); int n = nextInt(st), k = nextInt(st); for(int i = 2; i <= n; i++) if(prime(i)) p.add(i); int count = 0; for(int x = 2; x <= n; x++) { if(!prime(x)) continue; for(int i = 0; i + 1 < p.size(); i++) { int p1 = p.get(i); int p2 = p.get(i + 1); int P = p1 + p2 + 1; if(P == x) { count++; break; } if(P > x) break; } } System.out.println(count >= k ? "YES" : "NO"); } boolean prime(int n) { for(int i = 2; i * i <= n; i++) if(n % i == 0) return false; return true; } StringTokenizer tokens() throws IOException { return new StringTokenizer(input.readLine()); } String next(StringTokenizer st) { return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(input.readLine()); } int nextInt(StringTokenizer st) { return Integer.parseInt(st.nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(input.readLine()); } double nextDouble(StringTokenizer st) { return Double.parseDouble(st.nextToken()); } void print(Object... o) { out.println(deepToString(o)); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class A { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); class Pointd implements Comparable<Pointd>{ int x, in; @Override public int compareTo(Pointd o) { if(x > o.x) return 1; if(x < o.x) return -1; if(in < o.in) return -1; if(in > o.in) return 1; return 0; } public Pointd(int x, int in) { super(); this.x = x; this.in = in; } } void solve() throws IOException { int n = readInt(); Pointd[] a = new Pointd[n]; for(int i = 0; i < n; i++){ a[i] = new Pointd(readInt(), i); } Arrays.sort(a); int count = 0; for(int i = 0; i < n; i++){ if(a[i].x != a[a[i].in].x) count++; } if(count == 0 || count == 2) out.println("YES"); else out.println("NO"); } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } int[] readArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = readInt(); } return res; } long[] readArrL(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = readLong(); } return res; } public static void main(String[] args) { new A().run(); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
/** * @Author Tran Quang Loc (darkkcyan) * BEFORE READING CODE: * Java is really lengthy (at least for Java 8). So I used the advantage of initialization block. * Basically, every initialization block run before the constructor and they run in the declaration order. * And as I understand, every properties (or global variables) is also counted as initialization block. */ import java.io.*; import java.lang.*; import java.util.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.*; import static java.lang.System.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main { PrintWriter out = new PrintWriter(System.out, false); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stok = null; String next() { while (stok == null || !stok.hasMoreTokens()) try { stok = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return stok.nextToken(); } public static void main(String args[]) throws IOException { if (args.length > 0) { setIn(new FileInputStream(args[0] + ".inp")); setOut(new PrintStream(args[0] + ".out")); } Main solver = new Main(); solver.out.flush(); // could be replace with a method, but nah, this is just competitive programming :p } ///// Actual solution below ///// long n = parseLong(next()), k = parseLong(next()); long delta = 9 + 8 * (n + k); long a = (-3 + (long)sqrt(delta)) / 2; long b = n - a; { out.println(b); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author AlexFetisov */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { long n = in.nextInt(); long x = in.nextInt(); long y = in.nextInt(); long c = in.nextInt(); if (c == 1) { out.println(0); return; } long left = 1, right = 2 * n, middle, res = -1; long val = getNumberOfCells(x, y, n, 2); while (left <= right) { middle = (left + right) / 2; long numberOfCells = getNumberOfCells(x, y, n, middle); if (numberOfCells < c) { left = middle + 1; } else { res = middle; right = middle - 1; } } out.println(res); } private long getNumberOfCells(long x, long y, long n, long middle) { long res = 0; res += calc(x, y, middle + 1); res += calc(n - x + 1, y, middle + 1); res += calc(x, n - y + 1, middle + 1); res += calc(n - x + 1, n - y + 1, middle + 1); res -= calcX(x, n, middle); res -= calcX(y, n, middle); --res; return res; } private long calcX(long x, long n, long size) { long left = x - size; long right = x + size; left = Math.max(left, 1); right = Math.min(right, n); if (left <= right) { return right - left + 1; } return 0; } private long calc(long x, long y, long size) { if (size <= Math.min(x, y)) { return (1 + size) * size / 2; } if (size >= x + y - 1) { return x * y; } if (size > Math.max(x, y)) { return x * y - calc(x, y, x + y - 1 - size); } long min = Math.min(x, y); long res = (1 + min) * min / 2; long rest = size - min; res += rest * min; return res; } } 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 nextString() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String args[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); System.out.println("0 0 "+n);} }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long K = Long.valueOf(br.readLine()); long n = 0; long k = 0; //len * Math.pow(10, len) * 0.9; long len = 0; while(true){ len++; long preK = k; long preN = n; k += len * Math.pow(10, len) * 0.9; n += Math.pow(10, len) * 0.9; if(K < k) { k = preK; n = preN; break; } } long step = len - 1; while(true){ while(k <= K){ long preK = k; long preN = n; if(step == 0){ k += len; n++; }else{ k += len * Math.pow(10, step) * 0.9; n += Math.pow(10, step) * 0.9; } if(k == K || (k >= K && k - K < len)){ //System.out.println(k); //System.out.println(n); String nStr = Long.toString(n); System.out.println(nStr.charAt(nStr.length() - (int)(k-K) - 1)); return; } if(K < k){ k = preK; n = preN; break; } } step--; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { StreamTokenizer in; PrintWriter out; static public void main(String[] args) throws IOException { new Main().run(); } int ni() throws IOException { in.nextToken(); return (int) in.nval; } void run() throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); int n = ni(), t = ni(); if(n == 0) { out.println(0); out.flush(); return; } House[] h = new House[n]; for(int i = 0; i < n; i++) { h[i] = new House(); h[i].x = ni(); h[i].a = ni(); } Arrays.sort(h); int ret = 2; for(int i = 0; i < n - 1; i++) { if(2*(h[i + 1].x - h[i].x) - h[i].a - h[i + 1].a > 2*t) ret+=2; else if(2*(h[i + 1].x - h[i].x) - h[i].a - h[i + 1].a == 2*t) ret++; } out.println(ret); out.flush(); } void run1() throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); int t = ni(); long n = ni(), m = ni(); long x1 = ni(), y1 = ni(), x2 = ni(), y2 = ni(); long tx1 = Math.min(x1, x2), tx2 = x1 + x2 - tx1; long ty1 = Math.min(y1, y2), ty2 = y1 + y2 - ty1; long dx = tx2 - tx1; long dy = ty2 - ty1; } class House implements Comparable<House> { int x, a; public int compareTo(House h) { return x < h.x ? -1 : 1; } } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.*; public class BBi implements Runnable { public static void main(String[] args) { new Thread(new BBi()).run(); } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer in; PrintWriter out = new PrintWriter(System.out); public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } int n, x, y; public long count(long z) { long total = 0; long[][] c = new long[][] { { x, y }, { y, n - x + 1 }, { n - x + 1, n - y + 1 }, { n - y + 1, x } }; for (int i = 0; i < c.length; i++) { long inside = z; for (int j = 0; j < c[i].length; j++) { if (z > c[i][j]) { total += Math.min(z - c[i][j], c[i][1 - j]) * c[i][j]; inside -= (z - c[i][j]); } } if (z > c[i][0] && z > c[i][1]) { total -= Math.min(z - c[i][0], c[i][1]) * Math.min(z - c[i][1], c[i][0]); } if (inside > 0) total += inside * (inside + 1) / 2; } for (int i = 0; i < c.length; i++) { total -= Math.min(z, c[i][0]); } return total + 1; } public long solve(int n, int x, int y, long c) throws IOException { this.n = n; this.x = x; this.y = y; long l = 0; long r = 2L * n + 2; while (r - l > 1) { long z = (l + r) / 2; if (c <= count(z)) { r = z; } else { l = z; } } return r - 1; } public void run() { try { out.println(solve(nextInt(), nextInt(), nextInt(), nextLong())); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.util.*; import static java.lang.Math.*; import java.io.*; public class SolutionB { public static void main(String args[])throws IOException{ Scanner sc = new Scanner(System.in); int a[] = new int[1501]; for(int i = 0; i < 3; i++){ a[sc.nextInt()]++; } if(a[1] > 0 || a[2] > 1 || a[3] > 2 || (a[4] == 2 && a[2] == 1)){ System.out.println("YES"); }else{ System.out.println("NO"); } } }
constant
911_C. Three Garlands
CODEFORCES
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.round; import static java.lang.Math.sqrt; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { static long sqr(long a) { return a * a; } static void solve() throws Exception { int tests = scanInt(); for (int test = 0; test < tests; test++) { int n = scanInt(); out.println(n == 2 * sqr(round(sqrt(n / 2))) || n == 4 * sqr(round(sqrt(n / 4))) ? "YES" : "NO"); } } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import static java.util.Arrays.sort; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeSet; public class SecondOrderStatistics implements Runnable { public static void main(String[] args) throws Exception { new SecondOrderStatistics().run(); } private void solve() throws Exception { int n = nextInt(); SortedSet<Integer> sset = new TreeSet<Integer>(); for (int i = 0; i < n; i++) { int a = nextInt(); sset.add(a); } if (sset.size() < 2) out.println("NO"); else { Integer v[] = (Integer[]) sset.toArray(new Integer[sset.size()]); sort(v); out.println(v[1]); } } // -------------- Input/Output routines below ---------------// private BufferedReader in; PrintWriter out; StringTokenizer tokenizer; public void run() { // String problem = this.getClass().getName(); try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); solve(); out.flush(); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); // System.exit(1); } } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Test { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1024 * 48); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String str = br.readLine(); StringTokenizer st = new StringTokenizer(str, " "); long x = Long.parseLong(st.nextToken()); long k = Long.parseLong(st.nextToken()); if (x == 0) { bw.write(0 + "\n"); } else { int power = power(k, 1000000007); long answer = (((power * 2) % 1000000007) * (x % 1000000007)) % 1000000007; answer -= power - 1; answer = (answer + 1000000007) % 1000000007; bw.write(answer + "\n"); } bw.flush(); } public static int power(long a, int m) { if (a == 0) { return 1; } long pow = power(a / 2, m); if (a % 2 == 1) { return (int)(((pow * pow) % m) * 2) % m; } else { return (int)((pow * pow) % m); } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n, t[], g[], MOD = (int) 1e9 + 7; static int[][][] memo1, memo2[], memo3[]; static int dp1(int idx, int remCnt, int remSum) { if (idx == n) return remSum == 0 && remCnt == 0 ? 1 : 0; if (remCnt < 0 || remSum < 0) return 0; if (memo1[idx][remCnt][remSum] != -1) return memo1[idx][remCnt][remSum]; int ans = dp1(idx + 1, remCnt, remSum); if (g[idx] == 0) { ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]); if (ans >= MOD) ans -= MOD; } return memo1[idx][remCnt][remSum] = ans; } static int dp2(int idx, int remCnt1, int remCnt2, int remSum) { if (idx == n) return remSum == 0 && remCnt1 == 0 && remCnt2 == 0 ? 1 : 0; if (remSum < 0 || remCnt1 < 0 || remCnt2 < 0) return 0; if (memo2[idx][remCnt1][remCnt2][remSum] != -1) return memo2[idx][remCnt1][remCnt2][remSum]; int ans = dp2(idx + 1, remCnt1, remCnt2, remSum); if (g[idx] == 1) ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]); else if (g[idx] == 2) ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]); return memo2[idx][remCnt1][remCnt2][remSum] = ans; } private static int dp3(int cnt0, int cnt1, int cnt2, int last) { if (cnt0 < 0 || cnt1 < 0 || cnt2 < 0) return 0; if (cnt0 + cnt1 + cnt2 == 0) return 1; if (memo3[last][cnt0][cnt1][cnt2] != -1) return memo3[last][cnt0][cnt1][cnt2]; long ans = 0; if (last != 0) ans += dp3(cnt0 - 1, cnt1, cnt2, 0); if (last != 1) ans += dp3(cnt0, cnt1 - 1, cnt2, 1); if (last != 2) ans += dp3(cnt0, cnt1, cnt2 - 1, 2); return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); int[] fac = new int[n + 1]; t = new int[n]; g = new int[n]; int[] cnt = new int[3]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (int) (i * 1L * fac[i - 1] % MOD); int T = sc.nextInt(); for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; cnt[g[i]]++; } memo1 = new int[n][cnt[0] + 1][T + 1]; memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1]; memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= cnt[0]; j++) Arrays.fill(memo1[i][j], -1); for (int j = 0; j <= cnt[1]; j++) for (int k = 0; k <= cnt[2]; k++) Arrays.fill(memo2[i][j][k], -1); } for (int i = 0; i < 4; i++) for (int j = 0; j <= cnt[0]; j++) for (int k = 0; k <= cnt[1]; k++) Arrays.fill(memo3[i][j][k], -1); int ans = 0; for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++) for (int sum0 = 0; sum0 <= T; sum0++) for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++) for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) { long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD; ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD; ways *= fac[cnt0]; ways %= MOD; ways *= fac[cnt1]; ways %= MOD; ways *= fac[cnt2]; ways %= MOD; ans += ways; if (ans >= MOD) ans -= MOD; } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class P817C { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n = scan.nextLong(); long s = scan.nextLong(); long ans = 0; if (s > n) { System.out.println(0); return; } if (n > s+200) { ans += n-(s+200); n = s+200; } for (long i = s; i <= n; i++) { char[] num = (""+i).toCharArray(); int sum = 0; for (int j = 0; j < num.length; j++) sum += num[j] - '0'; if (i - sum >= s) ans++; } System.out.println(ans); } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.TreeMap; import java.util.Map; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Ribhav */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CGlassCarving solver = new CGlassCarving(); solver.solve(1, in, out); out.close(); } static class CGlassCarving { public void solve(int testNumber, FastReader s, PrintWriter out) { TreeMap<Long, Integer> mapH = new TreeMap<>(); TreeMap<Long, Integer> mapV = new TreeMap<>(); TreeMap<Long, Integer> hDiff = new TreeMap<>(); TreeMap<Long, Integer> vDiff = new TreeMap<>(); long width = s.nextInt(); long height = s.nextInt(); mapH.put(0L, 1); mapV.put(0L, 1); mapV.put(width, 1); mapH.put(height, 1); vDiff.put(width, 1); hDiff.put(height, 1); long maxV = height; long maxH = width; int n = s.nextInt(); for (int i = 0; i < n; i++) { char ch = s.nextCharacter(); long cut = s.nextInt(); if (ch == 'H') { Long next = mapH.higherKey(cut); Long prev = mapH.lowerKey(cut); Long diff = next - prev; int freq = hDiff.get(diff); if (freq == 1) { hDiff.remove(diff); } else { hDiff.put(diff, freq - 1); } hDiff.put(next - cut, hDiff.getOrDefault(next - cut, 0) + 1); hDiff.put(cut - prev, hDiff.getOrDefault(cut - prev, 0) + 1); mapH.put(cut, mapH.getOrDefault(cut, 0) + 1); } else { Long next = mapV.higherKey(cut); Long prev = mapV.lowerKey(cut); Long diff = next - prev; int freq = vDiff.get(diff); if (freq == 1) { vDiff.remove(diff); } else { vDiff.put(diff, freq - 1); } vDiff.put(next - cut, vDiff.getOrDefault(next - cut, 0) + 1); vDiff.put(cut - prev, vDiff.getOrDefault(cut - prev, 0) + 1); mapV.put(cut, mapV.getOrDefault(cut, 0) + 1); } out.println(hDiff.lastKey() * vDiff.lastKey()); } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
nlogn
527_C. Glass Carving
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; public class Round159ProblemA { public static void main(String[] args) { Reader r = new Reader(); int filters = r.nextInt(); int devices = r.nextInt(); int sockets = r.nextInt(); List<Integer> filtery = new ArrayList<>(); for (int i = 0; i < filters; i++) { filtery.add(r.nextInt()-1); } //System.out.println(filtery); if(devices <= sockets){ System.out.println(0); return; }else{ Collections.shuffle(filtery); Collections.sort(filtery); devices -= sockets; int act = filtery.size()-1; int result = 0; while(devices > 0){ //System.out.println(devices + " " + act); if(act < 0){ System.out.println(-1); return; } devices -= filtery.get(act); act--; result++; } System.out.println(result); } } static class Reader { StreamTokenizer in; public Reader() { in = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); } public int nextInt() { try { in.nextToken(); } catch (IOException e) { e.printStackTrace(); } return (int) in.nval; } public long nextLong() { try { in.nextToken(); } catch (IOException e) { e.printStackTrace(); } return (long) in.nval; } public String next() { try { in.nextToken(); } catch (IOException e) { e.printStackTrace(); } return in.sval; } } }
nlogn
257_A. Sockets
CODEFORCES
import java.io.IOException; import java.util.Arrays; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.util.NoSuchElementException; import java.util.TreeSet; import java.util.Collection; 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; MyScanner in = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, MyScanner in, PrintWriter out) { int n = in.nextInt(); int[] as = new int[n]; for (int i = 0; i < n; i++) as[i] = in.nextInt(); int[] sorted = as.clone(); ArrayUtils.sort(sorted); int diff = 0; for (int i = 0; i < n; i++)if(as[i]!=sorted[i])diff++; if(diff<=2)out.println("YES"); else out.println("NO"); } } class MyScanner { private final InputStream in; public MyScanner(InputStream in){ this.in = in; } public int nextInt(){ try{ int c=in.read(); if(c==-1) return c; while(c!='-'&&(c<'0'||'9'<c)){ c=in.read(); if(c==-1) return c; } if(c=='-') return -nextInt(); int res=0; do{ res*=10; res+=c-'0'; c=in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } } class ArrayUtils { public static void swap(int[] is, int i, int j) { int t = is[i]; is[i] = is[j]; is[j] = t; } public static void shuffle(int[] S) { Random rnd = r == null ? (r = new Random()) : r; shuffle(S, rnd); } private static Random r; private static void shuffle(int[] S, Random rnd) { for (int i = S.length; i > 1; i--) swap(S, i - 1, rnd.nextInt(i)); } public static void sort(int[] a) { shuffle(a); Arrays.sort(a); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.*; public class TestClass { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int arr[] = new int[n+1]; for(int i =0;i<n;i++) arr[i+1]= in.nextInt(); long sum[] = new long [n+1]; for(int i=1;i<=n;i++) sum[i]=sum[i-1]+arr[i]; long dp[] = new long[n+1]; for(int i =1;i<=n;i++) { for(int j=i;j>i-m&&j>=1;j--) { long val = sum[i]-sum[j-1]+dp[j-1]-k; dp[i]= Math.max(dp[i],val); } } long max =0; for(int i =1;i<=n;i++) max=Math.max(max,dp[i]); System.out.println(max); } }
quadratic
1197_D. Yet Another Subarray Problem
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); double n=s.nextLong(); double k=s.nextLong(); double num=(-3+Math.sqrt(9+8*(n+k)))/2; System.out.println((long)(n-num)); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.*; import java.util.*; /* * Heart beats fast * Colors and promises * How to be brave * How can I love when I am afraid... */ //read the question correctly (is y a vowel? what are the exact constraints?) //look out for SPECIAL CASES (n=1?) and overflow (ll vs int?) //always declare multidimensional arrays as [2][n] not [n][2] //it can lead to upto 2-3x diff in runtime //declare int/long tries with 16 array size due to object overhead :D public class Main { public static void main(String[] args) throws Exception { int n=ni(); Map<String, Integer> hola=new HashMap<String,Integer>(); hola.put("S", 0); hola.put("XS", 0); hola.put("XXS", 0); hola.put("XXXS", 0); hola.put("M", 0); hola.put("L", 0); hola.put("XL", 0); hola.put("XXL", 0); hola.put("XXXL", 0); for(int i=0; i<n; i++) { String te=ns(); hola.put(te,hola.get(te)+1); } for(int i=0; i<n; i++) { String te=ns(); hola.put(te,hola.get(te)-1); } int ans=0; for(int te:hola.values()) { ans+=max(te,0); } pr(ans); System.out.print(output); } /////////////////////////////////////////// /////////////////////////////////////////// ///template from here static int pow(int a, int b) { int c=1; while(b>0) { if(b%2!=0) c*=a; a*=a; } return c; } static class pair { int a, b; pair(){} pair(int c,int d){a=c;b=d;} } static interface combiner { public long combine(long a,long b); } static final long mod=1000000007; static final double eps=1e-9; static final long inf=100000000000000000L; static Reader in=new Reader(); static StringBuilder output=new StringBuilder(); static Random rn=new Random(); static void reverse(int[]a){for(int i=0; i<a.length/2; i++){a[i]^=a[a.length-i-1];a[a.length-i-1]^=a[i];a[i]^=a[a.length-i-1];}} static void sort(int[]a) { int te; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } static void sort(long[]a) { int te; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } static void sort(double[]a) { int te; double te1; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { te1=a[te]; a[te]=a[i]; a[i]=te1; } } Arrays.sort(a); } static void sort(int[][]a) { Arrays.sort(a, new Comparator<int[]>() { public int compare(int[]a,int[]b) { if(a[0]>b[0]) return -1; if(b[0]>a[0]) return 1; return 0; } }); } static void sort(pair[]a) { Arrays.sort(a,new Comparator<pair>() { @Override public int compare(pair a,pair b) { if(a.a>b.a) return 1; if(b.a>a.a) return -1; return 0; } }); } static int log2n(long a) { int te=0; while(a>0) { a>>=1; ++te; } return te; } static class vectorl implements Iterable<Long> { long a[]; int size; vectorl(){a=new long[10];size=0;} vectorl(int n){a=new long[n];size=0;} public void add(long b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Long> iterator() { Iterator<Long> hola=new Iterator<Long>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Long next() { return a[cur++]; } }; return hola; } } static class vector implements Iterable<Integer> { int a[],size; vector(){a=new int[10];size=0;} vector(int n){a=new int[n];size=0;} public void add(int b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Integer> iterator() { Iterator<Integer> hola=new Iterator<Integer>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Integer next() { return a[cur++]; } }; return hola; } } //output functions//////////////// static void pr(Object a){output.append(a+"\n");} static void pr(){output.append("\n");} static void p(Object a){output.append(a);} static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");} static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");} static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");} static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");} static void sop(Object a){System.out.println(a);} static void flush(){System.out.println(output);output=new StringBuilder();} ////////////////////////////////// //input functions///////////////// static int ni(){return Integer.parseInt(in.next());} static long nl(){return Long.parseLong(in.next());} static String ns(){return in.next();} static double nd(){return Double.parseDouble(in.next());} static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;} static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;} ////////////////////////////////// //some utility functions static void exit(){System.out.print(output);System.exit(0);} static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;} static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;} static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;} static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;} static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;} static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;} static String pr(String a, long b){String c="";while(b>0){if(b%2==1)c=c.concat(a);a=a.concat(a);b>>=1;}return c;} static long powm(long a, long b, long m){long an=1;long c=a;while(b>0){if(b%2==1)an=(an*c)%m;c=(c*c)%m;b>>=1;}return an;} static int gcd(int a, int b){if(b==0)return a;return gcd(b, a%b);} static long gcd(long a, long b){if(b==0)return a;return gcd(b, a%b);} static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.io.Writer; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int a[] = in.nextIntArray(n); int i,j,k; int b[] = a.clone(); ArrayUtils.randomShuffle(a); Arrays.sort(a); int c[] = new int[n]; k=0; for(i=0;i<n;++i) if(a[i]!=b[i]) c[k++] = i; String res = "NO"; if(k==0){ res = "YES"; }else if(k==1){ }else if(k==2){ i = c[0]; j = c[1]; if(a[i]==b[j] && a[j]==b[i]) res = "YES"; } out.writeln(res); } } 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(Exception e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] nextIntArray(int size){ int array[] = new int[size]; for(int i=0; i<size; ++i) array[i] = nextInt(); return array; } } class OutputWriter{ private PrintWriter out; public OutputWriter(Writer out){ this.out = new PrintWriter(out); } public OutputWriter(OutputStream out){ this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out))); } public void close(){ out.flush(); out.close(); } public void writeln(Object ... o){ for(Object x : o) out.print(x); out.println(); } } class ArrayUtils{ private final static Random random = new Random(System.nanoTime()); public static void randomShuffle(int a[]){ int n = a.length; for(int i=0;i<n;++i){ int j = random.nextInt(n-i); int t = a[i]; a[i] = a[j]; a[j] = t; } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.Scanner; import java.io.*; import java.util.*; public class ReallyBigNumbers817c { static long sd(String s) { long c = 0; for (int i = 0; i < s.length(); i++) { c += s.charAt(i); } return c - s.length() * 0x30; } public static void main(String[] args) { Scanner in = new Scanner(System.in); long n = in.nextLong(); long s = in.nextLong(); // number // level -- > (n + 8) / 9 * 9; --- > s long i = (s/10+1)*10 ; if (n<10||n-sd(n+"")<s) { System.out.println(0); return; } while(!(i-sd(i+"")>=s)){ i+=10; } System.out.println(n-i+1); } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.util.*; public class C{ static String s; static long val[]; static int N,size; static int index(char c){ if(c <= 'Z'){ return c - 'A'; }else{ return c - 'a' + ('Z' - 'A' + 1); } } static int l(int i){ return (i<<1)+1; } static int r(int i){ return (i<<1)+2; } static void setup(int l, int r, int i){ if(l==r){ val[i] = (1L<<index(s.charAt(l))); }else{ int mid = (l+r)/2; setup(l,mid,l(i)); setup(mid+1,r,r(i)); val[i] = val[l(i)] | val[r(i)]; } } static long query(int min, int max, int l, int r, int i){ if(min <= l && r <= max){ return val[i]; } if(max < l || r < min) return 0; int mid = (l+r)/2; return query(min,max,l,mid,l(i)) | query(min,max,mid+1,r,r(i)); } static long query(int min, int max){ return query(min,max,0,N-1,0); } static int binarySearch(int start, long toFind){ int max = N-1; int min = start; if(query(start,max) != toFind) return 1<<29; if(query(start,start) == toFind){ return 1; } int ret = max - min + 1; while(min + 1 < max){ int mid = (min+max)/2; if(query(start,mid) == toFind){ max = mid; }else{ min = mid; } } return max-start+1; } public static void main(String args[]){ Scanner sc = new Scanner(System.in); N = sc.nextInt(); s = sc.next(); int size = 1; while(size <= N) size*=2; val = new long[size*2]; setup(0,N-1,0); long toFind = query(0,N-1,0,N-1,0); long ans = 1L<<29; for(int i = 0; i < N; i++) ans = Math.min(ans,binarySearch(i,toFind)); System.out.println(ans); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; import java.util.Map.Entry; public class StringsProb { private void solve() throws IOException { String s = nextToken(); int res = 0; Map<String , Integer> m = new HashMap<String, Integer>(); for (int i = 0; i < s.length(); i++) for (int j = 0; j <= s.length(); j++) { if (i > j) continue; String a = s.substring(i , j); if (a.equals("")) continue; if (m.containsKey(a)) { m.put(a, m.get(a) + 1); } else m.put(a, 1); } for (Entry<String , Integer> e : m.entrySet()) { if (e.getValue() >= 2) res = Math.max(res, e.getKey().length()); } System.out.println(res); } public static void main(String[] args) { new StringsProb().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = nextInt(); } return res; } long[] readLongArray(int size) throws IOException { long[] res = new long[size]; for (int i = 0; i < size; i++) { res[i] = nextLong(); } return res; } double[] readDoubleArray(int size) throws IOException { double[] res = new double[size]; for (int i = 0; i < size; i++) { res[i] = nextDouble(); } return res; } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class GB17C { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); String[] dir = sc.readLine().split(" "); int n = Integer.parseInt(dir[0]); int r = Integer.parseInt(dir[1]); String[] t = sc.readLine().split(" "); int[] list = new int[n]; for(int x=0; x<n; x++){ list[x] = Integer.parseInt(t[x]); } double[] yCoords = new double[n]; for(int x=0; x<n; x++){ double stop = (double)r; int dist = 2*r; int xCoordNew = list[x]; for(int y=0; y<x; y++){ int xCoordOld = list[y]; if(Math.abs(xCoordNew - xCoordOld) == dist){ stop = Math.max(stop, yCoords[y]); } else if(Math.abs(xCoordNew - xCoordOld) < dist){ double extra = Math.pow((double)(dist*dist) - (double)((xCoordNew - xCoordOld)*(xCoordNew - xCoordOld)), 0.5); stop = Math.max(stop, yCoords[y] + extra); } } yCoords[x] = stop; System.out.print(stop+" "); } } } /* BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(sc.readLine()); String[] t = sc.readLine().split(" "); int[] list = new int[n]; for(int x=0; x<n; x++){ list[x] = Integer.parseInt(t[x]); } String[] dir = sc.readLine().split(" "); int a = Integer.parseInt(dir[0]); int b = Integer.parseInt(dir[1]); int c = Integer.parseInt(dir[2]); int d = Integer.parseInt(dir[3]); int e = Integer.parseInt(dir[4]); int n = Integer.parseInt(sc.readLine()); */
quadratic
908_C. New Year and Curling
CODEFORCES
//package cf196; import java.util.*; import java.io.*; public class A { FastScanner in; PrintWriter out; final long mod = (long) 1e9 + 9 ; public void solve() throws IOException { long n = in.nextInt(); long m = in.nextInt(); long k = in.nextInt(); long l = n / k; long c = n - m; long mul2 = Math.max(0, l - c); if (mul2 == 0) { out.println(m); return; } long ans = power(2, mul2 + 1, mod); ans = (ans + mod - 2) % mod; ans = (ans * k) % mod; long z = mul2 * k; long r = m - z; ans = (ans + r) % mod; out.print(ans); } public long power(long x, long pow, long mod) { if (pow == 0) { return 1; } if ((pow % 2) == 0) { return power(((x * x) % mod), pow / 2, mod); } else { return (power(x, pow - 1, mod) * x) % mod; } } public void run() { try { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] arg) { new A().run(); } }
logn
338_A. Quiz
CODEFORCES
import java.util.*; import java.io.*; public class SonyaExhibition { static BufferedReader br; static StringTokenizer tokenizer; public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(); int[] arr = {0,1}; for(int i = 0; i < n; i++) { System.out.print(arr[i % 2]); } System.out.println(); } public static String next() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) throw new IOException(); tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } }
linear
1004_B. Sonya and Exhibition
CODEFORCES
import java.io.*; public class Alpha_Round { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); String[] in = reader.readLine().split(" "); long n = Long.parseLong(in[0]); long k = Long.parseLong(in[1]); long D = 9 + 8*k + 8*n; long m = (long) ((-3 + Math.sqrt(D))/2); writer.write((n - m) + ""); writer.close(); } }
logn
1195_B. Sport Mafia
CODEFORCES
//package Round_159; import java.util.*; import java.io.*; import static java.lang.Math.*; public class a { void solve() throws Exception { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int a[] = new int[n]; for (int i = 0; i<n; i++){ a[i] = in.nextInt(); } Arrays.sort(a); int sum = 0; if (k >= m){ out.println(0); return; } sum = a[n-1] + k - 1; int j = 1; for (int i = n-2; i >=0 && sum < m; i--, j++){ sum += a[i] - 1; } if (sum < m){ out.println(-1); }else{ out.println(j); } } FastScanner in; PrintWriter out; String input = ""; String output = ""; void run() { try { if (input.length() > 0) { in = new FastScanner(new BufferedReader(new FileReader(input))); } else in = new FastScanner(new BufferedReader(new InputStreamReader( System.in))); if (output.length() > 0) out = new PrintWriter(new FileWriter(output)); else out = new PrintWriter(System.out); solve(); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); out.flush(); out.close(); } finally { out.close(); } } public static void main(String[] args) { new a().run(); } class FastScanner { BufferedReader bf; StringTokenizer st; public FastScanner(BufferedReader bf) { this.bf = bf; } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { return bf.readLine(); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
nlogn
257_A. Sockets
CODEFORCES
import java.util.*; import java.io.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.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[1 << (n - i)][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[mask][j] != 0) { for (int k = 0; k < n - i; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[mask | (1 << k)][k] += dp[mask][j]; } } } } if (((mask >> 0) & 1) != 0) { res += dp[mask][0]; } } } out.println(res / 2); } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { BufferedReader reader; StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } public boolean hasNext() throws IOException { while (!tokenizer.hasMoreTokens()) { String next = reader.readLine(); if (next == null) { return false; } tokenizer = new StringTokenizer(next); } return true; } public String next() throws IOException { hasNext(); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 28).start(); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(new InputStreamReader(System.in)); }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class c { class IO { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st; Random rnd = new Random();; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } } void run() throws IOException{ IO read=new IO(); int n=read.nextInt(); int a[]=new int[n],b[]=new int[n]; for(int i=0;i<n;i++) a[i]=b[i]=read.nextInt(); Arrays.sort(b); int cnt=0; for(int i=0;i<n;i++) if(a[i]!=b[i]) cnt++; if(cnt==0||cnt==2) read.out.println("YES"); else read.out.println("NO"); read.out.close(); } public static void main(String[] args) throws IOException { new c().run(); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.*; import java.util.*; public class YoureGivenAString { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); String str = f.readLine(); int max = 0; for (int i = 0; i < str.length(); i++) for (int j = i+1; j <= str.length(); j++) { String s = str.substring(i,j); if (str.indexOf(s) >= 0 && str.substring(str.indexOf(s)+1).indexOf(s) >= 0) max = Math.max(max, j-i); } System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; public class D999 { public static void main(String args[])throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int req=n/m; int arr[]=new int[n+1]; int size[]=new int[m]; List<Integer> list[]=new ArrayList[m]; for(int i=0;i<m;i++) { list[i]=new ArrayList<>(); } for(int i=1;i<=n;i++) { arr[i]=sc.nextInt(); size[arr[i]%m]++; list[arr[i]%m].add(i); } long tot=0;int x=0,y=0; List<Integer> idx=new ArrayList<>(); for(int i=0;i < 2*m;i++) { //System.out.println(i+" "+size[i%m]); if(size[i%m]>req) { for(int j=0;j<size[i%m]-req;j++) { idx.add(list[i%m].get(j)); y++; } size[i%m]=req; //System.out.println(i+" "+x+" "+y); } else if(size[i%m]<req) { //System.out.println(idx+" "+i); while(x!=y && size[i%m]<req) { int num=arr[idx.get(x)]; int gg=i-num%m; tot+=gg; arr[idx.get(x)]+=gg; x++; size[i%m]++; } } } System.out.println(tot); for(int i=1;i<=n;i++) { System.out.print(arr[i]+" "); } } }
linear
999_D. Equalize the Remainders
CODEFORCES
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class A_135 { /** * @param args */ public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int[] mas=new int[n]; for(int i=0;i<n;i++){ mas[i]=in.nextInt(); } Arrays.sort(mas); PrintWriter out=new PrintWriter(System.out); boolean isEd=true; for(int i=0;i<n;i++) if(mas[i]!=1){ isEd=false; break; } if(!isEd) out.print('1'); for(int i=0;i<n-1;i++){ out.print(' '); out.print(mas[i]); } if(isEd) out.print(" 2"); out.flush(); } }
nlogn
135_A. Replacement
CODEFORCES
import java.util.Scanner; public class Code1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.valueOf(sc.nextLine()); if (n % 2 == 0) System.out.println(4 + " " + (n - 4)); else { System.out.println(9 + " " + (n - 9)); } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.util.Scanner; public class ToyArmy { public static void main(String[] args) { int n = new Scanner(System.in).nextInt(); System.out.println(n + n / 2); } }
constant
84_A. Toy Army
CODEFORCES
import java.io.*; import java.math.*; import java.security.KeyStore.Entry; import java.util.*; public class QA { static long MOD = 1000000007; static boolean b[], b1[], check; static ArrayList<Integer>[] amp, pa; static ArrayList<Pair>[] amp1; static ArrayList<Pair>[][] damp; static int left[],right[],end[],sum[],dist[],cnt[],start[],color[],parent[],prime[],size[]; static int ans = 0,k; static int p = 0; static FasterScanner sc = new FasterScanner(System.in); //static Queue<Integer> q = new LinkedList<>(); static BufferedWriter log; static HashSet<Pair> hs; static HashMap<Pair,Integer> hm; static PriorityQueue<Integer> pri[]; static ArrayList<Integer>[] level; static Stack<Integer> st; static boolean boo[][]; static Pair prr[]; static long parent1[],parent2[],size1[],size2[],arr1[],SUM[],lev[], fibo[]; static int arr[], ver[][]; static private PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { soln(); } catch (Exception e) { System.out.println(e); } } }, "1", 1 << 26).start(); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } static int dp[][]; static int N,K,T,A,B; static long time; static int cost[][]; static boolean b11[]; static HashMap<Integer,Integer> h = new HashMap<>(); static HashSet<Pair> chec; static long ans1; static long ans2; static int BLOCK, MAX = 1000001; static double pi = Math.PI; static int Arr[], Brr[], pow[], M; static long fact[] = new long[100000+1]; static HashMap<Integer,Long> hm1; static HashSet<Integer> hs1[], hs2[]; static String[] str2; static char[] ch1, ch2; static int[] s,f,D; static int tf,ts; static int see[][] = new int[2050][2050]; static boolean bee[][] = new boolean[2050][2050]; static Queue<Pair> q = new LinkedList<>(); //static PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); public static void soln() throws IOException { //System.setIn(new FileInputStream("input.txt")); //System.setOut(new PrintStream("output.txt")); FasterScanner sc = new FasterScanner(new FileInputStream("input.txt"));//("C:\\Users\\Admin\\Desktop\\QAL2.txt")); //PrintWriter log1 = new PrintWriter("C:\\Users\\Admin\\Desktop\\input01"); PrintWriter log = new PrintWriter("output.txt");//("C:\\Users\\Admin\\Desktop\\output00"); //log = new BufferedWriter(new OutputStreamWriter(System.out)); int n = sc.nextInt() , m = sc.nextInt(); int k = sc.nextInt(); for(int i = 1; i <= n ; i++) for(int j =1;j<=m;j++) see[i][j]= 100000000; for(int i = 0; i < k; i++){ int x = sc.nextInt(), y = sc.nextInt(); bee[x][y] = true; see[x][y] = 0; q.add(new Pair(x,y)); } while(!q.isEmpty()){ //System.out.println(q); int x = q.peek().u, y = q.poll().v; if(x>1){ see[x-1][y] = min(see[x][y]+1,see[x-1][y]); if(!bee[x-1][y]) q.add(new Pair(x-1,y)); bee[x-1][y] = true; } if(x<n){ see[x+1][y] = min(see[x][y]+1,see[x+1][y]); if(!bee[x+1][y]) q.add(new Pair(x+1,y)); bee[x+1][y] = true; } if(y>1){ see[x][y-1] = min(see[x][y]+1,see[x][y-1]); if(!bee[x][y-1]) q.add(new Pair(x,y-1)); bee[x][y-1] = true; } if(y<m){ see[x][y+1] = min(see[x][y]+1,see[x][y+1]); if(!bee[x][y+1]) q.add(new Pair(x,y+1)); bee[x][y+1] = true; } } int ans = -1; Pair temp = null; for(int i = 1;i<=n;i++){ for(int j = 1;j<=m;j++){ if(see[i][j]>ans) { ans = see[i][j]; temp = new Pair(i,j); } } } log.write(temp.u+" "+temp.v); log.close(); } static int min(int a, int b){ if(a>b) return b; return a; } private static double dfs(int cur,int prev){ double r=0,n=0; for(int i : amp[cur]){ if(i!=prev){ r+=(1+dfs(i,cur)); n++; } } if(n!=0){ r=r/n; } return r; } static double fa1 = 0; static int fa = -1; static long nCr1(int n, int r){ if(n<r) return 0; return (((fact[n] * modInverse(fact[n-r], MOD))%MOD)*modInverse(fact[r], MOD))%MOD; } static class Node{ Node arr[] = new Node[2]; int cnt[] = new int[2]; } public static class Trie{ Node root; public Trie(){ root = new Node(); } public void insert(String x){ Node n = root; for(int i = 0;i < x.length() ;i++){ int a1 = x.charAt(i)-'0'; if(n.arr[a1]!=null){ n.cnt[a1]++; n = n.arr[a1]; continue; } n.arr[a1] = new Node(); n.cnt[a1]++; n = n.arr[a1]; } } public void delete(String x){ Node n = root; for(int i = 0;i < x.length() ;i++){ int a1 = x.charAt(i)-'0'; if(n.cnt[a1]==1){ n.arr[a1] = null; return; } else { n.cnt[a1]--; n = n.arr[a1]; } } } public long get(String x){ Node n = root; long ans = 0; for(int i = 0;i < x.length() ;i++){ int a1 = '1' - x.charAt(i); if(n.arr[a1]!=null){ ans += Math.pow(2, 30-i); n = n.arr[a1]; } else n = n.arr[1-a1]; // System.out.println(ans); } return ans; } } public static class FenwickTree { int[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new int[size + 1]; } public int rsq(int ind) { assert ind > 0; int sum = 0; while (ind > 0) { sum += array[ind]; //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number ind -= ind & (-ind); } return sum; } public int rsq(int a, int b) { assert b >= a && a > 0 && b > 0; return rsq(b) - rsq(a - 1); } public void update(int ind, int value) { assert ind > 0; while (ind < array.length) { array[ind] += value; //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number ind += ind & (-ind); } } public int size() { return array.length - 1; } } static double power(double x, long y) { if (y == 0) return 1; double p = power(x, y/2); p = (p * p); return (y%2 == 0)? p : (x * p); } static int Dfs(int x, int val){ b[x] = true; for(int p:hs2[x]){ if(!b[p]){ if(!hs1[x].contains(p)) val++; val += Dfs(p,0); } } return val; } static long nCr(int n, int r){ if(n<r) return 0; else return (((fact[n]*modInverse(fact[r], MOD))%MOD)*modInverse(fact[n-r], MOD))%MOD; } static void dfs1(int x, int p){ arr1[x] += lev[x]; for(int v:amp[x]){ if(v!=p){ dfs1(v,x); } } } static void bfs(int x){ } public static void seive(int n){ b = new boolean[(n+1)]; Arrays.fill(b, true); b[1] = true; for(int i = 2;i*i<=n;i++){ if(b[i]){ for(int p = 2*i;p<=n;p+=i){ b[p] = false; } } } /*for(int i = 2;i<=n;i++){ if(b[i]) prime[i] = i; }*/ } static class Graph{ int vertex; int weight; Graph(int v, int w){ vertex = v; weight = w; } } static class Pair implements Comparable<Pair> { int u; int v; int ans; public Pair(){ u = 0; v = 0; } public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { return Objects.hash(); } public boolean equals(Object o) { Pair other = (Pair) o; return ((u == other.u && v == other.v && ans == other.ans)); } public int compareTo(Pair other) { //return Double.compare(ans, other.ans); return Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } public static void buildGraph(int n){ for(int i =0;i<n;i++){ int x = sc.nextInt()-1, y = sc.nextInt()-1; amp[x].add(y); amp[y].add(x); } } public static int getParent(long x){ while(parent[(int) x]!=x){ parent[ (int) x] = parent[(int) parent[ (int) x]]; x = parent[ (int) x]; } return (int) x; } static long min(long a, long b, long c){ if(a<b && a<c) return a; if(b<c) return b; return c; } /* static class Pair3{ int x, y ,z; Pair3(int x, int y, int z){ this.x = x; this.y = y; this.z = z; } }*/ static void KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat,M,lps); int i = 0; // index for txt[] while (i < N) { if (pat.charAt(j) == txt.charAt(i)) { j++; i++; } if (j == M) { // parent.add((i-j)); j = lps[j-1]; } // mismatch after j matches else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j-1]; else i = i+1; } } } static void computeLPSArray(String pat, int M, int lps[]) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } private static void permutation(String prefix, String str) { int n = str.length(); if (n == 0); //hs.add(prefix); else { for (int i = 0; i < n; i++) permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n)); } } public static void buildTree(int n){ int arr[] = sc.nextIntArray(n); for(int i = 0;i<n;i++){ int x = arr[i]-1; amp[i+1].add(x); amp[x].add(i+1); } } static class SegmentTree { boolean st[]; boolean lazy[]; SegmentTree(int n) { int size = 4 * n; st = new boolean[size]; Arrays.fill(st, true); lazy = new boolean[size]; Arrays.fill(lazy, true); //build(0, n - 1, 1); } /*long[] build(int ss, int se, int si) { if (ss == se) { st[si][0] = 1; st[si][1] = 1; st[si][2] = 1; return st[si]; } int mid = (ss + se) / 2; long a1[] = build(ss, mid, si * 2), a2[] = build(mid + 1, se, si * 2 + 1); long ans[] = new long[3]; if (arr[mid] < arr[mid + 1]) { ans[1] = Math.max(a2[1], Math.max(a1[1], a1[2] + a2[0])); if (a1[1] == (mid - ss + 1)) ans[0] = ans[1]; else ans[0] = a1[0]; if (a2[2] == (se - mid)) ans[2] = ans[1]; else ans[2] = a2[2]; } else { ans[1] = Math.max(a1[1], a2[1]); ans[0] = a1[0]; ans[2] = a2[2]; } st[si] = ans; return st[si]; }*/ void update(int si, int ss, int se, int idx, long x) { if (ss == se) { //arr[idx] += val; st[si]=false; } else { int mid = (ss + se) / 2; if(ss <= idx && idx <= mid) { update(2*si, ss, mid, idx, x); } else { update(2*si+1, mid+1, se, idx, x); } st[si] = st[2*si]|st[2*si+1]; } } /*boolean get(int qs, int qe, int ss, int se, int si){ if(qs>se || qe<ss) return 0; if (qs <= ss && qe >= se) { return st[si]; } int mid = (ss+se)/2; return get(qs, qe, ss, mid, si * 2)+get(qs, qe, mid + 1, se, si * 2 + 1); }*/ void updateRange(int node, int start, int end, int l, int r, boolean val) { if(!lazy[node]) { // This node needs to be updated st[node] = lazy[node]; // Update it if(start != end) { lazy[node*2] = lazy[node]; // Mark child as lazy lazy[node*2+1] = lazy[node]; // Mark child as lazy } lazy[node] = true; // Reset it } if(start > end || start > r || end < l) // Current segment is not within range [l, r] return; if(start >= l && end <= r) { // Segment is fully within range st[node] = val; if(start != end) { // Not leaf node lazy[node*2] = val; lazy[node*2+1] = val; } return; } int mid = (start + end) / 2; updateRange(node*2, start, mid, l, r, val); // Updating left child updateRange(node*2 + 1, mid + 1, end, l, r, val); // Updating right child st[node] = st[node*2] | st[node*2+1]; // Updating root with max value } boolean queryRange(int node, int start, int end, int l, int r) { if(start > end || start > r || end < l) return false; // Out of range if(!lazy[node]) { // This node needs to be updated st[node] = lazy[node]; // Update it if(start != end) { lazy[node*2] = lazy[node]; // Mark child as lazy lazy[node*2+1] = lazy[node]; // Mark child as lazy } lazy[node] = true; // Reset it } if(start >= l && end <= r) // Current segment is totally within range [l, r] return st[node]; int mid = (start + end) / 2; boolean p1 = queryRange(node*2, start, mid, l, r); // Query left child boolean b = queryRange(node*2 + 1, mid + 1, end, l, r); // Query right child return (p1 | b); } void print() { for (int i = 0; i < st.length; i++) { System.out.print(st[i]+" "); } System.out.println(); } } static int convert(int x){ int cnt = 0; String str = Integer.toBinaryString(x); //System.out.println(str); for(int i = 0;i<str.length();i++){ if(str.charAt(i)=='1'){ cnt++; } } int ans = (int) Math.pow(3, 6-cnt); return ans; } static class Node2{ Node2 left = null; Node2 right = null; Node2 parent = null; int data; } static boolean check(char ch[][], int i, int j){ if(ch[i][j]=='O') return false; char c = ch[i][j]; ch[i][j] = 'X'; if(c=='X'){ if(i>=4){ int x = 0; int l = 0; for(x = 0;x<=4;x++){ if(ch[i-x][j]!='X'){ if(ch[i-x][j]!='.') break;else l++;} } if(x==5 && l<=1) return true; l = 0; if(j>=4){ for(x = 0;x<=4;x++){ if(ch[i-x][j-x]!='X'){ if(ch[i-x][j-x]!='.') break; else l++;} } if(x==5 && l<=1) return true; l =0; for(x = 0;x<=4;x++){ if(ch[i][j-x]!='X'){ if(ch[i][j-x]!='.') break; else l++;} } if(x==5 && l<=1) return true; } if(j<=5){ l = 0; for(x = 0;x<=4;x++){ if(ch[i][j+x]!='X'){ if(ch[i][j+x]!='.') break; else l++;} } if(x==5 && l<=1) return true; l = 0; for(x = 0;x<=4;x++){ if(ch[i-x][j+x]!='X'){ if(ch[i-x][j+x]!='.') break; else l++;} } if(x==5 && l<=1) return true; } } if(i<=5){ int x = 0; int l = 0; for(x = 0;x<=4;x++){ if(ch[i+x][j]!='X'){ if(ch[i+x][j]!='.') break; else l++;} } if(x==5 && l<=1) return true; l = 0; if(j>=4){ for(x = 0;x<=4;x++){ if(ch[i+x][j-x]!='X'){ if(ch[i+x][j-x]!='.') break; else l++;} } if(x==5 && l<=1) return true; l =0; for(x = 0;x<=4;x++){ if(ch[i][j-x]!='X'){ if(ch[i][j-x]!='.') break; else l++;} } if(x==5 && l<=1) return true; } if(j<=5){ l = 0; for(x = 0;x<=4;x++){ if(ch[i][j+x]!='X'){ if(ch[i][j+x]!='.') break; else l++;} } if(x==5 && l<=1) return true; l = 0; for(x = 0;x<=4;x++){ if(ch[i+x][j+x]!='X'){ if(ch[i+x][j+x]!='.') break; else l++;} } if(x==5 && l<=1) return true; } } } else{ if(i>=4){ int x = 0; int l = 0; for(x = 0;x<=4;x++){ if(ch[i-x][j]!='X'){ if(ch[i-x][j]!='.') break;else l++;} } if(x==5 && l<=0) return true; l = 0; if(j>=4){ for(x = 0;x<=4;x++){ if(ch[i-x][j-x]!='X'){ if(ch[i-x][j-x]!='.') break; else l++;} } if(x==5 && l<=0) return true; l =0; for(x = 0;x<=4;x++){ if(ch[i][j-x]!='X'){ if(ch[i][j-x]!='.') break; else l++;} } if(x==5 && l<=0) return true; } if(j<=5){ l = 0; for(x = 0;x<=4;x++){ if(ch[i][j+x]!='X'){ if(ch[i][j+x]!='.') break; else l++;} } if(x==5 && l<=0) return true; l = 0; for(x = 0;x<=4;x++){ if(ch[i-x][j+x]!='X'){ if(ch[i-x][j+x]!='.') break; else l++;} } if(x==5 && l<=0) return true; } } if(i<=5){ int x = 0; int l = 0; for(x = 0;x<=4;x++){ if(ch[i+x][j]!='X'){ if(ch[i+x][j]!='.') break; else l++;} } if(x==5 && l<=0) return true; l = 0; if(j>=4){ for(x = 0;x<=4;x++){ if(ch[i+x][j-x]!='X'){ if(ch[i+x][j-x]!='.') break; else l++;} } if(x==5 && l<=0) return true; l =0; for(x = 0;x<=4;x++){ if(ch[i][j-x]!='X'){ if(ch[i][j-x]!='.') break; else l++;} } if(x==5 && l<=0) return true; } if(j<=5){ l = 0; for(x = 0;x<=4;x++){ if(ch[i][j+x]!='X'){ if(ch[i][j+x]!='.') break; else l++;} } if(x==5 && l<=0) return true; l = 0; for(x = 0;x<=4;x++){ if(ch[i+x][j+x]!='X'){ if(ch[i+x][j+x]!='.') break; else l++;} } if(x==5 && l<=0) return true; } } } ch[i][j] = c; return false; } static class BinarySearchTree{ Node2 root = null; int height = 0; int max = 0; int cnt = 1; ArrayList<Integer> parent = new ArrayList<>(); HashMap<Integer, Integer> hm = new HashMap<>(); public void insert(int x){ Node2 n = new Node2(); n.data = x; if(root==null){ root = n; } else{ Node2 temp = root,temb = null; while(temp!=null){ temb = temp; if(x>temp.data) temp = temp.right; else temp = temp.left; } if(x>temb.data) temb.right = n; else temb.left = n; n.parent = temb; parent.add(temb.data); } } public Node2 getSomething(int x, int y, Node2 n){ if(n.data==x || n.data==y) return n; else if(n.data>x && n.data<y) return n; else if(n.data<x && n.data<y) return getSomething(x,y,n.right); else return getSomething(x,y,n.left); } public Node2 search(int x,Node2 n){ if(x==n.data){ max = Math.max(max, n.data); return n; } if(x>n.data){ max = Math.max(max, n.data); return search(x,n.right); } else{ max = Math.max(max, n.data); return search(x,n.left); } } public int getHeight(Node2 n){ if(n==null) return 0; height = 1+ Math.max(getHeight(n.left), getHeight(n.right)); return height; } } static long findDiff(long[] arr, long[] brr, int m){ int i = 0, j = 0; long fa = 1000000000000L; while(i<m && j<m){ long x = arr[i]-brr[j]; if(x>=0){ if(x<fa) fa = x; j++; } else{ if((-x)<fa) fa = -x; i++; } } return fa; } public static long max(long x, long y, long z){ if(x>=y && x>=z) return x; if(y>=x && y>=z) return y; return z; } static long modInverse(long a, long mOD2){ return power(a, mOD2-2, mOD2); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y/2, m) % m; p = (p * p) % m; return (y%2 == 0)? p : (x * p) % m; } static long d,x,y; public static void extendedEuclidian(long a, long b){ if(b == 0) { d = a; x = 1; y = 0; } else { extendedEuclidian(b, a%b); int temp = (int) x; x = y; y = temp - (a/b)*y; } } public static long gcd(long n, long m){ if(m!=0) return gcd(m,n%m); else return n; } static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static class FasterScanner { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public FasterScanner(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 long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } 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); } } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.util.*; public class Solution{ void solve()throws Exception { int n=nextInt(); int[]a=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); ArrayList<Integer>list=new ArrayList<Integer>(); for(int i=0;i<n;i++) list.add(a[i]); Collections.shuffle(list); int[]b=new int[n]; for(int i=0;i<n;i++) b[i]=list.get(i); Arrays.sort(b); int cnt=0; for(int i=0;i<n;i++) if(a[i]!=b[i]) cnt++; if(cnt<=2) System.out.println("YES"); else System.out.println("NO"); } private void mySort(int[] a) { if(a.length<=1) return; int n=a.length; int[]left=new int[n/2]; int[]right=new int[n-n/2]; for(int i=0;i<n;i++) if(i<left.length) left[i]=a[i]; else right[i-left.length]=a[i]; mySort(left); mySort(right); int i=0; int j=0; while (i<left.length || j<right.length) { if(i==left.length) a[i+j]=right[j++]; else if(j==right.length) a[i+j]=left[i++]; else if(left[i]<right[j]) a[i+j]=left[i++]; else a[i+j]=right[j++]; } } //////////// BufferedReader reader; PrintWriter writer; StringTokenizer stk; void run()throws Exception { reader=new BufferedReader(new InputStreamReader(System.in)); // reader=new BufferedReader(new FileReader("input.txt")); stk=null; //writer=new PrintWriter(new PrintWriter(System.out)); //writer=new PrintWriter(new FileWriter("output.txt")); solve(); reader.close(); //writer.close(); } int nextInt()throws Exception { return Integer.parseInt(nextToken()); } long nextLong()throws Exception { return Long.parseLong(nextToken()); } double nextDouble()throws Exception { return Double.parseDouble(nextToken()); } String nextString()throws Exception { return nextToken(); } String nextLine()throws Exception { return reader.readLine(); } String nextToken()throws Exception { if(stk==null || !stk.hasMoreTokens()) { stk=new StringTokenizer(nextLine()); return nextToken(); } return stk.nextToken(); } public static void main(String[]args) throws Exception { new Solution().run(); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.*; public class LearnMath { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int N = scan.nextInt(); scan.close(); if ((N%2) == 0) { System.out.println(4 + " " + (N-4)); } else { if (N > 18) { System.out.println(9 + " " + (N-9)); } else { System.out.println((N-9) + " " + 9); } } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.util.Scanner; import static java.lang.Integer.bitCount; import static java.lang.Integer.numberOfTrailingZeros; import static java.lang.System.out; /** * 11D * * @author artyom */ public class ASimpleTask { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] d = new int[n][n]; for (int i = 0, m = sc.nextInt(); i < m; i++) { int a = sc.nextInt() - 1, b = sc.nextInt() - 1; d[a][b] = 1; d[b][a] = 1; } long[][] dp = new long[1 << n][n]; // SOLUTION BEGINS for (int mask = 1; mask < 1 << n; mask++) { int start = numberOfTrailingZeros(mask); // the starting vertex of a Hamiltonian walk if (bitCount(mask) == 1) { dp[mask][start] = 1; continue; } for (int i = 0; i < n; i++) { if ((mask & (1 << i)) > 0 && i != start) { int xmask = mask ^ (1 << i); // mask without vertex i for (int j = 0; j < n; j++) { if (d[j][i] > 0) { dp[mask][i] += dp[xmask][j]; } } } } } // SOLUTION ENDS long sum = 0; for (int mask = 1; mask < 1 << n; mask++) { if (bitCount(mask) >= 3) { // We need at least 3 vertices for a cycle for (int i = 0; i < n; i++) { if (d[numberOfTrailingZeros(mask)][i] > 0) { sum += dp[mask][i]; } } } } out.print(sum / 2); } }
np
11_D. A Simple Task
CODEFORCES
import com.sun.org.apache.xpath.internal.operations.Bool; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { MyScanner scan = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = scan.nextInt(); int[] vals = new int[n]; for (int i = 0; i < n; i++) { vals[i] = scan.nextInt(); } for (int i = 0; i < n; i++) { if (solve(i, vals)) { out.print('A'); } else { out.print('B'); } } out.close(); } static HashMap<Integer, Boolean> dpResult = new HashMap<>(); private static boolean solve(int pos, int[] vals) { if (dpResult.containsKey(pos)) return dpResult.get(pos); int val = vals[pos]; boolean hasLose = false; for (int i = pos; i < vals.length; i += val) { if (i == pos) continue; if (vals[i] <= vals[pos]) continue; if (hasLose) break; if (!solve(i, vals)) { hasLose = true; } } for (int i = pos; i >= 0; i -= val) { if (i == pos) continue; if (vals[i] <= vals[pos]) continue; if (hasLose) break; if (!solve(i, vals)) { hasLose = true; } } dpResult.put(pos, hasLose); return hasLose; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
nlogn
1033_C. Permutation Game
CODEFORCES
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class D { public static void main(String[] args) throws Exception { new D().run(); } int[] BIT; public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = f.nextInt(); int[] arr = new int[n]; BIT = new int[n+10]; int inv = 0; for(int i = 0; i < n; i++) { arr[i] = f.nextInt(); inv ^= (i-query(arr[i])) & 1; add(arr[i]); } int k = f.nextInt(); while(k-->0) { int diff = -f.nextInt()+f.nextInt()+1; inv ^= (diff*(diff-1)/2) & 1; out.println(inv == 1 ? "odd" : "even"); } out.flush(); } public int query(int i) { i++; int res = 0; while(i > 0) { res += BIT[i]; i -= i & -i; } return res; } public void add(int i) { i++; while(i < BIT.length) { BIT[i]++; i += i & -i; } } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; public class Solution { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n=in.nextInt(); out.print(n/2+n); out.close(); in.close(); } }
constant
84_A. Toy Army
CODEFORCES
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author coderbd */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public static long MOD = 1000000009L; public long pow(long n, long p) { if (p == 0) return 1L; if (p == 1) return n; long ret = 1L; if (p % 2L != 0) ret = n; long tmp = pow(n, p / 2L); ret = (ret * tmp) % MOD; ret = (ret * tmp) % MOD; return ret; } public long func(long n, long k) { long times = n / k; long ret = n - times * k; ret += ((pow(2L, times + 1L) + MOD - 2L) % MOD) * k % MOD; return ret; } public void solve(int testNumber, InputReader in, OutputWriter out) { long n = in.readLong(); long m = in.readLong(); long k = in.readLong(); long wrong = n - m; long wow = n / k; long ans; if (wrong >= wow) ans = m; else ans = (func(n - wrong * k, k) + (k - 1L) * wrong % MOD) % MOD; out.printLine(ans); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0L; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
logn
338_A. Quiz
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class a implements Comparable<a>{ int x, y, id; //static BufferedReader in; //static StringTokenizer st; public a(int x1, int y1, int id1){ this.x = x1; this.y = y1; this.id = id1; } public int compareTo(a o) { return x - o.x; } static int n; static int arr[]; public static void main(String[] args) { Scanner in = new Scanner(System.in); //in = new BufferedReader(new InputStreamReader(System.in)); //st = new StringTokenizer(""," "); int n = in.nextInt(); arr = new int[n]; int sum = 0; for (int i=0; i<n; i++){ arr[i] = in.nextInt(); sum +=arr[i]; } Arrays.sort(arr); int sum2= 0; int ans = 0; for (int i=n-1; i>=0; i--){ sum2+=arr[i]; //System.out.println(sum2 + " " + sum); if (sum2>sum-sum2){ ans = n - i; break; } } System.out.println(ans); } }
nlogn
160_A. Twins
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] wide = new int[n], sta = new int[n]; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { wide[i] = sc.nextInt(); hm.put(wide[i], i + 1); } Util.sort(wide); sc.nextLine(); String s = sc.nextLine(); int tp = 0, pos = 0; StringBuilder out = new StringBuilder(); for (int i = 0; i < s.length(); i++) { int t; if (s.charAt(i) == '0') { t = wide[pos++]; sta[tp++] = t; } else t = sta[--tp]; out.append(hm.get(t) + " "); } System.out.println(out.toString()); sc.close(); } public static class Util { public static <T extends Comparable<T> > void merge_sort(T[] a) { Object[] aux = new Object[a.length]; merge_sort0(a, aux, 0, a.length); } public static <T extends Comparable<T> > void merge_sort(T[] a, int l, int r) { Object[] aux = new Object[a.length]; merge_sort0(a, aux, l, r); } @SuppressWarnings("unchecked") private static <T extends Comparable<T> > void merge_sort0(T[] a, Object[] temp, int l, int r) { if (l + 1 == r) return; int mid = (l + r) >> 1; merge_sort0(a, temp, l, mid); merge_sort0(a, temp, mid, r); int x = l, y = mid, c = l; while (x < mid || y < r) { if (y == r || (x < mid && a[x].compareTo(a[y]) <= 0)) temp[c++] = a[x++]; else temp[c++] = a[y++]; } for (int i = l; i < r; i++) a[i] = (T)temp[i]; } static final Random RAN = new Random(); public static <T extends Comparable<T> > void quick_sort(T[] a) { quick_sort0(a, 0, a.length); } public static <T extends Comparable<T> > void quick_sort(T[] a, int l, int r) { quick_sort0(a, l, r); } private static <T extends Comparable<T> > void quick_sort0(T[] a, int l, int r) { if (l + 1 >= r) return; int p = l + RAN.nextInt(r - l); T t = a[p]; a[p] = a[l]; a[l] = t; int x = l, y = r - 1; while (x < y) { while (x < y && a[y].compareTo(t) > 0) --y; while (x < y && a[x].compareTo(t) < 0) ++x; if (x < y) { T b = a[x]; a[x] = a[y]; a[y] = b; ++x; --y; } } quick_sort0(a, l, y + 1); quick_sort0(a, x, r); } static final int BOUND = 8; public static void bucket_sort(int[] a) { bucket_sort(a, 0, a.length); } public static void bucket_sort(int[] a, int l, int r) { int[] cnt = new int[1 << BOUND], b = new int[r - l + 1]; int y = 0; for (int i = l; i < r; i++) ++cnt[a[i] & (1 << BOUND) - 1]; while (y < Integer.SIZE) { for (int i = 1; i < 1 << BOUND; i++) cnt[i] += cnt[i - 1]; for (int i = r - 1; i >= l; i--) b[--cnt[a[i] >> y & (1 << BOUND) - 1]] = a[i]; y += BOUND; Arrays.fill(cnt, 0); for (int i = l; i < r; i++) { a[i] = b[i - l]; ++cnt[a[i] >> y & (1 << BOUND) - 1]; } } } public static void bucket_sort(long[] a) { bucket_sort(a, 0, a.length); } public static void bucket_sort(long[] a, int l, int r) { int[] cnt = new int[1 << BOUND]; long[] b = new long[r - l + 1]; int y = 0; while (y < Long.SIZE) { Arrays.fill(cnt, 0); for (int i = l; i < r; i++) ++cnt[(int) (a[i] >> y & (1 << BOUND) - 1)]; for (int i = 1; i < 1 << BOUND; i++) cnt[i] += cnt[i - 1]; for (int i = r - 1; i >= l; i--) b[--cnt[(int) (a[i] >> y & (1 << BOUND) - 1)]] = a[i]; for (int i = l; i < r; i++) a[i] = b[i - l]; y += BOUND; } } public static void sort(int[] a) { if (a.length <= 1 << BOUND) { Integer[] b = new Integer[a.length]; for (int i = 0; i < a.length; i++) b[i] = a[i]; quick_sort(b); for (int i = 0; i < a.length; i++) a[i] = b[i]; } else bucket_sort(a); } public static void sort(long[] a) { if (a.length <= 1 << BOUND) { Long[] b = new Long[a.length]; for (int i = 0; i < a.length; i++) b[i] = a[i]; quick_sort(b); for (int i = 0; i < a.length; i++) a[i] = b[i]; } else bucket_sort(a); } public static <T extends Comparable<T> > void sort(T[] a) { quick_sort(a); } public static void shuffle(int[] a) { Random ran = new Random(); for (int i = 0; i < a.length; i++) { int p = ran.nextInt(i + 1); int q = a[p]; a[p] = a[i]; a[i] = q; } } public static void shuffle(long[] a) { Random ran = new Random(); for (int i = 0; i < a.length; i++) { int p = ran.nextInt(i + 1); long q = a[p]; a[p] = a[i]; a[i] = q; } } public static <T> void shuffle(T[] a) { Random ran = new Random(); for (int i = 0; i < a.length; i++) { int p = ran.nextInt(i + 1); T q = a[p]; a[p] = a[i]; a[i] = q; } } } }
nlogn
982_B. Bus of Characters
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); FElongatedMatrix solver = new FElongatedMatrix(); solver.solve(1, in, out); out.close(); } static class FElongatedMatrix { int[][] G; int[][] G1; public int findIt(int[] map, int n, int start) { int[][] mask = new int[1 << n][n]; for (int i = 0; i < n; i++) mask[(1 << i)][i] = G[start][map[i]]; for (int i = 1; i < (1 << n); i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (k != j && (i & (1 << k)) == 0 && (i & (1 << j)) != 0) { mask[(i | (1 << k))][k] = Math.max(mask[(i | (1 << k))][k], Math.min(mask[i][j], G[map[j]][map[k]])); } } } } int ans = 0; for (int i = 0; i < n; i++) ans = Math.max(ans, Math.min(mask[(1 << n) - 1][i], G1[start][map[i]])); return ans; } public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int m = in.scanInt(); G = new int[n][n]; G1 = new int[n][n]; int[][] ar = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ar[i][j] = in.scanInt(); } } if (n == 1) { int ans = Integer.MAX_VALUE; for (int i = 0; i < m - 1; i++) ans = Math.min(ans, Math.abs(ar[0][i] - ar[0][i + 1])); out.println(ans); return; } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int min = Integer.MAX_VALUE; for (int k = 0; k < m; k++) min = Math.min(min, Math.abs(ar[i][k] - ar[j][k])); G[i][j] = G[j][i] = min; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; int min = Integer.MAX_VALUE; for (int k = 1; k < m; k++) min = Math.min(min, Math.abs(ar[i][k] - ar[j][k - 1])); G1[i][j] = min; } } int[] map; int ans = 0; for (int i = 0; i < n; i++) { map = new int[n - 1]; int tl = 0; for (int temp = 0; temp < n; temp++) { if (temp == i) continue; map[tl++] = temp; } ans = Math.max(ans, findIt(map, n - 1, i)); } out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class A { private void solve() throws IOException { int n = nextInt(); int k = nextInt(); Point[] p = new Point[n]; for (int i = 0; i < n; i++) p[i] = new Point(nextInt(), nextInt()); Arrays.sort(p, new Comparator<Point>() { @Override public int compare(Point o1, Point o2) { if (o1.x == o2.x) return o1.y - o2.y; return o2.x - o1.x; } }); Point cur = p[k - 1]; int res = 0; for (int i = 0; i < p.length; i++) { if (p[i].x == cur.x && p[i].y == cur.y) res++; } pl(res); } public static void main(String[] args) { new A().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } void p(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.flush(); writer.print(objects[i]); writer.flush(); } } void pl(Object... objects) { p(objects); writer.flush(); writer.println(); writer.flush(); } int cc; void pf() { writer.printf("Case #%d: ", ++cc); writer.flush(); } }
nlogn
166_A. Rank List
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n, t[], g[], MOD = (int) 1e9 + 7; static int[][][] memo1, memo2[], memo3[]; static int dp1(int idx, int remCnt, int remSum) { if (idx == n) return remSum == 0 && remCnt==0 ? 1 : 0; if(remCnt<0 || remSum<0) return 0; if (memo1[idx][remCnt][remSum] != -1) return memo1[idx][remCnt][remSum]; int ans = dp1(idx + 1, remCnt, remSum); if (g[idx] == 0) { ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]); if (ans >= MOD) ans -= MOD; } return memo1[idx][remCnt][remSum] = ans; } static int dp2(int idx, int remCnt1, int remCnt2, int remSum) { int all = remCnt1 + remCnt2; if (all == 0) return remSum == 0 ? 1 : 0; if (idx == n || remSum == 0) return 0; if (memo2[idx][remCnt1][remCnt2][remSum] != -1) return memo2[idx][remCnt1][remCnt2][remSum]; int ans = dp2(idx + 1, remCnt1, remCnt2, remSum); if (t[idx] <= remSum) { if (g[idx] == 1 && remCnt1 > 0) ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]); else if (g[idx] == 2 && remCnt2 > 0) ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]); } return memo2[idx][remCnt1][remCnt2][remSum] = ans; } private static int dp3(int cnt0, int cnt1, int cnt2, int last) { if (cnt0 + cnt1 + cnt2 == 0) return 1; if (memo3[last][cnt0][cnt1][cnt2] != -1) return memo3[last][cnt0][cnt1][cnt2]; long ans = 0; if (cnt0 > 0 && last != 0) ans += dp3(cnt0 - 1, cnt1, cnt2, 0); if (cnt1 > 0 && last != 1) ans += dp3(cnt0, cnt1 - 1, cnt2, 1); if (cnt2 > 0 && last != 2) ans += dp3(cnt0, cnt1, cnt2 - 1, 2); return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); int[] fac = new int[n + 1]; t = new int[n]; g = new int[n]; int[] cnt = new int[3]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (int) (i * 1L * fac[i - 1] % MOD); int T = sc.nextInt(); for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; cnt[g[i]]++; } memo1 = new int[n][cnt[0] + 1][T + 1]; memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1]; memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= cnt[0]; j++) Arrays.fill(memo1[i][j], -1); for (int j = 0; j <= cnt[1]; j++) for (int k = 0; k <= cnt[2]; k++) Arrays.fill(memo2[i][j][k], -1); } for (int i = 0; i < 4; i++) for (int j = 0; j <= cnt[0]; j++) for (int k = 0; k <= cnt[1]; k++) Arrays.fill(memo3[i][j][k], -1); int ans = 0; for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++) for (int sum0 = 0; sum0 <= T; sum0++) for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++) for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) { long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD; ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD; ways *= fac[cnt0]; ways %= MOD; ways *= fac[cnt1]; ways %= MOD; ways *= fac[cnt2]; ways %= MOD; ans += ways; if (ans >= MOD) ans -= MOD; } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class order { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(System.out))); int n=Integer.parseInt(in.readLine()); Set<Integer> set = new TreeSet<Integer>(); StringTokenizer st= new StringTokenizer(in.readLine()); int a; List<Integer> list =new LinkedList<Integer>(); while(st.hasMoreTokens()){ a= Integer.parseInt(st.nextToken()); if(!set.contains(a)){ list.add(a); set.add(a); } } if(list.size()==1){ out.println("NO"); }else{ Collections.sort(list); out.println(list.get(1)); } out.close(); System.exit(0); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class DD { public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int [] a=new int [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); TreeMap<Integer, Integer> map=new TreeMap<Integer, Integer>(); BigInteger ans=new BigInteger("0"); long sum=0; for(int i=0;i<n;i++){ sum+=a[i]; map.put(a[i], map.getOrDefault(a[i], 0)+1); int cntSame=map.get(a[i]); int cntLess=map.getOrDefault(a[i]-1, 0); int cntMore=map.getOrDefault(a[i]+1, 0); long sum2=sum; sum2-=1L*cntSame*a[i]; sum2-=1L*cntLess*(a[i]-1); sum2-=1L*cntMore*(a[i]+1); int cnt=i+1-(cntSame+cntLess+cntMore); ans = ans.subtract(BigInteger.valueOf(sum2)); ans= ans.add(BigInteger.valueOf(1L*cnt*a[i])); } pw.println(ans); pw.flush(); pw.close(); } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() {while (st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}} return st.nextToken();} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} String nextLine(){String str = ""; try {str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str;} } }
nlogn
903_D. Almost Difference
CODEFORCES
//package CodeforcesJava; import java.io.*; import java.util.*; public class Main { public void solve(InputProvider input, PrintWriter output) throws IOException { int n = input.nextInt(); int d = input.nextInt(); int count = 1; int current = input.nextInt(); for (int i = 1; i < n; i++) { int x = input.nextInt(); if (x - current == d * 2) { count++; } else if (x - current > d * 2) { count += 2; } current = x; } count++; output.print(count); } public static void main(String[] args) throws Exception { try (InputProvider input = new InputProvider(System.in); PrintWriter output = new PrintWriter(System.out)) { new Main().solve(input, output); } } public static class InputProvider implements AutoCloseable { private final BufferedReader reader; private StringTokenizer tokenizer; public InputProvider(Reader reader) { this.reader = new BufferedReader(reader); } public InputProvider(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); } public String next() throws IOException { if (Objects.isNull(tokenizer) || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { return reader.readLine(); } @Override public void close() throws Exception { reader.close(); } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sandip Jana */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { long x = in.readLong(); if (x % 2 == 1) { out.println("NO"); return; } if (x % 2 == 0) { long p = x / 2; long square = (long) Math.sqrt(p); if (square * 1L * square == p) { out.println("YES"); return; } } if (x % 4 == 0) { long p = x / 4; long square = (long) Math.sqrt(p); if (square * 1L * square == p) { out.println("YES"); return; } } out.println("NO"); } } 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 String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import java.util.regex.*; public class Main { static InputReader in; public static void main(String[] args) throws IOException{ File file = new File("input.txt"); if(file.exists())in = new InputReader( new FileInputStream(file) ); else in = new InputReader( System.in ); int n=in.nextInt(), m=in.nextInt(), k=in.nextInt(); int a[]=new int[n]; for( int i=0; i<n; i++ ) a[i]=in.nextInt(); Arrays.sort( a ); int i=n-1, ans=0; while( k<m && i>=0 ) { k+=a[i]-1; i--; ans++; } if( m<=k ) System.out.println( ans ); else System.out.println("-1"); } // IO utilities: static void out(Object ...o){ System.out.println(Arrays.deepToString(o)); } static class InputReader { private BufferedInputStream inp; private int offset; private final int size=5120000; private byte buff[]; InputReader( InputStream in ) throws IOException { inp = new BufferedInputStream( in ); buff=new byte[size]; offset=0; inp.read( buff, 0, size ); } int nextInt() throws IOException { int parsedInt=0; int i=offset; if( buff[i]==0 ) throw new IOException(); //EOF // skip any non digits while ( i<size && ( buff[i]<'0' || buff[i]>'9' ) ) i++; // read digits and parse number while( i<size && buff[i]>='0' && buff[i]<='9') { parsedInt*=10; parsedInt+=buff[i]-'0'; i++; } // check if we reached end of buffer if ( i==size ) { // copy leftovers to buffer start int j = 0; for ( ; offset<buff.length; j++, offset++ ) buff[j] = buff[offset]; // and now fill the buffer inp.read( buff, j, size - j ); // and attempt to parse int again offset = 0; parsedInt = nextInt(); } else offset=i; return parsedInt; } long nextLong() throws IOException{ long parsedLong=0; int i=offset; if( buff[i]==0 ) throw new IOException(); //EOF // skip any non digits while( i<size && ( buff[i]<'0' || buff[i]>'9' ) ) i++; // read digits and parse number while( i<size && buff[i]>='0' && buff[i]<='9') { parsedLong*=10L; parsedLong+=buff[i]-'0'; i++; } // check if we reached end of buffer if ( i==size ) { // copy leftovers to buffer start int j = 0; for ( ; offset<buff.length; j++, offset++ ) buff[j] = buff[offset]; // and now fill the buffer inp.read( buff, j, size - j ); // and attempt to parse int again offset = 0; parsedLong = nextLong(); } else offset=i; return parsedLong; } String next() throws IOException { StringBuilder token=new StringBuilder(); int i=offset; if( buff[i]==0 ) throw new IOException(); //EOF // skip any non chars while( i<size && ( buff[i]=='\n' || buff[i]==' ' || buff[i]=='\r' || buff[i]=='\t' ) ) i++; // read chars while( i<size && buff[i]!='\n' && buff[i]!=' ' && buff[i]!='\r' && buff[i]!='\t' && buff[i]!=0 ) { token.append( (char)buff[i] ); i++; } // check if we reached end of buffer if ( i==size ) { // copy leftovers to buffer start int j = 0; for ( ; offset<buff.length; j++, offset++ ) buff[j] = buff[offset]; // and now fill the buffer inp.read( buff, j, size - j ); // and attempt to parse int again offset = 0; return next(); } else offset=i; return token.toString(); } String nextLine() throws IOException { StringBuilder line=new StringBuilder(); int i=offset; if( buff[i]==0 ) throw new IOException(); //EOF // read chars while( i<size && buff[i]!='\n' && buff[i]!=0 ) { line.append( (char)buff[i] ); i++; } if( i<size && buff[i]=='\n' ) i++; // check if we reached end of buffer if ( i==size ) { // copy leftovers to buffer start int j = 0; for ( ; offset<buff.length; j++, offset++ ) buff[j] = buff[offset]; // and now fill the buffer inp.read( buff, j, size - j ); // and attempt to parse int again offset = 0; return nextLine(); } else offset=i; line.deleteCharAt( line.length()-1 ); return line.toString(); } } }
nlogn
257_A. Sockets
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Solution{ public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = Integer.parseInt(st.nextToken()); int ind = 0; for(int i=0;i<n;i++){ if(a[i]==n){ ind = i; break; } } boolean ok = true; for(int i=ind+1;i<n;i++) if(a[i]>a[i-1]) ok = false; for(int i=ind-1;i>=0;i--) if(a[i]>a[i+1]) ok = false; if(ok) System.out.println("YES"); else System.out.println("NO"); } }
linear
1197_B. Pillars
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Asgar Javadov */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] a = in.readIntArray(n); ArrayUtils.radixSort(a); int answer = 0; boolean[] used = new boolean[a.length]; for (int i = 0; i < a.length; ++i) { if (used[i]) continue; used[i] = true; answer++; for (int j = i + 1; j < a.length; ++j) if (a[j] % a[i] == 0) used[j] = true; } out.println(answer); } } static class ArrayUtils { public static void radixSort(int[] array) { int[] ordered = new int[array.length]; { int[] freq = new int[0xFFFF + 2]; for (int i = 0; i < array.length; ++i) freq[(array[i] & 0xFFFF) + 1]++; for (int i = 1; i < freq.length; ++i) freq[i] += freq[i - 1]; for (int i = 0; i < array.length; ++i) ordered[freq[array[i] & 0xFFFF]++] = array[i]; for (int i = 0; i < array.length; ++i) array[i] = ordered[i]; } { int[] freq = new int[0xFFFF + 2]; for (int i = 0; i < array.length; ++i) freq[(array[i] >>> 16) + 1]++; for (int i = 1; i < freq.length; ++i) freq[i] += freq[i - 1]; for (int i = 0; i < array.length; ++i) ordered[freq[array[i] >>> 16]++] = array[i]; int indexOfFirstNegative = freq[0x7FFF]; int index = 0; for (int i = indexOfFirstNegative; i < ordered.length; ++i, ++index) array[index] = ordered[i]; for (int i = 0; i < indexOfFirstNegative; ++i, ++index) array[index] = ordered[i]; } } } static class OutputWriter extends PrintWriter { public OutputWriter(OutputStream outputStream) { super(outputStream); } public OutputWriter(Writer writer) { super(writer); } public OutputWriter(String filename) throws FileNotFoundException { super(filename); } public void close() { super.close(); } } static class InputReader extends BufferedReader { StringTokenizer tokenizer; public InputReader(InputStream inputStream) { super(new InputStreamReader(inputStream), 32768); } public InputReader(String filename) { super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename))); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(readLine()); } catch (IOException e) { throw new RuntimeException(); } } return tokenizer.nextToken(); } public Integer nextInt() { return Integer.valueOf(next()); } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = nextInt(); return array; } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import static java.lang.Math.*; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class CFC23A implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok; public static void main(String[] args) { new Thread(new CFC23A()).start(); } void solve() throws IOException { int res = 0; String str = nextToken(); for(int i = 0; i < str.length(); ++i) for(int j = i + 1; j <= str.length(); ++j) if(isOk(str.substring(i, j), str)) res = max(res, j - i); out.println(res); } private boolean isOk(String substring, String str) { int from = 0, kol = 0; while(str.indexOf(substring, from) != -1 && kol < 2) { ++kol; from = str.indexOf(substring, from) + 1; } return kol >= 2; } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); // in = new BufferedReader(new FileReader(new File("input.txt"))); out = new PrintWriter(System.out); //out = new PrintWriter(new File("output.txt")); solve(); out.flush(); out.close(); in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String nextLine() throws IOException { tok = null; return in.readLine(); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class E { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out, false); int n = scanner.nextInt(); int m = scanner.nextInt(); char[] str = scanner.next().toCharArray(); int maxMask = 1 << m; long[] dp = new long[maxMask]; int[][] dists = new int[m][m]; for(int i = 1; i < n; i++) { int c1 = str[i] - 'a'; int c2 = str[i-1] - 'a'; dists[c1][c2]++; dists[c2][c1]++; } int[] pre = new int[maxMask]; for(int mask = 0; mask < maxMask; mask++) { for(int i = 0; i < m; i++) { if (((1 << i) & mask) == 0) continue; for(int j = 0; j < m; j++) { if (((1 << j) & mask) > 0) continue; pre[mask] += dists[i][j]; } } } Arrays.fill(dp, Long.MAX_VALUE/4); dp[0] = 0; for(int mask = 0; mask < maxMask; mask++) { if (dp[mask] == Long.MAX_VALUE/4) continue; for(int i = 0; i < m; i++) { if (((1 << i) & mask) > 0) continue; int nmask = mask | (1 << i); dp[nmask] = Math.min(dp[nmask], dp[mask] + pre[nmask]); } } out.println(dp[maxMask - 1]); out.flush(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.math.BigDecimal; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.Set; public class Task16e { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); double[][] prob = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { prob[i][j] = sc.nextDouble(); } } double[] var = new double[1 << n]; boolean[] was = new boolean[1 << n]; Arrays.fill(var, 0.0); Arrays.fill(was, false); was[0] = true; var[(1 << n) - 1] = 1.0; Set<Integer> cr = new HashSet<Integer>(); Set<Integer> nx = new HashSet<Integer>(); nx.add((1 << n) - 1); boolean[] fish = new boolean[n]; for (int cnt = 0; cnt < n -1; cnt++) { cr.clear(); cr.addAll(nx); nx.clear(); for (Iterator<Integer> iterator = cr.iterator(); iterator.hasNext();) { int curr = iterator.next(); for (int i = 0; i < n; i++) { fish[i] = ((1 << i) & curr) != 0; } int fishn = 0; for (int i = 0; i < n; i++) { if (fish[i]) fishn++; } if (fishn == 1) continue; for (int i = 0; i < n; i++) { if (!fish[i]) continue; for (int j = i + 1; j < n; j++) { if (!fish[j]) continue; int woi = curr & ~(1 << i); int woj = curr & ~(1 << j); var[woi] += var[curr] * prob[j][i]; var[woj] += var[curr] * prob[i][j]; nx.add(woi); nx.add(woj); } } } } double sum = 0.0; for (int i = 0; i < n; i++) { sum += var[1 << i]; } for (int i = 0; i < n; i++) { System.out.printf("%.6f ", var[1 << i] / sum); } } }
np
16_E. Fish
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); long a=s.nextLong(), b=s.nextLong(); long c=0; while(true) { if(a==b ){ System.out.println(c+a); return ; } else if(b==a+1){ c+=1; b=a; } else if(b<a){ long h = a/b-1; if(h<=0){ a-=b;c++;continue; } a-=b*h; c+=h; } else{ if(a==1){ long t = b-a; b = t; c+=t; b = a; continue; } long t = b-a; long h = b/a - 1 ; if(h<=0){ b = t; c+=1;continue; } c+=h;b-=h*a; // b = a; } } // System.out.println(c); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.util.Random; import java.util.Comparator; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion(); int testCount = in.scanInt(); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class E2RotateColumnsHardVersion { int[][] dp; int[] cur; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int m = in.scanInt(); int[][] ar = new int[n][m]; int[][] max = new int[m][2]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) ar[i][j] = in.scanInt(); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { max[i][0] = Math.max(max[i][0], ar[j][i]); } max[i][1] = i; } CodeHash.shuffle(max); Arrays.sort(max, new Comparator<int[]>() { public int compare(int[] o1, int[] o2) { return -o1[0] + o2[0]; } }); dp = new int[2][1 << n]; cur = new int[1 << n]; for (int i = 0; i < Math.min(m, n); i++) { Arrays.fill(cur, 0); Arrays.fill(dp[i & 1], 0); for (int j = 0; j < 1 << n; j++) { for (int k = 0; k < n; k++) { int sum = 0; for (int l = 0; l < n; l++) { if ((j & (1 << l)) != 0) { sum += (ar[(k + l) % n][max[i][1]]); } } cur[j] = Math.max(cur[j], sum); } } for (int j = 0; j < (1 << n); j++) { for (int k = j; ; k = (k - 1) & j) { dp[i & 1][j] = Math.max(dp[i & 1][j], dp[(i - 1) & 1][k] + cur[j ^ k]); if (k == 0) break; } } } out.println(dp[Math.min(n, m) & 1 ^ 1][(1 << n) - 1]); } } static class CodeHash { public static void shuffle(int[][] ar) { Random rd = new Random(new Random().nextInt()); for (int i = 0; i < ar.length; i++) { int index = rd.nextInt(ar.length); int[] temp = ar[i]; ar[i] = ar[index]; ar[index] = temp; } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; import java.io.*; public class a { public static void main(String[] args) throws IOException { //Scanner input = new Scanner(new File("input.txt")); //PrintWriter out = new PrintWriter(new File("output.txt")); PrintWriter out = new PrintWriter(System.out); input.init(System.in); long a = input.nextLong(), b = input.nextLong(); if(a==b) { out.println(0); out.close(); return; } long res = 0; for(int i = 0; i<63; i++) { if(a%(1l<<i) >= b%(1l<<i)) res += (1l<<i); else if(b/((1l<<i)) > a/((1l<<i))) res += (1l<<i); } out.println(res); out.close(); } public static long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a%b); } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } } static class IT { int[] left,right, val, a, b; IT(int n) { left = new int[3*n]; right = new int[3*n]; val = new int[3*n]; a = new int[3*n]; b = new int[3*n]; init(0,0, n); } int init(int at, int l, int r) { a[at] = l; b[at] = r; if(l==r) left[at] = right [at] = -1; else { int mid = (l+r)/2; left[at] = init(2*at+1,l,mid); right[at] = init(2*at+2,mid+1,r); } return at++; } //return the sum over [x,y] int get(int x, int y) { return go(x,y, 0); } int go(int x,int y, int at) { if(at==-1) return 0; if(x <= a[at] && y>= b[at]) return val[at]; if(y<a[at] || x>b[at]) return 0; return go(x, y, left[at]) + go(x, y, right[at]); } //add v to elements x through y void add(int x, int y, int v) { go3(x, y, v, 0); } void go3(int x, int y, int v, int at) { if(at==-1) return; if(y < a[at] || x > b[at]) return; val[at] += (Math.min(b[at], y) - Math.max(a[at], x) + 1)*v; go3(x, y, v, left[at]); go3(x, y, v, right[at]); } } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class e { public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } static ArrayList<String>list1=new ArrayList<String>(); static void combine(String instr, StringBuffer outstr, int index,int k) { if(outstr.length()==k) { list1.add(outstr.toString());return; } if(outstr.toString().length()==0) outstr.append(instr.charAt(index)); for (int i = 0; i < instr.length(); i++) { outstr.append(instr.charAt(i)); combine(instr, outstr, i + 1,k); outstr.deleteCharAt(outstr.length() - 1); } index++; } static ArrayList<ArrayList<Integer>>l=new ArrayList<>(); static void comb(int n,int k,int ind,ArrayList<Integer>list) { if(k==0) { l.add(new ArrayList<>(list)); return; } for(int i=ind;i<=n;i++) { list.add(i); comb(n,k-1,ind+1,list); list.remove(list.size()-1); } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static void main(String[] args) { // TODO Auto-generated method stub FastReader in=new FastReader(); HashMap<Integer,Integer>map=new HashMap<Integer,Integer>(); int n=in.nextInt(); int r=in.nextInt(); double theta=(double)360/(double)n; double b=1-((double)2/(double)(1-Math.cos((double)2*Math.PI/(double)n))); double x=Math.sqrt(1-b)-1; double ans=(double)r/(double)x; System.out.println(ans); } }
constant
1100_C. NN and the Optical Illusion
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); int ans = 0; boolean[] taken = new boolean[n]; Arrays.sort(a); for (int i = 0; i < n; i++) { if (taken[i]) continue; ans++; for (int j = i; j < n; j++) if (a[j] % a[i] == 0) taken[j] = true; } out.println(ans); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; public class A { public static void main(String args[]) { Scanner sc=new Scanner(System.in); long n=sc.nextLong(); if(n==0) System.out.println(0); else if(n%2==1) System.out.println((n+1)/2); else System.out.println(n+1); } }
constant
979_A. Pizza, Pizza, Pizza!!!
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.util.*; import java.io.*; public class B{ static int[][] hor; static int[][] ver; static int n; static int m; static int k; static long[][][] dp; static long dist(int row, int col) { if(k%2==1)return Integer.MAX_VALUE; return 2*make(row,col,k/2); } static long make(int row, int col, int moves) { if(moves == 0) { return 0; } if(dp[row][col][moves]!=-1)return dp[row][col][moves]; long ans = Long.MAX_VALUE; if(col-1>=0) { ans = Math.min(ans, hor[row][col-1]+make(row,col-1,moves-1)); } if(col+1<m) { ans = Math.min(ans, hor[row][col]+make(row,col+1,moves-1)); } if(row-1>=0) { ans = Math.min(ans, ver[row-1][col]+make(row-1,col,moves-1)); } if(row+1<n) { ans = Math.min(ans, ver[row][col]+make(row+1,col,moves-1)); } dp[row][col][moves] = ans; return ans; } public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); n = fs.nextInt(); m = fs.nextInt(); k = fs.nextInt(); hor = new int[n][m]; ver = new int[n][m]; dp = new long[505][505][24]; for(int i=0;i<505;i++)for(int j=0;j<505;j++)for(int k=0;k<24;k++)dp[i][j][k] = -1; for(int i=0;i<n;i++) { for(int j=0;j<m-1;j++) { int a = fs.nextInt(); hor[i][j] = a; } } for(int row=0;row<n-1;row++) { for(int col =0;col<m;col++) { int a = fs.nextInt(); ver[row][col] = a; } } for(int row=0;row<n;row++) { for(int col=0;col<m;col++) { long d = dist(row,col); if(d<Integer.MAX_VALUE) { out.print(d+" "); } else out.print("-1 "); } out.println(); } out.close(); } 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()); } } public static int[] sort(int[] arr) { List<Integer> temp = new ArrayList(); for(int i:arr)temp.add(i); Collections.sort(temp); int start = 0; for(int i:temp)arr[start++]=i; return arr; } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class c { public static void main(String args[]) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); //BEGIN HERE int n = in.nextInt(); int r = in.nextInt(); int xs[] = new int[n]; for(int i = 0; i < n; i++) xs[i] = in.nextInt(); double ys[] = new double[n]; ys[0] = r; for(int i = 1; i < n; i++) { double worst = r; for(int j = 0; j < i; j++) { if(xs[i] == xs[j]) { worst = Math.max(worst, ys[j] + r + r); }else if((xs[i] - xs[j]) * (xs[i] - xs[j]) <= 4*r*r ) { double hypot = r + r; double adj = Math.abs((xs[i] - xs[j])); double theta = Math.acos(adj/hypot); worst = Math.max(hypot * Math.sin(theta) + ys[j], worst); } } ys[i] = worst; } for(int i = 0; i < n; i++) out.printf("%.10f ",ys[i]); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = null; } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { if (st == null) { st = new StringTokenizer(br.readLine()); } String line = st.nextToken("\n"); st = null; return line; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static class combinatorics { static long modInv(long a, long b) { return 1 < a ? b - modInv(b % a, a) * b / a : 1; } static long factorial[], mod; combinatorics(int n, long MOD) { mod = MOD; factorial = new long[n + 1]; factorial[0] = 1; for (int i = 1; i <= n; i++) { factorial[i] = i * factorial[i - 1]; factorial[i] %= mod; } } static long nCr(int n, int r) { if (r > n) return 0; return (factorial[n] * modInv((factorial[n - r] * factorial[r]) % mod, mod)) % mod; } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } } public static class DisjointSet { int p[], r[], s[]; int numDisjoint; DisjointSet(int N) { numDisjoint = N; r = new int[N]; s = new int[N]; p = new int[N]; for (int i = 0; i < N; i++) p[i] = i; } int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } void unionSet(int i, int j) { if (!isSameSet(i, j)) // if from different set { numDisjoint--; int x = findSet(i), y = findSet(j); if (r[x] > r[y]) { p[y] = x; // rank keeps the tree short s[x] += s[y]; } else { p[x] = y; if (r[x] == r[y]) r[y]++; s[y] += s[x]; } } } int sizeOfSet(int i) { return s[findSet(i)]; } }; }
quadratic
908_C. New Year and Curling
CODEFORCES
/* * Code Author: Akshay Miterani * DA-IICT */ import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class A { static double eps=(double)1e-15; static long mod=(int)1e9+7; public static void main(String args[]){ InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); //----------My Code---------- int n=in.nextInt(); int l=0,r=0; String s=in.nextLine(); HashSet<Character> size=new HashSet<>(); for(int i=0;i<n;i++){ char p=s.charAt(i); size.add(p); } int chk=size.size(); HashMap<Character, Integer> hm=new HashMap<>(); int ans=Integer.MAX_VALUE; while(l<n){ if(hm.size()<chk && r<n){ char p=s.charAt(r); if(hm.containsKey(p)){ hm.put(p, hm.get(p)+1); } else{ hm.put(p, 1); } r++; } else{ char p=s.charAt(l); if(hm.get(p)==1){ hm.remove(p); } else{ hm.put(p, hm.get(p)-1); } l++; } if(hm.size()==chk){ ans=Math.min(ans, r-l); } } out.println(ans); out.close(); //---------------The End------------------ } static class Pair implements Comparable<Pair> { int u; int v; 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) { return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } 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; } 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; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine(){ String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; public class CF1102F { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[][] aa = new int[n][m]; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < m; j++) aa[i][j] = Integer.parseInt(st.nextToken()); } int[][] dd = new int[n][n]; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { int d = Integer.MAX_VALUE; for (int h = 0; h < m; h++) d = Math.min(d, Math.abs(aa[i][h] - aa[j][h])); dd[i][j] = dd[j][i] = d; } int[][] dd_ = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int d = Integer.MAX_VALUE; for (int h = 0; h < m - 1; h++) d = Math.min(d, Math.abs(aa[i][h] - aa[j][h + 1])); dd_[i][j] = d; } if (n == 1) { System.out.println(dd_[0][0]); return; } int[] ii = new int[1 << n]; for (int i = 0; i < n; i++) ii[1 << i] = i; int[][][] dp = new int[1 << n][n][n]; for (int b = 0; b < 1 << n; b++) for (int u = b; u > 0; u &= u - 1) { int i = ii[u & -u]; for (int v = b ^ 1 << i; v > 0; v &= v - 1) { int j = ii[v & -v]; if (b == (1 << i ^ 1 << j)) dp[b][i][j] = dd[i][j]; else { int x = 0; for (int w = b ^ 1 << i ^ 1 << j; w > 0; w &= w - 1) { int k = ii[w & -w]; x = Math.max(x, Math.min(dp[b ^ 1 << j][i][k], dd[k][j])); } dp[b][i][j] = x; } } } int b = (1 << n) - 1; int x = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (i != j) x = Math.max(x, Math.min(dp[b][i][j], dd_[i][j])); System.out.println(x); } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class YouAreGivenAString { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String s=r.readLine(); int max=0; for(int i=1;i<s.length();i++){ for (int j = 0; j <= s.length()-i; j++) { String sub=s.substring(j,j+i); if(count(s,sub)>=2) max=Math.max(max, i); } } System.out.println(max); } private static int count(String s, String sub) { int l=sub.length(); int c=0; for(int i=0;i<=s.length()-l;i++){ if(s.substring(i,i+l).equals(sub)) c++; } return c; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { static class Point { int x; int y; Point(int a, int b) { x = a; y = b; } @Override public String toString() { return "Point{" + "x=" + x + ", y=" + y + '}'; } } public static void main(String[] args) throws IOException { File f = new File("input.txt"); Scanner sc = new Scanner(f); BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt"))); int n = sc.nextInt(); int m = sc.nextInt(); boolean[][] board = new boolean[n][m]; int count = sc.nextInt(); Point[] burningTrees = new Point[count]; for (int i=0; i<count; i++) { burningTrees[i] = new Point(sc.nextInt() - 1,sc.nextInt() - 1); } Point last = findLastPoint(board,burningTrees); bw.append((last.x + 1) + " " + (last.y + 1) + "\n"); bw.flush(); bw.close(); sc.close(); } public static Point findLastPoint(boolean[][] board, Point[] burningTree){ Queue<Point> queue = new LinkedList<Point>(); for(int i = 0; i <burningTree.length; i++ ) { queue.add(burningTree[i]); board[burningTree[i].x][burningTree[i].y] = true; } Point lastPoint = new Point(-1,-1); while (!queue.isEmpty()) { Point p = queue.poll(); lastPoint = p; ArrayList<Point> neighbours = getNeighbours(p,board); for(int i = 0; i <neighbours.size(); i++ ) { queue.add(neighbours.get(i)); board[neighbours.get(i).x][neighbours.get(i).y] = true; } } return lastPoint; } public static ArrayList<Point> getNeighbours(Point p, boolean[][] board){ ArrayList<Point> neighbours = new ArrayList<>(); for(int i = -1; i <=1; i++ ){ for(int j = -1; j <= 1; j++ ){ if(Math.abs(i) != Math.abs(j)) { int x = p.x + i; int y = p.y + j; if (x >= 0 && x < board.length && y >= 0 && y < board[0].length) { if (board[x][y] == false) { neighbours.add(new Point(x,y)); } } } } } return neighbours; } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); if(n < 3) out.println(n); else { if((n & 1) == 1) out.println(lcm(n, lcm(n - 1, n - 2))); else out.println(Math.max(lcm(n - 1, lcm(n - 2, n - 3)), lcm(n, lcm(n - 1, n - 3)))); } out.flush(); out.close(); } static long gcd(long a, long b) { while(b != 0) { a = a%b; b ^= a; a ^= b; b ^= a; } return a; } static long lcm(long a, long b) { return a / gcd(a,b) * b; } } 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 int nextInt() { return Integer.parseInt(next()); } }
constant
235_A. LCM Challenge
CODEFORCES
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class ProblemD { static int n; static int m; static boolean[][] fire; public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File("input.txt")); n = sc.nextInt(); m = sc.nextInt(); int k = sc.nextInt(); fire = new boolean[n][m]; Queue<Pos> q = new LinkedList<Pos>(); for (int i = 0; i < k; i++) { int x = sc.nextInt(); int y = sc.nextInt(); q.add(new Pos(x - 1, y - 1)); fire[x - 1][y - 1] = true; } int[] di = new int[] { 1, -1, 0, 0 }; int[] dj = new int[] { 0, 0, 1, -1}; Pos last = null; while (q.size() > 0) { Pos pos = q.poll(); last = pos; for (int kk = 0; kk < 4; kk++) { int ni = pos.i + di[kk]; int nj = pos.j + dj[kk]; if (ni >= 0 && nj >= 0 && ni < n && nj < m) { if (!fire[ni][nj]) { fire[ni][nj] = true; q.add(new Pos(ni, nj)); } } } } PrintWriter out = new PrintWriter(new File("output.txt")); out.println((last.i + 1) + " " + (last.j + 1)); out.flush(); out.close(); } } class Pos { int i, j; public Pos(int i, int j) { super(); this.i = i; this.j = j; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + i; result = prime * result + j; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pos other = (Pos) obj; if (i != other.i) return false; if (j != other.j) return false; return true; } };
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.util.*; public final class subtractions { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static long solve(long a,long b) { if(a<=0 || b<=0) { return 0; } else { long max=Math.max(a,b),min=Math.min(a,b); long low=1,high=(long)(1e9); while(low<high) { long mid=(low+high)>>1,val=(min*mid),curr=max-val; if(curr<min) { high=mid; } else { low=mid+1; } } return low+solve(min,max-(low*min)); } } public static void main(String args[]) throws Exception { int t=sc.nextInt(); while(t>0) { long a=sc.nextLong(),b=sc.nextLong(); out.println(solve(a,b)); t--; } out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
constant
267_A. Subtractions
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.math.BigInteger; import java.util.HashMap; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); BigInteger ans = new BigInteger("0"); long val, index, index1, index2; long sum[] = new long[n]; val = in.scanInt(); HashMap<Long, Integer> hs = new HashMap<>(); hs.put(val, 1); sum[0] = val; for (int i = 1; i < n; i++) { val = in.scanInt(); sum[i] += sum[i - 1]; sum[i] += val; if (!hs.containsKey(val)) hs.put(val, 0); hs.put(val, hs.get(val) + 1); ans = ans.add(BigInteger.valueOf(((i + 1) * val) - sum[i])); index = (hs.containsKey(val + 1)) ? hs.get(val + 1) : 0; index1 = (hs.containsKey(val - 1)) ? hs.get(val - 1) : 0; index2 = (hs.containsKey(val)) ? hs.get(val) : 0; ans = ans.subtract(BigInteger.valueOf(((index + index1 + index2) * val) - ((index * (val + 1)) + (index1 * (val - 1)) + (index2 * (val))))); } out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
nlogn
903_D. Almost Difference
CODEFORCES
import java.util.HashSet; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); HashSet<Integer> set = new HashSet<>(); for(int i = 0; i<n; i++){ int a = sc.nextInt(); if(a!=0){ set.add(a); } } System.out.println(set.size()); } }
linear
992_A. Nastya and an Array
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class pr1073B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); int[] a = new int[n]; int[] b = new int[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { b[i] = Integer.parseInt(st.nextToken()); } solve(n, a, b, out); out.flush(); out.close(); } private static void solve(int n, int[] a, int[] b, PrintWriter out) { boolean[] book = new boolean[n+1]; boolean f; int j1 = 0, j2 = 0; for (int i = 0; i < n; i++) { f = false; int num = b[i]; if(!book[num]) { f = true; j1 = j2; for (;j2 < n; j2++) { book[a[j2]] = true; if (a[j2] == num) { j2++; break; } } } out.print(f ? j2-j1 + " ": 0 + " "); } } }
linear
1073_B. Vasya and Books
CODEFORCES
import java.awt.Label; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main implements Runnable { private boolean _ReadFromFile = false; private boolean _WriteToFile = false; static final String TASK_ID = "in"; static final String IN_FILE = TASK_ID + ".in"; static final String OUT_FILE = TASK_ID + ".out"; BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; private String alphabet; private void core() throws Exception { int n = nextInt(); alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int test = 0; test < n; test++) { String input = reader.readLine(); StringTokenizer st = new StringTokenizer(input, alphabet); ArrayList<Integer> have = new ArrayList<Integer>(); while (st.hasMoreElements()) { String kString = st.nextToken(); have.add(Integer.parseInt(kString)); } if (have.size() == 2) writer.println(twoInts(have.get(0), have.get(1))); else { String row = ""; int col = 0; for (int i = 0; i < input.length(); i++) { if (Character.isDigit(input.charAt(i))) { row = input.substring(0, i); col = Integer.parseInt(input.substring(i)); break; } } writer.println(oneInt(row, col)); } } } private String oneInt(String row, int col) { return "R" + col + "C" + toNum(row); } private int toNum(String row) { int res = 0; for (int i = 0; i < row.length(); i++) { res = res * 26 + row.charAt(i) - 'A' + 1; } return res; } private String twoInts(Integer row, Integer col) { return toAlpha(col) + row; } private String toAlpha(Integer col) { String res = ""; while (col > 0) { if (col % 26 > 0) { res = alphabet.charAt(col % 26 - 1) + res; col /= 26; } else { res = "Z" + res; col -= 26; col /= 26; } } return res; } void debug(Object...os) { System.out.println(Arrays.deepToString(os)); } //--------------------- IO stuffs --------------------- public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Main()); thread.start(); thread.join(); } public void run() { try { reader = _ReadFromFile ? new BufferedReader(new FileReader(IN_FILE)) : new BufferedReader(new InputStreamReader(System.in)); writer = _WriteToFile ? new PrintWriter(OUT_FILE) : new PrintWriter(new BufferedOutputStream(System.out)); tokenizer = null; core(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws Exception { return Integer.parseInt(nextToken()); } long nextLong() throws Exception { return Long.parseLong(nextToken()); } double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } String nextToken() throws Exception { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
linear
1_B. Spreadsheets
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 { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if(n%2==0){ System.out.println(4 + " " + (n-4)); } else{ int a = Math.min(9,n-9); int b = Math.max(9,n-9); System.out.println(a + " " + b); } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
// discussed with rainboy import java.io.*; import java.util.*; public class CF915D { static ArrayList[] aa; static boolean[] visited, instack; static int[] stack; static int cnt, h_, i_, j_; static boolean dfs1(int i) { if (visited[i]) { if (instack[i]) { h_ = i; return true; } return false; } visited[i] = instack[i] = true; stack[cnt++] = i; ArrayList<Integer> adj = aa[i]; for (int j : adj) if (dfs1(j)) return true; instack[i] = false; cnt--; return false; } static boolean dfs2(int i) { if (visited[i]) return instack[i]; visited[i] = instack[i] = true; ArrayList<Integer> adj = aa[i]; for (int j : adj) if (!(i == i_ && j == j_) && dfs2(j)) return true; instack[i] = false; return false; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); aa = new ArrayList[n]; for (int i = 0; i < n; i++) aa[i] = new ArrayList<Integer>(); while (m-- > 0) { st = new StringTokenizer(br.readLine()); int i = Integer.parseInt(st.nextToken()) - 1; int j = Integer.parseInt(st.nextToken()) - 1; aa[i].add(j); } visited = new boolean[n]; instack = new boolean[n]; stack = new int[n]; for (int i = 0; i < n; i++) if (dfs1(i)) break; if (cnt == 0) { System.out.println("YES"); return; } for (j_ = h_, i_ = stack[--cnt]; ; j_ = i_, i_ = stack[--cnt]) { Arrays.fill(visited, false); Arrays.fill(instack, false); boolean cycle = false; for (int i = 0; i < n; i++) if (dfs2(i)) { cycle = true; break; } if (!cycle) { System.out.println("YES"); return; } if (i_ == h_) break; } System.out.println("NO"); } }
quadratic
915_D. Almost Acyclic Graph
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main{ public static long howMany(long n, long x, long y, long s){ long res = 0; int cnt = 0; long[] px = new long[9]; long[] py = new long[9]; if(x - s < 1){ px[cnt] = 1; py[cnt++] = y-x+s+1 <= n ? y-x+s+1 : n; px[cnt] = 1; py[cnt++] = x+y-s-1 > 0? x+y-s-1: 1; res += 6; }else{ px[cnt] = x-s; py[cnt++] = y; res += 2; } if(y - s < 1){ py[cnt] = 1; px[cnt++] = x+y-s-1 > 0 ? x+y-s-1 : 1; py[cnt] = 1; px[cnt++] = x-(y-s)+1 <= n ? x-y+s+1: n; res += 6; }else{ px[cnt] = x; py[cnt++] = y-s; res += 2; } if(x + s > n){ px[cnt] = n; py[cnt++] = y-(x+s)+n > 0 ? y-(x+s)+n : 1; px[cnt] = n; py[cnt++] = x+s+y - n <= n ? x+s+y-n : n; res += 6; }else{ px[cnt] = x+s; py[cnt++] = y; res += 2; } if(y + s > n){ py[cnt] = n; px[cnt++] = x+y+s-n <= n? x+y+s-n : n; py[cnt] = n; px[cnt++] = n-(y+s-x) > 0 ? n-(y+s-x) :1; res += 6; }else{ px[cnt] = x; py[cnt++] = y+s; res += 2; } px[cnt] = px[0]; py[cnt] = py[0]; long ret = 0; long sum = 0; for(int i = 0; i < cnt; i++){ ret += px[i]*py[i+1]-py[i]*px[i+1]; sum += Math.max(Math.abs(px[i]-px[i+1]), Math.abs(py[i]-py[i+1]))+1; } return (4*ret + 4*sum - res)/8; } public static void main(String[] args) throws Exception{ BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer str = new StringTokenizer(r.readLine()); int n = Integer.parseInt(str.nextToken()); int x = Integer.parseInt(str.nextToken()); int y = Integer.parseInt(str.nextToken()); long c = Long.parseLong(str.nextToken()); if(c == 1){ System.out.println(0); return; } long high = 1; while(howMany(n, x, y, high) < c){ high <<= 1; } long low = high>>1; while(high - low > 1){ long med = (high+low)/2; if(howMany(n, x, y, med) < c){ low = med; }else{ high = med; } } System.out.println(high); } }
logn
256_B. Mr. Bender and Square
CODEFORCES