src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Locale; import java.io.OutputStream; import java.io.PrintWriter; import java.util.RandomAccess; import java.util.AbstractList; import java.io.Writer; import java.util.List; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.InputMismatchException; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Jacob Jiang */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] b = a.clone(); ArrayUtils.safeSort(b); int diff = 0; for (int i = 0; i < n; i++) { if (a[i] != b[i]) diff++; } out.println(diff <= 2 ? "YES" : "NO"); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] nextIntArray(int count) { int[] result = new int[count]; for (int i = 0; i < count; i++) { result[i] = nextInt(); } return result; } } class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(String x) { writer.println(x); } public void close() { writer.close(); } } class ArrayUtils { public static List<Integer> asList(int[] array) { return new IntList(array); } private static class IntList extends AbstractList<Integer> implements RandomAccess { int[] array; private IntList(int[] array) { this.array = array; } public Integer get(int index) { return array[index]; } public Integer set(int index, Integer element) { int result = array[index]; array[index] = element; return result; } public int size() { return array.length; } } public static void safeSort(int[] array) { Collections.shuffle(asList(array)); Arrays.sort(array); } }
nlogn
220_A. Little Elephant and 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
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.InputMismatchException; 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); Task solver = new Task(); int testCount = 1; for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class Task { int n; int[] a; int[] b; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.readInt(); a = new int[n]; b = new int[n]; for (int i = 0; i < n; ++i) a[i] = b[i] = in.readInt(); sort(0, n - 1); int different = 0; for (int i = 0; i < n; ++i) if (a[i] != b[i]) ++different; out.println(different <= 2 ? "YES" : "NO"); } public void sort(int lo, int hi) { if (lo < hi) { int mid = (lo + hi) / 2; sort(lo, mid); sort(mid + 1, hi); merge(lo, mid, hi); } } public void merge(int lo, int mid, int hi) { int n1 = mid - lo + 1; int n2 = hi - (mid + 1) + 1; int[] x = new int[n1 + 1]; int[] y = new int[n2 + 1]; for (int i = 0; i < n1; ++i) x[i] = b[lo + i]; for (int j = 0; j < n2; ++j) y[j] = b[mid + 1 + j]; x[n1] = y[n2] = Integer.MAX_VALUE; for (int k = lo, i = 0, j = 0; k <= hi; ++k) b[k] = x[i] < y[j] ? x[i++] : y[j++]; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public Long readLong() { return Long.parseLong(readString()); } public Double readDouble() { return Double.parseDouble(readString()); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.*; public class r220a { public static void main(String args[]) { Scanner in =new Scanner(System.in); int N = in.nextInt(); ArrayList<Integer> list = new ArrayList<Integer>(); ArrayList<Integer> sort = new ArrayList<Integer>(); for(int i = 0; i < N; i++) { int k = in.nextInt(); list.add(k); sort.add(k); } Collections.sort(sort); int count = 0; for(int i = 0; i < N; i++) { if(sort.get(i).intValue() != list.get(i).intValue()) count++; } if(count != 2 && count != 0) System.out.println("NO"); else System.out.println("YES"); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Random; import java.util.TreeSet; /** * Actual solution is at the top, in class Solver */ public class Main implements Runnable { private static String[] args; public static void main(String[] args) { Main.args = args; new Thread(null, new Main(), "MyRunThread", 1 << 26).start(); } @Override public void run() { long time_beg = -1; InputStream inputStream = System.in; OutputStream outputStream = System.out; if (args.length > 0 && args[0].equals("outside")) { time_beg = System.currentTimeMillis(); try { inputStream = new FileInputStream("IO/in.txt"); // outputStream = new FileOutputStream("IO/out.txt"); } catch (Exception e) { System.err.println(e); System.exit(1); } } else { try { // inputStream = new FileInputStream("file_name"); // outputStream = new FileOutputStream("file_name"); } catch (Exception e) { System.err.println(e); System.exit(1); } } Solver s = new Solver(); s.in = new InputReader(inputStream); s.out = new OutputWriter(outputStream); if (args.length > 0 && args[0].equals("outside")) { s.debug = new DebugWriter(s.out); } s.solve(); s.out.close(); if (args.length > 0 && args[0].equals("outside")) { s.debug.close(); System.err.printf("*** Total time: %.3f ***\n", (System.currentTimeMillis() - time_beg) / 1000.0); } } } final class Solver { InputReader in; OutputWriter out; DebugWriter debug; public void solve() { int n = in.readInt(); int[] mas = new int[n]; int[] sorted = new int[n]; for (int i = 0; i < n; ++i) sorted[i] = mas[i] = in.readInt(); Random rnd = new Random(System.nanoTime()); for (int i = 1; i < n; ++i) { int j = rnd.nextInt(i); int tmp = sorted[j]; sorted[j] = sorted[i]; sorted[i] = tmp; } Arrays.sort(sorted); int id1 = -1; for (int i = 0; i < n; ++i) if (mas[i] != sorted[i]) { id1 = i; break; } int id2 = -1; for (int i = n - 1; i >= 0; --i) if (mas[i] != sorted[i]) { id2 = i; break; } if (id1 != -1 && id2 != -1 && id1 != id2) { int tmp = mas[id1]; mas[id1] = mas[id2]; mas[id2] = tmp; } for (int i = 0; i < n; ++i) if (mas[i] != sorted[i]) { out.printLine("NO"); return; } out.printLine("YES"); } } class InputReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } } 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 printFormat(String format, Object... objects) { writer.printf(format, objects); } public void print(char[] objects) { writer.print(objects); } public void printLine(char[] objects) { writer.println(objects); } public void printLine(char[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void print(int[] objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(int[] objects) { print(objects); writer.println(); } public void printLine(int[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void print(long[] objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(long[] objects) { print(objects); writer.println(); } public void printLine(long[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void print(double[] objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(double[] objects) { print(objects); writer.println(); } public void printLine(double[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void print(byte[] objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(byte[] objects) { print(objects); writer.println(); } public void printLine(byte[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void print(boolean[] objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(boolean[] objects) { print(objects); writer.println(); } public void printLine(boolean[][] objects) { for (int i = 0; i < objects.length; ++i) printLine(objects[i]); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class DebugWriter { private final OutputWriter writer; public DebugWriter(OutputWriter writer) { this.writer = writer; } private void printDebugMessage() { writer.print("debug:\t"); } public void printLine(Object... objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printFormat(String format, Object... objects) { flush(); printDebugMessage(); writer.printFormat(format, objects); flush(); } public void printLine(char[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(char[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void printLine(double[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(double[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void printLine(int[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(int[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void printLine(long[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(long[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void printLine(byte[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(byte[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void printLine(boolean[] objects) { flush(); printDebugMessage(); writer.printLine(objects); flush(); } public void printLine(boolean[][] objects) { flush(); for (int i = 0; i < objects.length; ++i) printLine(objects[i]); flush(); } public void flush() { writer.flush(); } public void close() { writer.close(); } }
nlogn
220_A. Little Elephant and Problem
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.Arrays; import java.util.Scanner; public class test1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int a[]=new int[n]; int b[]=new int[n]; for(int i=0;i<n;i++) { a[i]=in.nextInt(); b[i]=a[i]; } Arrays.sort(b); int count=0; for(int i=0;i<n;i++) if(a[i]!=b[i]) count++; if(count<=2) System.out.println("YES"); else System.out.println("NO"); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Problem220A { static int[] numbers; static int[] numbersCopy; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int i = Integer.parseInt(in.readLine()); numbers = new int[i]; numbersCopy = new int[i]; StringTokenizer stringTokenizer = new StringTokenizer(in.readLine()); int numOutOfPlace = 0; for (int j = 0; j < i; j++) { numbers[j] = Integer.parseInt(stringTokenizer.nextToken()); numbersCopy[j] = numbers[j]; } Arrays.sort(numbers); for (int j = 0; j < i; j++) { if (numbers[j] != numbersCopy[j]) { numOutOfPlace++; if (numOutOfPlace > 2) { break; } } } if (numOutOfPlace == 0 || numOutOfPlace == 2) { System.out.println("YES"); } else { System.out.println("NO"); } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class LittleElephant { public static void main(String[] args){ Scanner input = new Scanner(System.in); int n = input.nextInt(); int temp; ArrayList<Integer> a2 = new ArrayList<Integer>(); ArrayList<Integer> a1 = new ArrayList<Integer>(); int count = 0; int temp1,temp2; for(int i= 0; i < n ; i++){ temp = input.nextInt(); a2.add(temp); a1.add(temp); } Collections.sort(a2); input.close(); for(int i = 0; i < n; i++){ temp1 = a2.get(i); temp2 = a1.get(i); if(temp1 != temp2){ count++; } } if(count==2 || count==0){ System.out.println("YES"); }else{ System.out.println("NO"); } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.*; import java.math.BigInteger; import static java.math.BigInteger.*; 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(); int[]b=a.clone(); 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 boolean sorted(int[] a) { for(int i=0;i+1<a.length;i++) if(a[i]>a[i+1]) return false; return true; } //////////// 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.io.*; import java.util.*; public class Main { static class Scanner { StreamTokenizer in; boolean forceMode = false; Scanner(InputStream is, String codePage, boolean forceMode) { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(is))); if (!forceMode) { in.resetSyntax(); in.wordChars(33, 255); in.whitespaceChars(0, 32); } } Scanner(InputStream is, String codePage) { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(is))); if (!forceMode) { in.resetSyntax(); in.wordChars(33, 255); in.whitespaceChars(0, 32); } } String next() { try { in.nextToken(); return in.sval; } catch (Exception e) { throw new Error(); } } int nextInt() { if (forceMode) { try { in.nextToken(); return (int) in.nval; } catch (Exception e) { throw new Error(); } } else { return Integer.parseInt(next()); } } long nextLong() { if (forceMode) { throw new Error("No long at force mod!"); } else { return Long.parseLong(next()); } } double nextDouble() { if (forceMode) { try { in.nextToken(); return in.nval; } catch (Exception e) { throw new Error(); } } else { return Double.parseDouble(next()); } } } static class Assertion { static void checkRE(boolean e) { if (!e) { throw new Error(); } } static void checkTL(boolean e) { if (!e) { int idx = 1; while (idx > 0) { idx++; } } } } Scanner in; PrintWriter out; class Int implements Comparable<Int> { int value; int pos; public Int(int value, int pos) { this.value = value; this.pos = pos; } @Override public int compareTo(Int second) { if (this.value == second.value) { return this.pos - second.pos; } else { return this.value - second.value; } } } void solve() { int n = in.nextInt(); Int ar[] = new Int[n]; for (int i = 0; i < ar.length; i++) { ar[i] = new Int(in.nextInt(), i); } Arrays.sort(ar); int cnt = 0; for (int i = 0; i < ar.length; i++) { if (ar[i].value!=ar[ar[i].pos].value) { cnt++; } } if (cnt == 2 || cnt == 0) { out.println("YES"); } else { out.println("NO"); } } final static String fileName = ""; void run() { // try { // in = new Scanner(new FileInputStream(fileName + ".in"), "ISO-8859-1"); // out = new PrintWriter(fileName + ".out", "ISO-8859-1"); // } catch (FileNotFoundException e) { // throw new Error(e); // // } catch (UnsupportedEncodingException e) { // throw new Error(e); // } in = new Scanner(System.in, ""); out = new PrintWriter(System.out); try { solve(); } catch (Exception e) { throw new Error(e); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class A { static BufferedReader in; static PrintWriter out; static StringTokenizer st; static Random rnd; void solve() throws IOException { int n = nextInt(); int[] arr = new int[n]; Integer[] arrCopy = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = arrCopy[i] = nextInt(); Arrays.sort(arrCopy); int bad = 0; for (int i = 0; i < n; i++) if (arr[i] != arrCopy[i]) ++bad; boolean fail = bad > 2; out.println(!fail ? "YES" : "NO"); } public static void main(String[] args) { new A().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); rnd = new Random(); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(42); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; /* * @author Ivan Pryvalov ([email protected]) */ public class Codeforces_R136_Div1_A implements Runnable{ private void solve() throws IOException { int n = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = scanner.nextInt(); } boolean sorted = true; for (int i = 0; i < a.length; i++) { if (!isOk(a, i)){ sorted = false; } } if (sorted){ out.println("YES"); return; } List<Integer> idx = new ArrayList<Integer>(); for(int i=0; i<n; i++){ if (!isOk(a, i)){ idx.add(i); } } if (idx.size() > 6){ out.println("NO"); return; } for(int i=0; i<idx.size(); i++){ for(int j=0; j<n; j++){ swap(a, idx.get(i), j); if (isOk(a, idx) && isOk(a, j)){ out.println("YES"); return; } swap(a, idx.get(i), j); } } out.println("NO"); } private boolean isOk(int[] a, int i) { boolean ordered = true; if (i>0 && !(a[i-1] <= a[i])){ ordered = false; } if (i<a.length-1 && !(a[i]<=a[i+1])){ ordered = false; } return ordered; } private boolean isOk(int[] a, List<Integer> idx) { for(int i : idx){ if (!isOk(a, i)) return false; } return true; } private void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } ///////////////////////////////////////////////// final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8 ; final int BUF_SIZE_INPUT = 1024; final int BUF_SIZE_OUT = 1024; boolean inputFromFile = false; String filenamePrefix = "A-small-attempt0"; String inSuffix = ".in"; String outSuffix = ".out"; //InputStream bis; //OutputStream bos; PrintStream out; ByteScanner scanner; ByteWriter writer; // @Override public void run() { try{ InputStream bis = null; OutputStream bos = null; //PrintStream out = null; if (inputFromFile){ File baseFile = new File(getClass().getResource("/").getFile()); bis = new BufferedInputStream( new FileInputStream(new File( baseFile, filenamePrefix+inSuffix)), INPUT_BUFFER_SIZE); bos = new BufferedOutputStream( new FileOutputStream( new File(baseFile, filenamePrefix+outSuffix))); out = new PrintStream(bos); }else{ bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE); bos = new BufferedOutputStream(System.out); out = new PrintStream(bos); } scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE); writer = new ByteWriter(bos, BUF_SIZE_OUT); solve(); out.flush(); }catch (Exception e) { e.printStackTrace(); System.exit(1); } } public interface Constants{ final static byte ZERO = '0';//48 or 0x30 final static byte NINE = '9'; final static byte SPACEBAR = ' '; //32 or 0x20 final static byte MINUS = '-'; //45 or 0x2d final static char FLOAT_POINT = '.'; } public static class EofException extends IOException{ } public static class ByteWriter implements Constants { int bufSize = 1024; byte[] byteBuf = new byte[bufSize]; OutputStream os; public ByteWriter(OutputStream os, int bufSize){ this.os = os; this.bufSize = bufSize; } public void writeInt(int num) throws IOException{ int byteWriteOffset = byteBuf.length; if (num==0){ byteBuf[--byteWriteOffset] = ZERO; }else{ int numAbs = Math.abs(num); while (numAbs>0){ byteBuf[--byteWriteOffset] = (byte)((numAbs % 10) + ZERO); numAbs /= 10; } if (num<0) byteBuf[--byteWriteOffset] = MINUS; } os.write(byteBuf, byteWriteOffset, byteBuf.length - byteWriteOffset); } /** * Please ensure ar.length <= byteBuf.length! * * @param ar * @throws IOException */ public void writeByteAr(byte[] ar) throws IOException{ for (int i = 0; i < ar.length; i++) { byteBuf[i] = ar[i]; } os.write(byteBuf,0,ar.length); } public void writeSpaceBar() throws IOException{ byteBuf[0] = SPACEBAR; os.write(byteBuf,0,1); } } public static class ByteScanner implements Constants{ InputStream is; public ByteScanner(InputStream is, int bufSizeInput, int bufSize){ this.is = is; this.bufSizeInput = bufSizeInput; this.bufSize = bufSize; byteBufInput = new byte[this.bufSizeInput]; byteBuf = new byte[this.bufSize]; } public ByteScanner(byte[] data){ byteBufInput = data; bufSizeInput = data.length; bufSize = data.length; byteBuf = new byte[bufSize]; byteRead = data.length; bytePos = 0; } private int bufSizeInput; private int bufSize; byte[] byteBufInput; byte by=-1; int byteRead=-1; int bytePos=-1; byte[] byteBuf; int totalBytes; boolean eofMet = false; private byte nextByte() throws IOException{ if (bytePos<0 || bytePos>=byteRead){ byteRead = is==null? -1: is.read(byteBufInput); bytePos=0; if (byteRead<0){ byteBufInput[bytePos]=-1;//!!! if (eofMet) throw new EofException(); eofMet = true; } } return byteBufInput[bytePos++]; } /** * Returns next meaningful character as a byte.<br> * * @return * @throws IOException */ public byte nextChar() throws IOException{ while ((by=nextByte())<=0x20); return by; } /** * Returns next meaningful character OR space as a byte.<br> * * @return * @throws IOException */ public byte nextCharOrSpacebar() throws IOException{ while ((by=nextByte())<0x20); return by; } /** * Reads line. * * @return * @throws IOException */ public String nextLine() throws IOException { readToken((byte)0x20); return new String(byteBuf,0,totalBytes); } public byte[] nextLineAsArray() throws IOException { readToken((byte)0x20); byte[] out = new byte[totalBytes]; System.arraycopy(byteBuf, 0, out, 0, totalBytes); return out; } /** * Reads token. Spacebar is separator char. * * @return * @throws IOException */ public String nextToken() throws IOException { readToken((byte)0x21); return new String(byteBuf,0,totalBytes); } /** * Spacebar is included as separator char * * @throws IOException */ private void readToken() throws IOException { readToken((byte)0x21); } private void readToken(byte acceptFrom) throws IOException { totalBytes = 0; while ((by=nextByte())<acceptFrom); byteBuf[totalBytes++] = by; while ((by=nextByte())>=acceptFrom){ byteBuf[totalBytes++] = by; } } public int nextInt() throws IOException{ readToken(); int num=0, i=0; boolean sign=false; if (byteBuf[i]==MINUS){ sign = true; i++; } for (; i<totalBytes; i++){ num*=10; num+=byteBuf[i]-ZERO; } return sign?-num:num; } public long nextLong() throws IOException{ readToken(); long num=0; int i=0; boolean sign=false; if (byteBuf[i]==MINUS){ sign = true; i++; } for (; i<totalBytes; i++){ num*=10; num+=byteBuf[i]-ZERO; } return sign?-num:num; } /* //TODO test Unix/Windows formats public void toNextLine() throws IOException{ while ((ch=nextChar())!='\n'); } */ public double nextDouble() throws IOException{ readToken(); char[] token = new char[totalBytes]; for (int i = 0; i < totalBytes; i++) { token[i] = (char)byteBuf[i]; } return Double.parseDouble(new String(token)); } } public static void main(String[] args) { new Codeforces_R136_Div1_A().run(); } }
nlogn
220_A. Little Elephant and Problem
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.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Sunits789 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n=in.nextInt(); int arr[]=new int[n]; in.getArray(arr); int arrc[]=new int[n]; for(int i=0;i<n;i++){ arrc[i]=arr[i]; } Library.sort(arrc); int c=0; for(int i=0;i<n;i++){ if(arrc[i]!=arr[i]){ c++; } } if(c>2){ out.println("NO"); } else{ out.println("YES"); } } } 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()); } public void getArray(int arr[]){ for(int i=0;i<arr.length;i++){ arr[i]=nextInt(); } } } class Library{ public static void sort(int n[]){ int len=n.length; int l1=len/2; int l2=len-l1; int n1[]=new int[l1]; int n2[]=new int[l2]; for(int i=0;i<l1;i++){ n1[i]=n[i]; } for(int i=0;i<l2;i++){ n2[i]=n[i+l1]; } if(l1!=0){ sort(n1); sort(n2); } int ind1=0; int ind2=0; int ind=0; for(int i=0;i<len&&ind1<l1&&ind2<l2;i++){ if(n1[ind1]<n2[ind2]){ n[i]=n1[ind1]; ind1++; } else{ n[i]=n2[ind2]; ind2++; } ind++; } if(ind1<l1){ for(int i=ind1;i<l1;i++){ n[ind]=n1[i]; ind++; } } if(ind2<l2){ for(int i=ind2;i<l2;i++){ n[ind]=n2[i]; ind++; } } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class A { BufferedReader br; StringTokenizer st; PrintWriter out; void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } int[] b = a.clone(); Arrays.sort(b); int k = 0; for (int i = 0; i < n; i++) { if (a[i] != b[i]) { k++; } } if (k <= 2) { out.println("YES"); } else { out.println("NO"); } } void run() { try { // br = new BufferedReader(new FileReader("G.in")); // out = new PrintWriter("G.out"); br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new A().run(); } public String nextToken() throws IOException { while ((st == null) || (!st.hasMoreTokens())) st = new StringTokenizer(br.readLine()); return st.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()); } }
nlogn
220_A. Little Elephant and Problem
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(); int[]b=a.clone(); mySort(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
//package round136; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; public class A2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = new int[n]; int[] b = new int[n]; for(int i = 0;i < n;i++)b[i] = a[i] = ni(); b = radixSort(b); int ct = 0; for(int i = 0;i < n;i++){ if(a[i] != b[i])ct++; } if(ct <= 2){ out.println("YES"); }else{ out.println("NO"); } } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i]; int[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A2().run(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { Scanner in; static PrintWriter out; static class Scanner { StreamTokenizer in; Scanner(InputStream is) { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(is))); in.resetSyntax(); in.whitespaceChars(0, 32); in.wordChars(33, 255); } int nextInt() { try { in.nextToken(); return Integer.parseInt(in.sval); } catch (IOException e) { throw new Error(); } } String next() { try { in.nextToken(); return in.sval; } catch (IOException e) { throw new Error(); } } } static class Value implements Comparable <Value> { int x; int pos; Value(int x, int pos) { this.x = x; this.pos = pos; } public int compareTo(Value second) { if (this.x == second.x) { return this.pos - second.pos; } else { return this.x - second.x; } } } void solve() { int n = in.nextInt(); Value ar[] = new Value[n]; for (int i = 0; i < n; i++) { ar[i] = new Value(in.nextInt(), i); } Arrays.sort(ar); int cnt = 0; //LinkedList <Integer> gavno = new LinkedList<Integer>(); for (int i = 0; i < n; i++) { if (ar[i].pos != i && ar[ar[i].pos].x != ar[i].x) { cnt++; //gavno.add(i); } } if (cnt > 2) { out.println("NO"); } else { out.println("YES"); } } static void asserT(boolean e) { if (!e) { throw new Error(); } } public void run() { in = new Scanner(System.in); out = new PrintWriter(System.out); try { solve(); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.*; import java.io.*; import java.awt.Point; import static java.lang.Math.*; public class CF220A { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); StringTokenizer st = new StringTokenizer(in.readLine()); int[] A = new int[n]; Integer[] B = new Integer[n]; for(int i=0; i<n; i++) { A[i] = Integer.parseInt(st.nextToken()); B[i] = A[i]; } Collections.sort(Arrays.asList(B)); int cnt = 0; for(int i=0; i<n; i++) if(A[i] != B[i]) cnt++; System.out.println(cnt <= 2 ? "YES" : "NO"); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.Scanner; /** * User: serparamon */ public class Codeforces_2012_08_31_A { public static void main(String[] args) throws IOException { //Scanner in = new Scanner(System.in); StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(System.out); in.nextToken(); int n = (int) in.nval; int[] a = new int[n]; for (int i=0; i<n; i++) { in.nextToken(); a[i] = (int) in.nval; } int[] b = Arrays.copyOf(a, n); Arrays.sort(a); int k = 0; for (int i=0; i<n; i++) { if (a[i] != b[i]) k++; } if (k==0 || k==2) out.println("YES"); else out.println("NO"); out.flush(); out.close(); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static int n; static long TotalTime; static Problem[] problems; static StringBuilder sb; public static void main(String[] args) { FastScanner sc = new FastScanner(); sb = new StringBuilder(); n = sc.nextInt(); TotalTime = sc.nextLong(); problems = new Problem[n]; for (int i = 0; i < n; i++) { problems[i] = new Problem (sc.nextInt(), sc.nextLong(), i); } Arrays.sort(problems); long num = -1; long high = n; long low = 0; int iter = 0; while (high - low > 1) { num = (high + low) / 2; if (test(num, false)) { low = num; } else { high = num; } } if (test(high, false)) num = high; else num = low; test(num, true); System.out.print(sb); } public static boolean test (long num, boolean print) { int count = 0; long sum = 0L; if (print) sb.append(num + "\n" + num + "\n"); for (int i = 0; i < n && count < num; i++) { if (problems[i].a >= num) { count++; sum += problems[i].t; if (print) sb.append((problems[i].index + 1) + " "); } } return (count == num) && (sum <= TotalTime); } public static class Problem implements Comparable<Problem> { int a; long t; int index; public int compareTo(Problem o) { return Long.compare(t, o.t); } public Problem (int a, long t, int index) { this.a = a; this.t = t; this.index = index; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
nlogn
913_D. Too Easy Problems
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Andy Phan */ public class p1096f { static long MOD = 998244353; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); BIT invert = new BIT(n+5); BIT neg = new BIT(n+5); long res = 0; int[] arr = new int[n]; boolean[] has = new boolean[n+1]; long num1 = 0; for(int i = 0; i < n; i++) { arr[i] = in.nextInt(); if(arr[i] != -1) { res += invert.read(n+5)-invert.read(arr[i]); res %= MOD; invert.update(arr[i], 1); has[arr[i]] = true; } else num1++; } if(num1 == 0) { System.out.println(res); return; } for(int i = 1; i <= n; i++) if(!has[i]) neg.update(i, 1); long invertNum1 = modInv(num1, MOD); res += ((num1*(num1-1))%MOD)*modInv(4, MOD); res %= MOD; long cnt = 0; for(int i = 0; i < n; i++) { if(arr[i] == -1) { cnt++; continue; } res += (((neg.read(n+5)-neg.read(arr[i]))*cnt)%MOD)*invertNum1; res %= MOD; } cnt = 0; for(int i = n-1; i >= 0; i--) { if(arr[i] == -1) { cnt++; continue; } res += (((neg.read(arr[i]))*cnt)%MOD)*invertNum1; res %= MOD; } System.out.println(res); } //@ static class BIT { int n; int[] tree; public BIT(int n) { this.n = n; tree = new int[n + 1]; } int read(int i) { int sum = 0; while (i > 0) { sum += tree[i]; i -= i & -i; } return sum; } void update(int i, int val) { while (i <= n) { tree[i] += val; i += i & -i; } } //$ } //@ // Computes the modular inverse of x // Returns 0 if the GCD of x and mod is not 1 // O(log n) : Can be converted to use BigIntegers static long modInv(long x, long mod) { return (BigInteger.valueOf(x).modInverse(BigInteger.valueOf(mod))).longValue(); } static long modInv(long a, long b, long y0, long y1, long q0, long q1) { long y2 = y0 - y1*q0; return b == 0 ? y2 : modInv(b, a % b, y1, y2, q1, a / b); } //@ static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a / gcd(a, b) * b; } }
nlogn
1096_F. Inversion Expectation
CODEFORCES
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args){ try { new Main().solve(); } catch (Exception e) { e.printStackTrace(); } } ArrayList<Edge>[]edge; int n,m,cnt=0; int ord; int[]order;int[]vis; Edge[] e; private void solve() throws Exception{ InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); n=in.nextInt();m=in.nextInt(); edge=new ArrayList[n+1]; e=new Edge[m]; vis=new int[n+1]; order=new int[n+1]; for(int i=1;i<=n;i++){ edge[i]=new ArrayList<>(); } for(int i=1;i<=m;i++){ int s=in.nextInt(),t=in.nextInt(),c=in.nextInt(); edge[s].add(new Edge(s,t,c,i)); } int l=0,r=1000000000; while (l<r){ int mid=(l+r)>>>1; if(judge(mid,false))r=mid; else l=mid+1; } out.print(l+" "); judge(l,true); Arrays.sort(e,0,cnt,Comparator.comparingInt(x->x.id)); int ans=0; int[]a=new int[m]; for(int i=0;i<cnt;i++){ if(order[e[i].s]<order[e[i].t])a[ans++]=e[i].id; } out.println(ans); for(int i=0;i<ans;i++){ out.print(a[i]+" "); } out.println(); out.flush(); } boolean judge(int min,boolean mod){ Arrays.fill(vis,0); cycle=false; for(int i=1;i<=n;i++){ if(vis[i]==0){ dfs(i,min,mod); if(cycle)return false; } } return true; } boolean cycle=false; void dfs(int cur,int min,boolean mod){ if(cycle)return; vis[cur]=1; for(Edge e:edge[cur]){ if(e.c<=min){ if(mod)this.e[cnt++]=e; continue; } if(vis[e.t]==1){ cycle=true;return; } else if(vis[e.t]==0)dfs(e.t,min,mod); } vis[cur]=2; if(mod)order[cur]=ord++; } } class Edge{ int s,t,c,id; Edge(int a,int b,int c,int d){ s=a;t=b;this.c=c;id=d; } } class InputReader{ StreamTokenizer tokenizer; public InputReader(InputStream stream){ tokenizer=new StreamTokenizer(new BufferedReader(new InputStreamReader(stream))); tokenizer.ordinaryChars(33,126); tokenizer.wordChars(33,126); } public String next() throws IOException { tokenizer.nextToken(); return tokenizer.sval; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public boolean hasNext() throws IOException { int res=tokenizer.nextToken(); tokenizer.pushBack(); return res!=tokenizer.TT_EOF; } }
nlogn
1100_E. Andrew and Taxi
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Map; import java.util.HashMap; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ReaderFastIO in = new ReaderFastIO(inputStream); PrintWriter out = new PrintWriter(outputStream); DConcatenatedMultiples solver = new DConcatenatedMultiples(); solver.solve(1, in, out); out.close(); } static class DConcatenatedMultiples { public void solve(int testNumber, ReaderFastIO in, PrintWriter out) { Map<Integer, Integer>[] mapMods = new HashMap[11]; int n = in.nextInt(); int k = in.nextInt(); int[] a = in.readArrayInt(n); for (int i = 0; i < 11; i++) { mapMods[i] = new HashMap<>(); } for (int i = 0; i < n; i++) { int pot = getPot(a[i]); mapMods[pot].put(a[i] % k, mapMods[pot].getOrDefault(a[i] % k, 0) + 1); } long ct = 0; for (int i = 0; i < n; i++) { int ownPot = getPot(a[i]); long suffix = a[i] * 10L; for (int j = 1; j <= 10; j++) { int mod = (int) (suffix % k); int comMod = (k - mod) % k; int qt = mapMods[j].getOrDefault(comMod, 0); if (j == ownPot && (a[i] % k) == comMod) { qt--; } ct += qt; suffix = (suffix * 10L) % k; } } out.println(ct); } public int getPot(int x) { int ct = 0; while (x != 0) { x /= 10; ct++; } return ct; } } static class ReaderFastIO { BufferedReader br; StringTokenizer st; public ReaderFastIO() { br = new BufferedReader(new InputStreamReader(System.in)); } public ReaderFastIO(InputStream input) { br = new BufferedReader(new InputStreamReader(input)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] readArrayInt(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } } }
nlogn
1029_D. Concatenated Multiples
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); long dest = sc.nextLong(); long max = (long)N * ((long)N + 1L) / 2L; if (dest < 2 * N - 1 || dest > max) { out.println("No"); out.close(); return; } int[] d = new int[N + 1]; int[] f = new int[N + 1]; int K = 1; for (; K <= N; K++) { long dep = 1L, cnt = 1L, c = 1L; long t = 1L; while (cnt < N) { c = c * K; dep++; t += (dep * Math.min(c, N - cnt)); cnt += c; } if (t <= dest) break; } out.println("Yes"); int dep = 1; long cnt = 1L, c = 1L; long t = 1L; d[1] = 1; while (cnt < N) { dep++; c = c * K; long x = (long)N - cnt; int min; if (c >= x) min = (int)x; else min = (int)c; d[dep] = min; t += (dep * Math.min(c, (long)N - cnt)); cnt += c; } dest -= t; int curDep = dep; int nextDep = dep + 1; while (dest > 0) { if (d[curDep] <= 1) curDep--; d[curDep]--; long next = Math.min(nextDep++, dest + curDep); dest -= ((int)next - curDep); d[(int)next]++; } int first = 1; for (int i = 2; i < nextDep; i++) { int p = 0, fn = first - d[i - 1] + 1; for (int j = first + 1; j <= first + d[i]; j++) { if (p == K) { fn++; p = 0; } p++; f[j] = fn; } first += d[i]; } for (int i = 2; i <= N; i++) out.format("%d ", f[i]); out.close(); } static class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } /* public double nextDouble() { return Double.parseDouble(next()); } 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; }*/ } }
nlogn
1098_C. Construct a tree
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] arr = new int[n]; HashMap<Integer, Integer> map = new HashMap<>(); StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { int x = Integer.parseInt(st.nextToken()); arr[i] = x; if (!map.containsKey(x)) { map.put(x, 1); } else { map.replace(x, map.get(x) + 1); } } int[] power = new int[31]; for (int i = 0; i < 31; i++) { power[i] = 1 << i; // 0 100=4 1000=8 10000=16 } int c = 0; for (int i = 0; i < n; i++) { boolean f = false; for (int j = 0; j <= 30; j++) { int check = power[j] - arr[i]; if ((map.containsKey(check) && check != arr[i])) { f = true; break;} if((map.containsKey(check) && check == arr[i] && map.get(check) >=2)) { f = true; break; } } if (!f) { c++; } } System.out.println(c); } }
nlogn
1005_C. Summarize to the Power of Two
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class pr988B { 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()); ArrayList<String> a = new ArrayList<>(); for (int i = 0; i < n; i++) { a.add(br.readLine()); } if(solve(n, a)){ out.println("YES"); for (String s : a) { out.println(s); } } else out.println("NO"); out.flush(); out.close(); } private static boolean solve(int n, ArrayList<String> a) { a.sort(Comparator.comparingInt(String::length)); for (int i = 0; i < n - 1; i++) { if(!a.get(i+1).contains(a.get(i))) return false; } return true; } }
nlogn
988_B. Substrings Sort
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main { static int[] a; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); a = sc.nextIntArray(n); long inversions = divide(0, n - 1); // out.println(inversions); // System.err.println(Arrays.toString(a)); if (n == 5) out.println("Petr"); else { if (n % 2 == 0) out.println(inversions % 2 == 0 ? "Petr" : "Um_nik"); else out.println(inversions % 2 != 0 ? "Petr" : "Um_nik"); } out.flush(); out.close(); } static long divide(int b, int e) { if (b == e) return 0; long cnt = 0; int mid = b + e >> 1; cnt += divide(b, mid); cnt += divide(mid + 1, e); cnt += merge(b, mid, e); return cnt; } static long merge(int b, int mid, int e) { long cnt = 0; int len = e - b + 1; int[] tmp = new int[len]; int i = b, j = mid + 1; for (int k = 0; k < len; k++) { if (i == mid + 1 || (j != e + 1 && a[i] > a[j])) { tmp[k] = a[j++]; cnt += (mid + 1 - i); } else tmp[k] = a[i++]; } for (int k = 0; k < len; k++) a[b + k] = tmp[k]; return cnt; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
nlogn
986_B. Petr and Permutations
CODEFORCES
import java.io.*; import java.util.*; public class Solution { static class Data{ int x,i; Data(int x,int i){ this.x = x; this.i = i; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s = br.readLine().split("\\s"); int N = Integer.parseInt(s[0]); int K = Integer.parseInt(s[1]); s = br.readLine().split("\\s"); int[] arr = new int[N]; for(int i=0;i<N;++i) arr[i] = Integer.parseInt(s[i]); solve(N,K,arr); } private static void solve(int N,int K,int[] arr){ PriorityQueue<Data> pq = new PriorityQueue<Data>(2000,(a,b) -> a.x - b.x == 0 ? b.i - a.i : b.x - a.x); for(int i=0;i<arr.length;++i){ pq.offer(new Data(arr[i],i)); } int tot_sum = 0; List<Integer> ls = new ArrayList<>(); Set<Integer> set = new HashSet<>(); for(int i=1;i<=K;++i){ Data t = pq.poll(); tot_sum += t.x; set.add(t.i); } int last = -1; for(int i =0;i<arr.length;++i){ if(set.contains(i)){ K--; //System.out.println(i); if(K == 0) ls.add(arr.length-last-1); else ls.add(i-last); last = i; } } System.out.println(tot_sum); int size = ls.size(); for(int i=0;i<size;++i){ System.out.print(ls.get(i) + " "); } } }
nlogn
1006_B. Polycarp's Practice
CODEFORCES
import java.util.*; import java.io.*; public class D { static final boolean stdin = true; static final String filename = ""; static FastScanner br; static PrintWriter pw; public static void main(String[] args) throws IOException { if (stdin) { br = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); } else { br = new FastScanner(filename + ".in"); pw = new PrintWriter(new FileWriter(filename + ".out")); } Solver solver = new Solver(); solver.solve(br, pw); } static class Solver { static long mod = (long) (1e10); public void solve(FastScanner br, PrintWriter pw) throws IOException { int n = br.ni(); Integer[] in = br.nIa(n); TreeSet<Integer> ts = new TreeSet<Integer>(); for (int i = 0; i < n; i++) { ts.add(in[i]); } String twoSol = ""; for (int i = 0; i <= 30; i++) { for (int j : in) { if (ts.contains(j + (int) Math.pow(2, i))) { if (ts.contains(j - (int) Math.pow(2, i))) { pw.println(3); pw.println(j + " " + (j + (int) Math.pow(2, i)) + " " + (j - (int) Math.pow(2, i))); pw.close(); System.exit(0); }else{ twoSol = (j + " " + (j + (int) Math.pow(2, i))); } } } } if (twoSol.isEmpty()) { pw.println(1); pw.println(in[0]); } else { pw.println(2); pw.println(twoSol); } pw.close(); } static long gcd(long a, long b) { if (a > b) return gcd(b, a); if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long pow(long a, long b) { if (b == 0) return 1L; long val = pow(a, b / 2); if (b % 2 == 0) return val * val % mod; else return val * val % mod * a % mod; } } static class Point implements Comparable<Point> { int a; int b; Point(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Point o) { return this.a - o.a; } } 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)); } ArrayList<Integer>[] ng(int n, int e) { ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<Integer>(); } for (int i = 0; i < e; i++) { int a = ni() - 1; int b = ni() - 1; adj[a].add(b); adj[b].add(a); } return adj; } Integer[] nIa(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } int[] nia(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } Long[] nLa(int n) { Long[] arr = new Long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } long[] nla(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } String[] nsa(int n) { String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = nt(); } return arr; } String nt() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(nt()); } long nl() { return Long.parseLong(nt()); } double nd() { return Double.parseDouble(nt()); } } }
nlogn
988_D. Points and Powers of Two
CODEFORCES
import java.util.*; import java.io.*; public class Chores { public static void main(String args[])throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String[] line = br.readLine().split("\\W"); int n = Integer.parseInt(line[0]); int a = Integer.parseInt(line[1]); int b = Integer.parseInt(line[2]); int[] num = new int[n]; line = br.readLine().split("\\W"); for(int i=0;i<n;i++) num[i] = Integer.parseInt(line[i]); Arrays.sort(num); System.out.println(num[b]-num[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { A problem = new A(); problem.solve(); } private void solve() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int p = sc.nextInt(); int v = sc.nextInt(); long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextLong(); } long aux; for(int i = 0; i < n -1; i++){ for(int j = i + 1; j < n; j++){ if((a[i]) > (a[j])){ aux = a[j]; a[j] = a[i]; a[i] = aux; } } } System.out.println(a[v]-a[v-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class A { /** * @param args */ public static void main(String[] args) { HomeWorks hw = new HomeWorks(); hw.sol(); hw.print(); } } class HomeWorks { HomeWorks(){ Scanner scr = new Scanner(System.in); n = scr.nextInt(); a = scr.nextInt(); b = scr.nextInt(); h = new int[n]; for (int i = 0; i < n; i++){ h[i] = scr.nextInt(); } scr.close(); } void sol() { Arrays.sort(h); int Vasya = h[b-1]; int Petya = h[b]; ans = Petya - Vasya; if (ans < 0){ ans = 0; } } void print(){ PrintWriter pw = new PrintWriter(System.out); pw.println(ans); pw.flush(); pw.close(); } int ans; int[] h; int n; int a; int b; }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class A { public static void main(String[] args) throws Exception { int n = nextInt(), b = nextInt(), a = nextInt(); int[] mas = new int[n]; for(int i = 0; i<n; i++) { mas[i] = nextInt(); } Arrays.sort(mas); if(mas[a - 1] == mas[a]) { exit(0); } println(mas[a] - mas[a-1]); } ///////////////////////////////////////////////////////////////// // IO ///////////////////////////////////////////////////////////////// private static StreamTokenizer in; private static PrintWriter out; private static BufferedReader inB; private static boolean FILE=false; private static int nextInt() throws Exception{ in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception{ in.nextToken(); return in.sval; } static{ try { out = new PrintWriter(FILE ? (new FileOutputStream("output.txt")) : System.out); inB = new BufferedReader(new InputStreamReader(FILE ? new FileInputStream("input.txt") : System.in)); } catch(Exception e) {e.printStackTrace();} in = new StreamTokenizer(inB); } ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // pre - written ///////////////////////////////////////////////////////////////// private static void println(Object o) throws Exception { out.println(o); out.flush(); } private static void exit(Object o) throws Exception { println(o); exit(); } private static void exit() { System.exit(0); } private static final int INF = Integer.MAX_VALUE; private static final int MINF = Integer.MIN_VALUE; ////////////////////////////////////////////////////////////////// }
nlogn
169_A. Chores
CODEFORCES
/** * Write a description of class VK2A here. * * @author (your name) * @version (a version number or a date) */ import java.util.*; public class VK2A { public static void main(String args[]) { Scanner S = new Scanner(System.in); int n = S.nextInt(); int a = S.nextInt(); int b = S.nextInt(); int[] A = new int[n]; for(int i = 0; i < n; i++) A[i] = S.nextInt(); for(int i = 0; i < n; i++) for(int j = 0; j < n - i - 1; j++) { if(A[j] < A[j + 1]) { int temp = A[j]; A[j] = A[j + 1]; A[j + 1] = temp; } } System.out.println(A[a - 1] - A[a]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class A { private void solve() throws IOException { int n = nextInt(); int a = nextInt(); int b = nextInt(); int[] h = new int[n]; for (int i = 0; i < n; i++) h[i] = nextInt(); Arrays.sort(h); int fstB = h[h.length - a]; int lstA = h[h.length - a - 1]; pl((fstB - lstA) > 0 ? (fstB - lstA) : 0); } 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
169_A. Chores
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String [] args){ Scanner in= new Scanner(System.in); int n=in.nextInt(); int a=in.nextInt(); int b=in.nextInt(); int []deals=new int[n]; for(int i=0; i<n; i++){ deals[i]=in.nextInt(); } Arrays.sort(deals); System.out.println(deals[b]-deals[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); int mod=1000000007; String[] input=in.readLine().split(" "); int n=Integer.parseInt(input[0]); int a=Integer.parseInt(input[1]); int b=Integer.parseInt(input[2]); String[] h=in.readLine().split(" "); int[] mas=new int[n]; for(int i=0; i<n; i++){ mas[i]=Integer.parseInt(h[i]); } Arrays.sort(mas); int l=mas[b-1]; int r=mas[b]; int count=0; if(l==r) count=0; else count=r-l; out.println(count); out.close(); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class VKRound2Div2Task1 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); String[] strs = str.split(" "); int n = Integer.parseInt(strs[0]); int a = Integer.parseInt(strs[1]); int b = Integer.parseInt(strs[2]); str = br.readLine(); String[] hs = str.split(" "); int[] h = new int[hs.length]; for(int i=0;i<hs.length;i++){ h[i] = Integer.parseInt(hs[i]); } Arrays.sort(h); if(h[b-1]==h[b]){ System.out.println(0); }else{ System.out.println(h[b]-h[b-1]); } } }
nlogn
169_A. Chores
CODEFORCES
import java.util.*; // VK Cup 2012 Round2 Unofficial Div2 Edition public class Main { void A(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int[] h = new int[n]; for(int i=0; i<n; i++){ h[i] = sc.nextInt(); } Arrays.sort(h); System.out.println(h[b]-h[b-1]); } public static void main(String[] args) { new Main().A(); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class r114 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); ArrayList<Integer> l = new ArrayList<Integer>(); for (int i = 0 ; i < n; i++) { l.add(sc.nextInt()); } Collections.sort(l); int pet = l.get(n - a); int vas = l.get(b - 1); if (pet <= vas) { System.out.println(0); } else System.out.println(pet - vas); sc.close(); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.Arrays; public class Main{ public static void main(String[] args) throws Exception { int n = nextInt(); int a = nextInt(); int b = nextInt(); int[] tasks = new int[n]; for(int i = 0; i < n; i++){ tasks[i] = nextInt(); } Arrays.sort(tasks); exit(tasks[b] - tasks[b-1]); } private static PrintWriter out; private static BufferedReader inB; private static boolean FILE = false; static { try { out = new PrintWriter(FILE ? (new FileOutputStream("output.txt")) : System.out); inB = new BufferedReader(new InputStreamReader(FILE ? new FileInputStream("input.txt") : System.in)); } catch(Exception e) {e.printStackTrace();} } private static StreamTokenizer in = new StreamTokenizer(inB); private static void exit(Object o) throws Exception { out.println(o); out.flush(); System.exit(0); } private static void println(Object o) throws Exception{ out.println(o); out.flush(); } private static void print(Object o) throws Exception{ out.print(o); out.flush(); } private static int nextInt() throws Exception { in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Success { /** * @param args */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int a = scan.nextInt(); int b=scan.nextInt(); int[] t=new int[n]; for(int i=0;i<n;i++) { t[i]=scan.nextInt(); } Arrays.sort(t); System.out.println(t[b]-t[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.*; public class test { public static void main(String[] args) { new test().run(); } PrintWriter out = null; void run() { Scanner in = new Scanner(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int[] h = new int[n]; for (int i = 0; i < n; i++) h[i] = in.nextInt(); Arrays.sort(h); if (h[b] == h[b - 1]) out.println(0); else out.println(h[b] - h[b - 1]); out.close(); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Arrays; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: Михаил * Date: 25.03.12 * Time: 19:03 * To change this template use File | Settings | File Templates. */ public class ProblemOne { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); int problemCount = scanner.nextInt(); int petrCount = scanner.nextInt(); int vasCount = scanner.nextInt(); int [] problems = new int[problemCount]; for (int i = 0; i < problemCount; i++) { problems[i] = scanner.nextInt(); } Arrays.sort(problems); System.out.println(-problems[vasCount - 1] + problems[vasCount]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: Mirza * Date: 25.03.12 * Time: 18:51 * To change this template use File | Settings | File Templates. */ public class main { static Scanner in; static int next() throws Exception {return in.nextInt();}; //static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} // static BufferedReader in; static PrintWriter out; public static void main(String[] args) throws Exception { in = new Scanner(System.in); // in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = next(); int a = next(); int b = next(); int k = 0; int i; int[] ar = new int[n]; for(i=0;i<n;i++) ar[i]=next(); Arrays.sort(ar); k = ar[n-a]-ar[b-1]; if(k<0) out.print(0); else out.print(k); out.close(); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int[] h = new int[n]; for (int i = 0; i < n; i++) h[i] = sc.nextInt(); Arrays.sort(h); pw.print(h[b]-h[b-1]); pw.close(); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.util.Arrays; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author hheng */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int[] chores = new int[n]; for (int i=0; i<n; i++) chores[i] = in.nextInt(); Arrays.sort(chores); out.println(chores[b]-chores[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.*; public class Contest169ProblemA implements Runnable { void solve() throws NumberFormatException, IOException { int n = nextInt(), a = nextInt(), b = nextInt(); ArrayList<Integer> tasks= new ArrayList<Integer>(); for (int i = 0; i < n; ++i){ tasks.add(nextInt()); } Collections.sort(tasks); int l1 = tasks.get(b-1); int l2 = tasks.get(b); if (l2 - l1 >= 0){ out.print(l2-l1); } else { out.print(l2-l1); } } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) { new Thread(new Contest169ProblemA()).start(); } public void run() { try { if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new FileReader("input.txt")); } out = new PrintWriter(System.out); solve(); } catch (Exception e) { e.printStackTrace(); System.out.print(e); System.exit(9000); } finally { out.flush(); out.close(); } } //Получаем следующий токен String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[]parts = br.readLine().split("\\s+"); int n = Integer.parseInt(parts[0]); int a = Integer.parseInt(parts[1]); int b = Integer.parseInt(parts[2]); parts = br.readLine().split("\\s+"); int[]hard = new int[n]; for(int i = 0; i < n; i++){ hard[i] = Integer.parseInt(parts[i]); } Arrays.sort(hard); System.out.println(hard[b]-hard[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class A { int INF = 1 << 28; void run() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); long[] chores = new long[n]; for(int i=0;i<n;i++) chores[i] = sc.nextLong(); sort(chores); System.out.println(chores[b]-chores[b-1]); } public static void main(String[] args) { new A().run(); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.*; /** * @author Vaibhav Mittal */ public class Main { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int testCases = 1; Task solver = new Task(); for (int i = 1; i <= testCases; ++i) solver.solve(in, out); out.close(); } } class Task { public void solve(Scanner in, PrintWriter out) { int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int[] complexity = new int[n]; for (int i = 0; i < n; ++i) complexity[i] = in.nextInt(); Arrays.sort(complexity); out.println(complexity[b] - complexity[b - 1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int[] h = new int[3000]; for(int i = 0; i<n; i++) h[i] = in.nextInt(); int l = 0, r = 1000000000, m = 0; int ansl = 0, ansr = 0; while(l<=r){ m = (l+r)/2; int ca=0; for(int i = 0;i<n;i++) if (h[i]>m) ca++; if (ca == a) ansl=m; if (ca <= a) r=m-1; else l=m+1; } l = 0; r = 1000000000; while(l<=r){ m = (l+r)/2; int ca=0; for(int i = 0;i<n;i++) if (h[i]>m) ca++; if (ca == a) ansr=m; if (ca < a) r=m-1; else l=m+1; } if (ansl == 0 || ansr==0) System.out.print(0); else System.out.print(ansr-ansl+1); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { //<editor-fold desc="input parse" defaultstate="collapsed"> private static StringTokenizer st; private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static long nextLong() { return Long.parseLong(st.nextToken()); } private static int nextInt() { return Integer.parseInt(st.nextToken()); } private static double nextDouble() { return Double.parseDouble(st.nextToken()); } private static short nextShort() { return Short.parseShort(st.nextToken()); } private static byte nextByte() { return Byte.parseByte(st.nextToken()); } private static void initTokenizer() throws Exception { st = new StringTokenizer(reader.readLine()); } //</editor-fold> public static void main(String[] args) throws Exception { initTokenizer(); int n = nextInt(); int a = nextInt(); int b = nextInt(); int[] h = new int[n]; initTokenizer(); for (int i = 0; i < n; i++) { h[i] = nextInt(); } Arrays.sort(h); System.out.print(h[b] - h[b - 1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()), a = Integer.parseInt(st.nextToken()), b = Integer.parseInt(st.nextToken()); st = new StringTokenizer(in.readLine()); ArrayList<Integer> A = new ArrayList<Integer>(); for (int i = 0 ; i < n ; i++) { A.add(Integer.parseInt(st.nextToken())); } Collections.sort(A); System.out.println(A.get(b) - A.get(b - 1)); } }
nlogn
169_A. Chores
CODEFORCES
import java.awt.Point; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Start { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } public static void main(String[] args) { new Start().run(); } public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int levtIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (levtIndex < rightIndex) { if (rightIndex - levtIndex <= MAGIC_VALUE) { insertionSort(a, levtIndex, rightIndex); } else { int middleIndex = (levtIndex + rightIndex) / 2; mergeSort(a, levtIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, levtIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int levtIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - levtIndex + 1; int length2 = rightIndex - middleIndex; int[] levtArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, levtIndex, levtArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = levtIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = levtArray[i++]; } else { a[k] = levtArray[i] <= rightArray[j] ? levtArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int levtIndex, int rightIndex) { for (int i = levtIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= levtIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } class LoL implements Comparable<LoL> { int x; int y; public LoL(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(LoL arg0) { if (arg0.x == x) { return y - arg0.y; } return arg0.x - x; } } public void solve() throws IOException { int n = readInt(); int a = readInt()-1; int b = readInt()-1; int [] d = new int [n]; for (int i = 0; i <n; i++){ d[i] = readInt(); } mergeSort(d); out.print(d[b+1]-d[b]); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.util.Arrays; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author codeKNIGHT */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int n=in.nextInt(),a=in.nextInt(),b=in.nextInt(),i,c=0; int ar[]=new int[n]; for(i=0;i<n;i++) ar[i]=in.nextInt(); Arrays.sort(ar); out.println(ar[b]-ar[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.security.SecureRandom; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { public void solve() throws Exception { int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); long h[] = new long[n]; for (int i = 0;i < n; ++ i) { h[i] = sc.nextLong(); } Arrays.sort(h); long l = h[n - a]; long r = h[n - a - 1]; out.println(l - r); } /*--------------------------------------------------------------*/ static String filename = ""; static boolean fromFile = false; BufferedReader in; PrintWriter out; FastScanner sc; public static void main(String[] args) { new Thread(null, new Solution(), "", 1 << 25).start(); } public void run() { try { init(); solve(); } catch (Exception e) { throw new RuntimeException(e); } finally { out.close(); } } void init() throws Exception { if (fromFile) { in = new BufferedReader(new FileReader(filename+".in")); out = new PrintWriter(new FileWriter(filename+".out")); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } sc = new FastScanner(in); } } class FastScanner { BufferedReader reader; StringTokenizer strTok; public FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws IOException { while (strTok == null || !strTok.hasMoreTokens()) { strTok = new StringTokenizer(reader.readLine()); } return strTok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } public BigDecimal nextBigDecimal() throws IOException { return new BigDecimal(nextToken()); } }
nlogn
169_A. Chores
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.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.util.Arrays; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author @zhendeaini6001 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int[] input = IOUtils.readIntArray(in, n); Arrays.sort(input); int x = input[b-1]; int y = input[b]; out.println(y - x); } } class IOUtils { public static int[] readIntArray(Scanner in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.nextInt(); return array; } }
nlogn
169_A. Chores
CODEFORCES
import java.util.*; import java.io.*; import java.math.BigInteger; public class VkR2A{ static BufferedReader br; public static void main(String args[])throws Exception{ br=new BufferedReader(new InputStreamReader(System.in)); int nm[] = toIntArray(); int n = nm[0]; int a = nm[1]; int b = nm[2]; nm=toIntArray(); Arrays.sort(nm); int k=nm[b-1]; int res=nm[b]-k; System.out.println(res); } /****************************************************************/ public static int[] toIntArray()throws Exception{ String str[]=br.readLine().split(" "); int k[]=new int[str.length]; for(int i=0;i<str.length;i++){ k[i]=Integer.parseInt(str[i]); } return k; } public static int toInt()throws Exception{ return Integer.parseInt(br.readLine()); } public static long[] toLongArray()throws Exception{ String str[]=br.readLine().split(" "); long k[]=new long[str.length]; for(int i=0;i<str.length;i++){ k[i]=Long.parseLong(str[i]); } return k; } public static long toLong()throws Exception{ return Long.parseLong(br.readLine()); } public static double[] toDoubleArray()throws Exception{ String str[]=br.readLine().split(" "); double k[]=new double[str.length]; for(int i=0;i<str.length;i++){ k[i]=Double.parseDouble(str[i]); } return k; } public static double toDouble()throws Exception{ return Double.parseDouble(br.readLine()); } public static String toStr()throws Exception{ return br.readLine(); } public static String[] toStrArray()throws Exception{ String str[]=br.readLine().split(" "); return str; } /****************************************************************/ }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class Main { public static void main(String[] args)throws Exception { File _=new File("chores.in"); BufferedReader br=_.exists()? new BufferedReader(new FileReader(_)):new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; String str; st=new StringTokenizer(br.readLine()); int n,a,b; n=Integer.parseInt(st.nextToken()); a=Integer.parseInt(st.nextToken()); b=Integer.parseInt(st.nextToken()); ArrayList<Integer> chores=new ArrayList<Integer>(); int k; st=new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { k=Integer.parseInt(st.nextToken()); chores.add(k); } Collections.sort(chores); System.out.println(chores.get(b)-chores.get(b-1)); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class problemA { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int[] hs = new int[n]; for(int i = 0; i < n; i++){ hs[i] = sc.nextInt(); } Arrays.sort(hs); System.out.println(hs[b]-hs[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import sun.reflect.generics.tree.Tree; import java.io.*; import java.util.*; public class A2 { static Scanner in; static int next() throws Exception {return in.nextInt();}; // static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} // static BufferedReader in; static PrintWriter out; public static void main(String[] args) throws Exception { in = new Scanner(System.in); // in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = next(), a = next(), b = next(); int h[] = new int[n]; for (int i = 0;i < n;i++) h[i] = next(); Arrays.sort(h); int res = h[b] - h[b-1]; out.println(res); out.println(); out.close(); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class ProblemA { public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); String[] data = s.readLine().split(" "); int n = Integer.valueOf(data[0]); int a = Integer.valueOf(data[1]); int b = Integer.valueOf(data[2]); long[] h = new long[n]; String[] line = s.readLine().split(" "); for (int i = 0 ; i < n ; i++) { h[i] = Integer.valueOf(line[i]); } Arrays.sort(h); System.out.println(h[b] - h[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.InputMismatchException; public class R2_D2_A { public static void main(String[] args) { // BufferedReader in = new BufferedReader(new // InputStreamReader(System.in)); InputReader in = new InputReader(System.in); int n = in.readInt(); int a = in.readInt(); int b = in.readInt(); Integer[] inp = new Integer[n]; for (int i = 0; i < inp.length; i++) { inp[i] = in.readInt(); } Arrays.sort(inp); int petya = inp[inp.length-a]; int next = inp[inp.length-a-1]; int diff = petya - next; System.out.println(diff); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Train_A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int [] h = new int[n]; for (int i = 0; i < n; i++) { h[i] = sc.nextInt(); } Arrays.sort(h); System.out.println(h[n-a] - h[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { private static IO io; public static void main(String[] args) throws IOException { new Main().run(); } private void run() throws IOException { io = new IO(System.getProperty("ONLINE_JUDGE")!=null); solve(); io.flush(); } private void solve() throws IOException { int n = io.nI(), a = io.nI(), b = io.nI(), h[] = new int[n], i; for(i = 0; i<n; i++)h[i] = io.nI(); Arrays.sort(h); io.wln(h[b]-h[b-1]); }//2.2250738585072012e-308 private int gcd(int a, int b) { while(b>0) b^=a^=b^=a%=b; return a; } @SuppressWarnings("unused") private class IO{ StreamTokenizer in; PrintWriter out; BufferedReader br; Reader reader; Writer writer; public IO(boolean oj) throws IOException{ Locale.setDefault(Locale.US); reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt"); writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt"); br = new BufferedReader(reader); in = new StreamTokenizer(br); out = new PrintWriter(writer); } public void wln(){out.println();} public void wln(int arg){out.println(arg);} public void wln(long arg){out.println(arg);} public void wln(double arg){out.println(arg);} public void wln(String arg){out.println(arg);} public void wln(boolean arg){out.println(arg);} public void wln(char arg){out.println(arg);} public void wln(float arg){out.println(arg);} public void wln(Object arg){out.println(arg);} public void w(int arg){out.print(arg);} public void w(long arg){out.print(arg);} public void w(double arg){out.print(arg);} public void w(String arg){out.print(arg);} public void w(boolean arg){out.print(arg);} public void w(char arg){out.print(arg);} public void w(float arg){out.print(arg);} public void w(Object arg){out.print(arg);} public void wf(String format, Object...args){out.printf(format, args);} public void flush(){out.flush();} public int nI() throws IOException {in.nextToken(); return(int)in.nval;} public long nL() throws IOException {in.nextToken(); return(long)in.nval;} public String nS() throws IOException {in.nextToken(); return in.sval;} public double nD() throws IOException {in.nextToken(); return in.nval;} public float nF() throws IOException {in.nextToken(); return (float)in.nval;} public void wc(char...a){for(char c : a){in.ordinaryChar(c);in.wordChars(c, c);}} public void wc(char c1, char c2){in.ordinaryChars(c1, c2); in.wordChars(c1, c2);} } }
nlogn
169_A. Chores
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class SolA { private static InputReader in; private static PrintWriter out; public static void main(String[] args) throws IOException { in = new InputReader(System.in); out = new PrintWriter(System.out); run(); out.close(); } public static void run() { int n = in.readInt(); int a = in.readInt(); int b = in.readInt(); int[] h = new int[n]; for(int i = 0; i < n; i++) { h[i] = - in.readInt(); } Arrays.sort(h); int base = -h[a-1]; int base1 = -h[a]; out.print(-(base1 - base)); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class Solver { StringTokenizer st; BufferedReader in; PrintWriter out; public long result = 0; public int k = 0; public static void main(String[] args) throws NumberFormatException, IOException { Solver solver = new Solver(); solver.open(); solver.solve(); solver.close(); } public void open() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } public String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } public void solve() throws NumberFormatException, IOException { int n = nextInt(); int a = nextInt(); int b = nextInt(); int[] ar = new int[n]; for(int i=0;i<n;i++){ ar[i] = nextInt(); } Arrays.sort(ar); out.println(ar[b]-ar[b-1]); } public void close() { out.flush(); out.close(); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int[] ar = new int[n]; for (int i = 0; i < n; i++) ar[i] = in.nextInt(); Arrays.sort(ar); int x1 = ar[b-1]; int x2 = ar[b]; System.out.println(x2-x1); } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class CF_Chores { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int a = s.nextInt(); int b = s.nextInt(); long ar[] = new long[n]; for (int i = 0; i < n; i++) { ar[i]=s.nextLong(); } Arrays.sort(ar); long ret = 0; // System.out.println(Arrays.toString(ar)); if(ar[b]==ar[b-1]) System.out.println("0"); else { ret = ar[b]-ar[b-1]; System.out.println(ret); } } }
nlogn
169_A. Chores
CODEFORCES
import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { Scanner c=new Scanner(System.in); int n=c.nextInt(); int a=c.nextInt(); //higher int b=c.nextInt(); //lower int C[]=new int[n]; for(int i=0;i<n;i++) C[i]=c.nextInt(); Arrays.sort(C); //System.out.println(Arrays.toString(C)); int petya=C[n-a]; System.out.println((C[n-a]-C[n-a-1])); } } //must declare new classes here
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer=null; public static void main(String[] args) throws IOException { new Main().execute(); } void debug(Object...os) { System.out.println(Arrays.deepToString(os)); } int ni() throws IOException { return Integer.parseInt(ns()); } long nl() throws IOException { return Long.parseLong(ns()); } double nd() throws IOException { return Double.parseDouble(ns()); } String ns() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(br.readLine()); return tokenizer.nextToken(); } String nline() throws IOException { tokenizer=null; return br.readLine(); } //Main Code starts Here int totalCases, testNum; int n,a,b; long arr[]; void execute() throws IOException { totalCases = 1; for(testNum = 1; testNum <= totalCases; testNum++) { if(!input()) break; solve(); } } void solve() throws IOException { Arrays.sort(arr); long x1 = arr[b-1]; long x2 = arr[b]; System.out.println(x2-x1); } boolean input() throws IOException { n = ni(); a = ni(); b = ni(); arr = new long[n]; for(int i = 0;i<n;i++) { arr[i] = nl(); } return true; } }
nlogn
169_A. Chores
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = sc.nextInt(); } Arrays.sort(ar); if (ar[b-1] == ar[b ]) { System.out.println(0); } else { System.out.println(ar[b ] - ar[b-1]); } } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Solution { public static void main(String[] args) throws IOException { new Solution().run(); } StreamTokenizer in; Scanner ins; PrintWriter out; int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } void run() throws IOException { if(System.getProperty("ONLINE_JUDGE")!=null) { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); ins = new Scanner(System.in); out = new PrintWriter(System.out); } else { in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt"))); ins = new Scanner(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } int n = nextInt(),a = nextInt(),b = nextInt(); b--; int [] A = new int[n]; for(int i = 0; i < n ;i++) { A[i] = nextInt(); } Arrays.sort(A); if(A[b] == A[b+1]) out.print(0); else out.print(A[b+1]- A[b]); out.close(); } class Team implements Comparable { public int p,t; public int compareTo(Object obj) { Team a = (Team) obj; if(p>a.p || p==a.p && t<a.t) return -1; else if(p==a.p && t==a.t) return 0; else return 1; } } }
nlogn
169_A. Chores
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int a = input.nextInt(); int b = input.nextInt(); int x[] = new int[n]; for (int i=0; i<n; i++) x[i]=input.nextInt(); Arrays.sort(x); int y[] = new int[n]; for (int i=0; i<n; i++) y[i]=x[n-i-1]; System.out.println(y[a-1]-y[a]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class A { @SuppressWarnings("unchecked") private static void solve() throws IOException { ArrayList<Num> c = new ArrayList<Num>(); n = nextInt(); a = nextInt(); b = nextInt(); for(int i = 0; i < n; i++) { int next = nextInt(); boolean found = false; for(int j = 0; j < c.size(); j++) { if(c.get(j).num == next) { c.get(j).freq++; found = true; break; } } if(!found) c.add(new Num(next)); } Collections.sort(c); int below = 0; int above = n; boolean f = false; for(int i = 0; i < c.size(); i++) { below += c.get(i).freq; above -= c.get(i).freq; if(below == b && above == a) { if(i == c.size()) break; System.out.println(c.get(i+1).num - c.get(i).num); f = true; break; } } if(!f) System.out.println(0); } static int n; static int a; static int b; public static void main(String[] args) { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(239); } } static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } } class Num implements Comparable<Num> { int num; int freq; Num(int n) { num = n; freq = 1; } public int compareTo(Num other) { return this.num - other.num; } }
nlogn
169_A. Chores
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; 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); PrintWriter out = new PrintWriter(outputStream); A solver = new A(); solver.solve(1, in, out); out.close(); } } class A { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); int a = in.readInt(); int b = in.readInt(); int[] hs = new int[n]; for (int i=0;i<n;i++){ hs[i]=in.readInt(); } Arrays.sort(hs); out.println(hs[b]-hs[b-1]); } } class InputReader { BufferedReader in; public InputReader(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public int skipSpace() { int c; try { while (true) { c = in.read(); if (c < 0) { throw new InputMismatchException(); } if (c > 32) { break; } } } catch (IOException e) { throw new InputMismatchException(); } return c; } public int readInt() { int res = 0; boolean sign = false; int c = skipSpace(); try { if (c == '-') { sign = true; c = in.read(); } while (true) { if (c >= '0' && c <= '9') { res = res * 10 + c - '0'; } else { throw new InputMismatchException(); } c = in.read(); if (c <= 32) { break; } } if (sign) { res = -res; } return res; } catch (IOException e) { throw new InputMismatchException(); } } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.*; public class A { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; String FInput=""; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } catch (NullPointerException e) { line=null; } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; new A(filePath); } public void readFInput() { for(;;) { try { readNextLine(); FInput+=line+" "; } catch(Exception e) { break; } } inputParser = new StringTokenizer(FInput, " "); } public A(String inputFile) { openInput(inputFile); readNextLine(); int n=NextInt(); int a=NextInt(); int b=NextInt(); int ret=0; readNextLine(); int [] p = new int[n]; for(int i=0; i<n; i++) { p[i]=NextInt(); } Arrays.sort(p); int id=0,cnt=0; while(id<n&&cnt<b) { cnt++; id++; } if(id<n) { ret=p[id]-p[id-1]; } System.out.print(ret); closeInput(); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.*; import java.util.*; public class ayyyyyy { public static void main(String[] args) { new ayyyyyy(); } Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int t, n; int[] a; ayyyyyy() { t = in.nextInt(); while (t --> 0) { a = new int[n = in.nextInt()]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); shuffle(a); Arrays.sort(a); out.println(Math.min(n-2, a[n-2]-1)); } out.close(); } void shuffle(int[] x) { for (int i = 0; i < n; i++) { int swp = (int)(n*Math.random()); int tmp = x[swp]; x[swp] = x[i]; x[i] = tmp; } } }
nlogn
1197_A. DIY Wooden Ladder
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class A { static MyScanner sc; static PrintWriter pw; public static void main(String[] args) throws Throwable { sc = new MyScanner(); pw = new PrintWriter(System.out); n = sc.nextInt(); T = sc.nextLong(); p = new int[n]; l = new int[n]; x = new int[n]; t = new int[n]; adj = new ArrayList[n]; for (int i = 0; i < n; i++) x[i] = sc.nextInt(); for (int i = 0; i < n; i++) t[i] = sc.nextInt(); adj[0] = new ArrayList<>(); for (int i = 1; i < n; i++) { adj[i] = new ArrayList<>(); p[i] = sc.nextInt() - 1; l[i] = sc.nextInt(); adj[p[i]].add(i); } ftCnt = new long[N]; ftSum = new long[N]; ans = new long[n]; dfs(0); pw.println(ans[0]); pw.flush(); pw.close(); } static int n; static long T; static int[] p, l, x, t; static ArrayList<Integer>[] adj; static long[] ans; static void dfs(int u) { update(t[u], x[u], 1L * x[u] * t[u]); ans[u] = getMaxCnt(); long[] vals = {-1, -1, -1}; for (int v : adj[u]) { T -= 2 * l[v]; dfs(v); vals[0] = ans[v]; Arrays.sort(vals); T += 2 * l[v]; } if (u != 0) { if (vals[1] != -1) ans[u] = Math.max(ans[u], vals[1]); } else { if (vals[2] != -1) ans[u] = Math.max(ans[u], vals[2]); } update(t[u], -x[u], -1L * x[u] * t[u]); } static int N = (int) 1e6 + 2; static long[] ftCnt, ftSum; static void update(int idx, long cnt, long val) { while (idx < N) { ftCnt[idx] += cnt; ftSum[idx] += val; idx += (idx & -idx); } } static long getSum(int idx) { long ret = 0; while (idx > 0) { ret += ftSum[idx]; idx -= (idx & -idx); } return ret; } static long getCnt(int idx) { long ret = 0; while (idx > 0) { ret += ftCnt[idx]; idx -= (idx & -idx); } return ret; } static long getMaxCnt() { int start = 1, end = N - 1, ans = N - 1; while (start <= end) { int mid = (start + end) / 2; if (getSum(mid) >= T) { ans = mid; end = mid - 1; } else start = mid + 1; } long remT = T - (ans > 1 ? getSum(ans - 1) : 0); long cnt = (ans > 1 ? getCnt(ans - 1) : 0); long cntOfVal = getCnt(ans) - cnt; cnt += Math.min(cntOfVal, remT / ans); return cnt; } 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
1099_F. Cookies
CODEFORCES
import java.util.*; import java.math.*; public class Split { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n= sc.nextInt(); int k= sc.nextInt(); int a[] = new int[n]; int d[] = new int[n-1]; for(int i=0;i<n;i++) { a[i] = sc.nextInt(); if(i>0) d[i-1] = a[i-1] - a[i]; } Arrays.sort(d); int t = 0; for(int i=0;i<k-1;i++) t += d[i]; System.out.println(a[n-1]-a[0]+t); } }
nlogn
1197_C. Array Splitting
CODEFORCES
import java.io.*; import java.util.*; import javax.lang.model.util.ElementScanner6; public class codef { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer nk=new StringTokenizer(br.readLine()); int n=Integer.parseInt(nk.nextToken()); int k=Integer.parseInt(nk.nextToken()); String st[]=br.readLine().split(" "); int ans[]=new int[n]; int a[]=new int[n]; for(int i=0;i<n;i++) ans[i]=Integer.parseInt(st[i]); for(int i=1;i<n;i++) a[i]=ans[i]-ans[i-1]; a[0]=-1; Arrays.sort(a); int count=0,sum=0; for(int i=0;i<n;i++) if(a[i]<0) count++; else sum=sum+a[i]; k=k-count; int i=n-1; while(k>0 && i>=0) { if(a[i]>-1) { sum=sum-a[i]; k--; } i--; } System.out.println(sum); } }
nlogn
1197_C. Array Splitting
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner in =new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = in.nextInt(); for(int i = n-1; i > 0; i--) arr[i] -= arr[i-1]; arr[0] = 0; Arrays.sort(arr); long sum = 0; for(int i = n-k; i >= 0; i--) sum += arr[i]; System.out.println(sum); } }
nlogn
1197_C. Array Splitting
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.System.out; public class Main { private FastScanner scanner = new FastScanner(); public static void main(String[] args) { new Main().solve(); } private List<Integer>[] gr = new ArrayList[1000_000+5]; private int dp[][] = new int[21][1000_000+5]; private boolean used[] = new boolean[1000_000+5]; void init(int v, int p) { Stack<Integer> st = new Stack<>(); st.push(v); st.push(p); while (!st.isEmpty()) { p = st.pop(); v = st.pop(); used[v] = true; dp[0][v] = p; for (int i = 1; i <= 20; i++) { if (dp[i - 1][v] != -1) { dp[i][v] = dp[i - 1][dp[i - 1][v]]; } } for (int next : gr[v]) { if (!used[next]) { st.push(next); st.push(v); } } } } private void solve() { int n = scanner.nextInt(), k = scanner.nextInt(); boolean[] ans = new boolean[1000_000 + 5]; for (int i = 0; i < n; i++) { gr[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i ++) { int u = scanner.nextInt() - 1, v = scanner.nextInt() - 1; gr[u].add(v); gr[v].add(u); } k = n - k - 1; ans[n - 1] = true; init(n - 1 , n - 1); int t, d, next; for (int i = n - 2; i >= 0; i--) { t = i; d = 1; if (ans[i]) { continue; } for (int j = 20; j >= 0; j--){ next = dp[j][t]; if (next != -1 && !ans[next]) { t = next; d += 1 << j; } } if (d <= k) { k -=d; t = i; while (!ans[t]) { ans[t] = true; t = dp[0][t]; } } if (k == 0) { break; } } StringBuilder sb = new StringBuilder(""); for (int i = 0; i < n; i++) { if (!ans[i]) { sb.append(i + 1).append(" "); } } System.out.println(sb.toString()); } 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); } } } }
nlogn
980_E. The Number Games
CODEFORCES
import java.util.*; import java.io.*; public class a { static long mod = 1000000007; static boolean[][] blacks; public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(new PrintStream(System.out)); //Scanner input = new Scanner(new File("input.txt")); //PrintWriter out = new PrintWriter(new File("output.txt")); int n = input.nextInt(), t = input.nextInt(); int res = 2; Cottage[] data = new Cottage[n]; int[] xs = new int[n], as = new int[n]; for(int i = 0; i<n; i++) { data[i] = new Cottage(input.nextInt(), input.nextInt()); } Arrays.sort(data); for(int i = 0; i<n; i++) { xs[i] = data[i].x; as[i] = data[i].a; } for(int i = 0; i<n-1; i++) { if(2*(xs[i+1]-xs[i]) == 2*t+as[i]+as[i+1]) res++; else if(2*(xs[i+1]-xs[i]) > 2*t+as[i]+as[i+1]) res+=2; } out.println(res); out.close(); } static class Cottage implements Comparable<Cottage> { /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ int x, a; public Cottage(int xx, int aa) { x = xx; a = aa; } @Override public int compareTo(Cottage o) { // TODO(mkirsche): Auto-generated method stub return this.x - o.x; } } static long pow(long a, long p) { if(p==0) return 1; if((p&1) == 0) { long sqrt = pow(a, p/2); return (sqrt*sqrt)%mod; } else return (a*pow(a,p-1))%mod; } 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 long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static String nextLine() throws IOException { return reader.readLine(); } } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.Random; import java.util.Arrays; import java.util.StringTokenizer; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStreamReader; import java.io.File; public class Task{ static final boolean readFromFile = false; static final String fileInputName = "input.txt", fileOutputName = "output.txt"; public static void main(String args[]){ FileInputStream fileInputStream; FileOutputStream fileOutputStream; InputStream inputStream = System.in; OutputStream outputStream = System.out; if (readFromFile){ try{ fileInputStream = new FileInputStream(new File(fileInputName)); fileOutputStream = new FileOutputStream(new File(fileOutputName)); }catch (FileNotFoundException e){ throw new RuntimeException(e); } } PrintWriter out = new PrintWriter((readFromFile)?fileOutputStream:outputStream); InputReader in = new InputReader((readFromFile)?fileInputStream:inputStream); Solver s = new Solver(in, out); s.solve(); out.close(); } } class Solver{ private PrintWriter out; private InputReader in; public void solve(){ int n = in.nextInt(); double t = in.nextDouble(), a[] = new double[n], x[] = new double[n]; for (int i=0;i<n;i++){ x[i] = in.nextDouble(); a[i] = in.nextDouble(); } int ans = 2; for (int i=0;i<n-1;i++) for (int j=i+1;j<n;j++) if (x[j]<x[i]){ double buf = x[i];x[i]=x[j];x[j]=buf; buf = a[i]; a[i]=a[j];a[j]=buf; } for (int i=0;i<n-1;i++){ if (x[i]+a[i]/2+t<x[i+1]-a[i+1]/2) ans += 2; if (x[i]+a[i]/2+t==x[i+1]-a[i+1]/2) ans++; } out.println(ans); } Solver(InputReader in, PrintWriter out){ this.in = in; this.out = out; } } class InputReader{ StringTokenizer tok; BufferedReader buf; InputReader(InputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } InputReader(FileInputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } public String next(){ while (tok==null || !tok.hasMoreTokens()){ try{ tok = new StringTokenizer(buf.readLine()); }catch (IOException e){ throw new RuntimeException(e); } } return tok.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public float nextFloat(){ return Float.parseFloat(next()); } public String nextLine(){ try{ return buf.readLine(); }catch (IOException e){ return null; } } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.awt.Point; import java.io.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Main{ static class Run implements Runnable{ //TODO parameters final boolean consoleIO = true; final String inFile = "input.txt"; final String outFile = "output.txt"; Pair<Double,Double>[] p; int n, t; int find() { int count = 2; for(int i = 0; i < n-1; ++i) { double dif = p[i+1].a-p[i].b; int comp = Double.compare(dif,t); if(comp==0) count+=1; else if(comp>0) count+=2; } return count; } @Override public void run() { n = nextInt(); t = nextInt(); p = new Pair[n]; for(int i = 0; i < n; ++i) { int x = nextInt()+1000; int a = nextInt(); double h = a/(double)2; p[i] = new Pair<Double,Double>(x-h,x+h); } Arrays.sort(p, new PComparator()); print(find()); close(); } class PComparator implements Comparator<Pair<Double,Double>> { @Override public int compare(Pair<Double, Double> o1, Pair<Double, Double> o2) { return Double.compare(o1.a, o2.a); } } //========================================================================================================================= BufferedReader in; PrintWriter out; StringTokenizer strTok; Run() { if (consoleIO) { initConsoleIO(); } else { initFileIO(); } } void initConsoleIO() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } void initFileIO() { try { in = new BufferedReader(new FileReader(inFile)); out = new PrintWriter(new FileWriter(outFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } void close() { try { in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } int nextInt() { return Integer.parseInt(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } float nextFloat() { return Float.parseFloat(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } String nextLine() { try { return in.readLine(); } catch (IOException e) { return "__NULL"; } } boolean hasMoreTokens() { return (strTok == null) || (strTok.hasMoreTokens()); } String nextToken() { while (strTok == null || !strTok.hasMoreTokens()) { String line; try { line = in.readLine(); strTok = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return strTok.nextToken(); } void cout(Object o){ System.out.println(o); } void print(Object o) { out.write(o.toString()); } void println(Object o) { out.write(o.toString() + '\n'); } void printf(String format, Object... args) { out.printf(format, args); } String sprintf(String format, Object... args) { return MessageFormat.format(format, args); } } static class Pair<A, B> { A a; B b; A f() { return a; } B s() { return b; } Pair(A a, B b) { this.a = a; this.b = b; } Pair(Pair<A, B> p) { a = p.f(); b = p.s(); } @Override public String toString() { return a+" "+b; } } public static void main(String[] args) throws IOException { Run run = new Run(); Thread thread = new Thread(run); thread.run(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; public class A { public static double EPS = .001; public class House implements Comparable<House> { int x; int a; public House(int mx, int ma) { x = mx; a = ma; } public int compareTo(House o) { return x - o.x; } public double right() { return (double)x + ((double)a)/2.0; } public double left() { return (double)x - ((double)a)/2.0; } } public static void main(String[] args) { new A().solve(); } public void solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int t = in.nextInt(); ArrayList<House> houses = new ArrayList<House>(); for(int i=0;i<n;i++) { int x = in.nextInt(); int a = in.nextInt(); houses.add(new House(x,a)); } Collections.sort(houses); int total = 2; for(int i=0;i<houses.size()-1;i++) { House me = houses.get(i); House next = houses.get(i+1); double meright = me.right(); double nextleft = next.left(); double diff = nextleft - meright; if(diff-EPS > ((double)t)) { total += 2; } else if(diff+EPS > ((double)t)) { total += 1; } } System.out.println(total); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; public class Village { private class House implements Comparable<House>{ Double Coordinate; Double Sidelength; public House(double coordinate, double sidelength) { Coordinate = coordinate; Sidelength = sidelength; } public int compareTo(House o) { return Coordinate.compareTo(o.Coordinate); } } public static void main(String args[]) { Village v = new Village(); v.solve(); } public void solve() { Scanner in = new Scanner(System.in); int numhouse = in.nextInt(); double requireside = in.nextDouble(); //System.out.println(numhouse); //System.out.println(requireside); ArrayList<House> coordinate = new ArrayList<House>(); ArrayList<Double> sidelength = new ArrayList<Double>(); while (in.hasNext()) { double coo = in.nextDouble(); double side = in.nextDouble(); //System.out.println(coo); //System.out.println(side); coordinate.add(new House(coo,side)); sidelength.add(side); } Collections.sort(coordinate); ArrayList<Double> edges = new ArrayList<Double>(); int count = 2; for (int i = 0; i < coordinate.size();i++) { edges.add(coordinate.get(i).Coordinate - (double)coordinate.get(i).Sidelength/(double)2); edges.add(coordinate.get(i).Coordinate + (double)coordinate.get(i).Sidelength/(double)2); } ArrayList<Double> difference = new ArrayList<Double>(); for (int i = 1; i < edges.size() - 1; i++) { difference.add(Math.abs(edges.get(i) - edges.get(i+1))); } for (int i = 0; i < difference.size(); i+=2) { if (difference.get(i) == requireside) count++; else if (difference.get(i) > requireside) count+=2; } System.out.println(count); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class A15 { static StreamTokenizer in; static PrintWriter out; static int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } static String nextString() throws IOException { in.nextToken(); return in.sval; } public static void main(String[] args) throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); int n = nextInt(), t = nextInt(); int[] x = new int[n]; int[] a = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt(); a[i] = nextInt(); } int ans = 0; for (int i = 0; i < n; i++) { boolean left = true, right = true; for (int j = 0; j < n; j++) if (x[j] < x[i] && a[i] + 2*t + a[j] >= 2*Math.abs(x[i] - x[j])) left = false; else if (x[j] > x[i] && a[i] + 2*t + a[j] > 2*Math.abs(x[i] - x[j])) right = false; if (left) ans++; if (right) ans++; } out.println(ans); out.flush(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author madi */ public class CottageTown { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] in = sc.nextLine().split(" "); int n = Integer.parseInt(in[0]); int t = Integer.parseInt(in[1]); int[] coor = new int[n]; int[] side = new int[n]; for (int i = 0; i < n; i++) { in = sc.nextLine().split(" "); coor[i] = Integer.parseInt(in[0]); side[i] = Integer.parseInt(in[1]); } quickSort(coor, 0, n - 1, side); int count = 2; double dist; for (int i = 0; i < n - 1; i++) { dist = (coor[i + 1] - coor[i]) - (double)(side[i + 1] + side[i]) / 2.0; if (dist > t) { count += 2; } else if (dist == t) { count += 1; } } System.out.println(count); } private static int partition(int[] arr, int left, int right, int[] temp) { int i = left, j = right; int tmp; int pivot = arr[(left + right) / 2]; while (i <= j) { while (arr[i] < pivot) { i++; } while (arr[j] > pivot) { j--; } if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; tmp = temp[i]; temp[i] = temp[j]; temp[j] = tmp; i++; j--; } } return i; } private static void quickSort(int[] arr, int left, int right, int[] temp) { int index = partition(arr, left, right, temp); if (left < index - 1) { quickSort(arr, left, index - 1, temp); } if (index < right) { quickSort(arr, index, right, temp); } } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.Scanner; public class Flatwile { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt(); int[] c = new int[n]; int[] a = new int[n]; for (int i=0; i<n; i++){ c[i] = sc.nextInt(); a[i] = sc.nextInt(); } sort(c, a); int res = 1; double prev = Integer.MIN_VALUE; for(int i=0; i<c.length; i++){ if (c[i]-a[i]/2d - prev >=t){ res++; } if (i!=c.length-1 && c[i+1]-a[i+1]/2d-(c[i]+a[i]/2d)>t ){ res++; } prev = c[i] +a[i]/2d; } System.out.println(res); } private static void sort(int[] a, int[] b){ for(int i=0; i<a.length; i++){ for(int j=i+1; j<a.length; j++){ if (a[i]>a[j]){ swap(a, i, j); swap(b, i, j); } } } } private static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { new A().solve(); } public void solve() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt(); float[] left = new float[n]; float[] right = new float[n]; for (int i=0; i<n; ++i) { int c = sc.nextInt(); int w = sc.nextInt(); left[i] = (float) (c - (float) w * 1.0 / 2); right[i] = (float) (c + (float) w * 1.0 / 2); } for (int i=0; i<n; ++i) for (int j=i+1; j<n; ++j) if (left[j] < left[i]) { float tmp = left[i]; left[i] = left[j]; left[j] = tmp; tmp = right[i]; right[i] = right[j]; right[j] = tmp; } int res = 2; for (int i=1; i<n; ++i) { float dis = left[i] - right[i-1]; if (Math.abs(dis - t) < 0.000001) res ++; if ((dis - t) > 0.000001) res += 2; } System.out.println(res); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Houses implements Runnable { private void solve() throws IOException { int n = nextInt(); int t = nextInt(); int[] x = new int[n]; int[] a = new int[n]; for (int i = 0; i < n; ++i) { x[i] = nextInt() * 2; a[i] = nextInt(); } Set<Integer> res = new HashSet<Integer>(); for (int i = 0; i < n; ++i) { if (valid(n, t, x, a, x[i] + a[i] + t)) res.add(x[i] + a[i] + t); if (valid(n, t, x, a, x[i] - a[i] - t)) res.add(x[i] - a[i] - t); } writer.println(res.size()); } private boolean valid(int n, int t, int[] x, int[] a, int pos) { for (int i = 0; i < n; ++i) { if (Math.abs(pos - x[i]) < a[i] + t) return false; } return true; } public static void main(String[] args) { new Houses().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; public class C15A { public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int t=sc.nextInt(); double nm[][]=new double[n][2]; int a=0; int b=0; for(int i=0;i<n;i++){ a=sc.nextInt(); b=sc.nextInt(); nm[i][0]=a-(double)b/2; nm[i][1]=a+(double)b/2; } Arrays.sort(nm, new ArrayColumnComparator(1)); int sum=0; for(int i=0;i<n-1;i++){ if(nm[i+1][0]-nm[i][1]==t) sum++; else if(nm[i+1][0]-nm[i][1]>t){ sum+=2; } } System.out.println(sum+2); } } class ArrayColumnComparator implements Comparator { private int cm = 0; ArrayColumnComparator(int cm) { this.cm = cm; } public int compare(Object o1, Object o2) { double[] row1 = (double[])o1; double[] row2 = (double[])o2; int i; if (row1[cm]>row2[cm]) i=1; else if(row1[cm]<row2[cm]) i=-1; else i=0; return i; } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; import static java.lang.Math.*; public class Main{ public static void main(String[] args){ new Main().run(); } void run(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt() * 2; H[] tbl = new H[n]; for(int i = 0; i < n; i++)tbl[i] = new H(sc.nextInt()*2, sc.nextInt()*2); Arrays.sort(tbl); TreeSet<Integer> cand = new TreeSet<Integer>(); //cand.add(tbl[0].x - tbl[0].len / 2); for(int i = 0; i < n; i++){ int left = tbl[i].x - tbl[i].len / 2 - t / 2; if(!cand.contains(left)){ if(i > 0 && tbl[i-1].x + tbl[i-1].len/2 > left - t/2){ }else{ cand.add(left); } } int right = tbl[i].x + tbl[i].len / 2 + t/2; if(!cand.contains(right)){ if(i < n-1 && tbl[i+1].x - tbl[i+1].len/2 < right + t/2){ }else{ cand.add(right); } } } System.out.println(cand.size()); } class H implements Comparable<H>{ int x, len; H(int a, int b){ x = a; len = b; } public int compareTo(H h){ return this.x - h.x; } } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.*; public class j { public static void main(String a[])throws IOException { BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); int k=0,i=0,j=0,n=0,p=0,t=0; String s; s=b.readLine(); StringTokenizer c=new StringTokenizer(s); n=Integer.parseInt(c.nextToken()); k=Integer.parseInt(c.nextToken()); int d[]=new int[n]; int e[]=new int[n]; for(i=0;i<n;i++) { s=b.readLine(); StringTokenizer z=new StringTokenizer(s); d[i]=Integer.parseInt(z.nextToken()); e[i]=Integer.parseInt(z.nextToken()); } for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { if(d[j]<d[i]) { t=d[j]; d[j]=d[i]; d[i]=t; t=e[j]; e[j]=e[i]; e[i]=t; } } } for(i=0;i<n-1;i++) { if(((d[i+1]-e[i+1]/2.0)-(d[i]+e[i]/2.0))>k) p+=2; if(((d[i+1]-e[i+1]/2.0)-(d[i]+e[i]/2.0))==k) p++; } System.out.print(p+2); } }
nlogn
15_A. Cottage Village
CODEFORCES