content
stringlengths 219
31.2k
| complexity
stringclasses 5
values | file_name
stringlengths 6
9
| complexity_ranked
float64 0.1
0.9
|
---|---|---|---|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.PriorityQueue;
public class LessorEqual_CodeForces {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp[]=br.readLine().split(" ");
int n = Integer.parseInt(temp[0]);
int k = Integer.parseInt(temp[1]);
temp=br.readLine().split(" ");
int [] num = new int[n];
// int [] freq = new int [1000000000];
PriorityQueue<Integer>pq = new PriorityQueue<Integer>();
for(int i=0;i<n;i++){
num[i]=Integer.parseInt(temp[i]);
pq.add(num[i]);
// freq[num[i]]++;
}
if(k==0){
int y= pq.poll();
if(y==1){
System.out.println(-1);
System.exit(0);
}
else
{
System.out.println(y-1);
System.exit(0);
}
}
//System.out.println(pq);
int count=0;
int max=0;
while (!pq.isEmpty()){
int x = pq.poll();
while(count<=k&&!pq.isEmpty()&& pq.peek()==x){
pq.poll();
count++;
}
// System.out.println(x);
count++;
max=x;
if(count==k)
break;
}
//System.out.println("the count is "+ count);
if(count==k){
if(!pq.contains(max+1)&& max<1e9)
System.out.println(max+1);
else
System.out.println(max);
}
else
System.out.println(-1);
}
}
|
nlogn
|
884.java
| 0.7 |
import java.util.Scanner;
public class JavaApplication7 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n= sc.nextInt();
int m=sc.nextInt();
long sum=0;
long []d=new long[n];
long[]ds=new long[n];
for(int i =0;i<n;i++){
d[i]=sc.nextLong();
sum+=d[i];
ds[i]=sum;
}
long[]le=new long[m];
for(int i =0;i<m;i++){
le[i]=sc.nextLong();
}
int l=0;
int h=n;
int k=(h-l)/2;
k+=l;
for(int i=0;i<m;i++){
l=0;
h=n;
k=(h-l)/2;
k+=l;
for(;l<=h;){
k=(h-l)/2;
k+=l;
if(ds[k]<le[i]){
l=k+1;
}
else if(ds[k]==le[i]){break;}
else{
h=k-1;
}
}
//System.out.println(k);
if(ds[k]<le[i]){
k++;
}
if(k==0){
System.out.println((int)(k+1)+" "+le[i]);
}
else{
System.out.println((int)(k+1)+" "+(long)(le[i]-ds[k-1]));
}
}
}
}
|
nlogn
|
888.java
| 0.7 |
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
|
895.java
| 0.7 |
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Comp c1 = getComp(scanner);
Comp c2 = getComp(scanner);
c1.sortByPrice();
c2.sortByPrice();
int i = 0;
int j = 0;
while(i < c1.num || j < c2.num) {
Elem xi = (i < c1.num) ? c1.elems.get(i) : null;
Elem yj = (j < c2.num) ? c2.elems.get(j) : null;
if(xi != null && yj != null) {
if(xi.price >= yj.price) {
if(!c2.resultSet.contains(xi)) {
c1.resultSet.add(xi);
}
i++;
} else {
if(!c1.resultSet.contains(yj)) {
c2.resultSet.add(yj);
}
j++;
}
} else
if(xi != null) {
if(!c2.resultSet.contains(xi)) {
c1.resultSet.add(xi);
}
i++;
} else {
if(!c1.resultSet.contains(yj)) {
c2.resultSet.add(yj);
}
j++;
}
}
long result = c1.getResultPrice() + c2.getResultPrice();
System.out.println(result);
}
private static Comp getComp(Scanner scanner) {
Comp c = new Comp();
c.num = scanner.nextInt();
for(int i = 0; i < c.num; i++) {
c.addElem(scanner.nextLong(), scanner.nextLong());
}
return c;
}
}
class Comp {
int num;
List<Elem> elems = new ArrayList<>();
Set<Elem> resultSet = new HashSet<>();
void addElem(long el, long pr) {
Elem elem = new Elem(el, pr);
elems.add(elem);
}
void sortByPrice() {
Collections.sort(elems);
}
long getResultPrice() {
long sumPrice = 0;
for(Elem elem : resultSet) {
sumPrice += elem.price;
}
return sumPrice;
}
}
class Elem implements Comparable<Elem> {
long elem;
long price;
public Elem(long el, long pr) {
this.elem = el;
this.price = pr;
}
public int compareTo(Elem other) {
return (int) (other.price - price);
}
public boolean equals(Object o) {
if(!(o instanceof Elem)) {
return false;
}
Elem other = (Elem) o;
return (other.elem == elem);
}
public int hashCode() {
return (int) elem;
}
public String toString() {
return "(" + elem + ", " + price + ")";
}
}
|
nlogn
|
897.java
| 0.7 |
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] wide = new int[n], sta = new int[n];
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
wide[i] = sc.nextInt();
hm.put(wide[i], i + 1);
}
Util.sort(wide);
sc.nextLine();
String s = sc.nextLine();
int tp = 0, pos = 0;
StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
int t;
if (s.charAt(i) == '0') {
t = wide[pos++];
sta[tp++] = t;
} else t = sta[--tp];
out.append(hm.get(t) + " ");
}
System.out.println(out.toString());
sc.close();
}
public static class Util {
public static <T extends Comparable<T> > void merge_sort(T[] a) {
Object[] aux = new Object[a.length];
merge_sort0(a, aux, 0, a.length);
}
public static <T extends Comparable<T> > void merge_sort(T[] a, int l, int r) {
Object[] aux = new Object[a.length];
merge_sort0(a, aux, l, r);
}
@SuppressWarnings("unchecked")
private static <T extends Comparable<T> > void merge_sort0(T[] a, Object[] temp, int l, int r) {
if (l + 1 == r) return;
int mid = (l + r) >> 1;
merge_sort0(a, temp, l, mid);
merge_sort0(a, temp, mid, r);
int x = l, y = mid, c = l;
while (x < mid || y < r) {
if (y == r || (x < mid && a[x].compareTo(a[y]) <= 0)) temp[c++] = a[x++];
else temp[c++] = a[y++];
}
for (int i = l; i < r; i++) a[i] = (T)temp[i];
}
static final Random RAN = new Random();
public static <T extends Comparable<T> > void quick_sort(T[] a) {
quick_sort0(a, 0, a.length);
}
public static <T extends Comparable<T> > void quick_sort(T[] a, int l, int r) {
quick_sort0(a, l, r);
}
private static <T extends Comparable<T> > void quick_sort0(T[] a, int l, int r) {
if (l + 1 >= r) return;
int p = l + RAN.nextInt(r - l);
T t = a[p]; a[p] = a[l]; a[l] = t;
int x = l, y = r - 1;
while (x < y) {
while (x < y && a[y].compareTo(t) > 0) --y;
while (x < y && a[x].compareTo(t) < 0) ++x;
if (x < y) {
T b = a[x]; a[x] = a[y]; a[y] = b;
++x; --y;
}
}
quick_sort0(a, l, y + 1);
quick_sort0(a, x, r);
}
static final int BOUND = 8;
public static void bucket_sort(int[] a) {
bucket_sort(a, 0, a.length);
}
public static void bucket_sort(int[] a, int l, int r) {
int[] cnt = new int[1 << BOUND], b = new int[r - l + 1];
int y = 0;
for (int i = l; i < r; i++) ++cnt[a[i] & (1 << BOUND) - 1];
while (y < Integer.SIZE) {
for (int i = 1; i < 1 << BOUND; i++) cnt[i] += cnt[i - 1];
for (int i = r - 1; i >= l; i--) b[--cnt[a[i] >> y & (1 << BOUND) - 1]] = a[i];
y += BOUND;
Arrays.fill(cnt, 0);
for (int i = l; i < r; i++) {
a[i] = b[i - l];
++cnt[a[i] >> y & (1 << BOUND) - 1];
}
}
}
public static void bucket_sort(long[] a) {
bucket_sort(a, 0, a.length);
}
public static void bucket_sort(long[] a, int l, int r) {
int[] cnt = new int[1 << BOUND];
long[] b = new long[r - l + 1];
int y = 0;
while (y < Long.SIZE) {
Arrays.fill(cnt, 0);
for (int i = l; i < r; i++) ++cnt[(int) (a[i] >> y & (1 << BOUND) - 1)];
for (int i = 1; i < 1 << BOUND; i++) cnt[i] += cnt[i - 1];
for (int i = r - 1; i >= l; i--) b[--cnt[(int) (a[i] >> y & (1 << BOUND) - 1)]] = a[i];
for (int i = l; i < r; i++) a[i] = b[i - l];
y += BOUND;
}
}
public static void sort(int[] a) {
if (a.length <= 1 << BOUND) {
Integer[] b = new Integer[a.length];
for (int i = 0; i < a.length; i++) b[i] = a[i];
quick_sort(b);
for (int i = 0; i < a.length; i++) a[i] = b[i];
} else bucket_sort(a);
}
public static void sort(long[] a) {
if (a.length <= 1 << BOUND) {
Long[] b = new Long[a.length];
for (int i = 0; i < a.length; i++) b[i] = a[i];
quick_sort(b);
for (int i = 0; i < a.length; i++) a[i] = b[i];
} else bucket_sort(a);
}
public static <T extends Comparable<T> > void sort(T[] a) {
quick_sort(a);
}
public static void shuffle(int[] a) {
Random ran = new Random();
for (int i = 0; i < a.length; i++) {
int p = ran.nextInt(i + 1);
int q = a[p]; a[p] = a[i]; a[i] = q;
}
}
public static void shuffle(long[] a) {
Random ran = new Random();
for (int i = 0; i < a.length; i++) {
int p = ran.nextInt(i + 1);
long q = a[p]; a[p] = a[i]; a[i] = q;
}
}
public static <T> void shuffle(T[] a) {
Random ran = new Random();
for (int i = 0; i < a.length; i++) {
int p = ran.nextInt(i + 1);
T q = a[p]; a[p] = a[i]; a[i] = q;
}
}
}
}
|
nlogn
|
901.java
| 0.7 |
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
public final class Codeforces
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=0;i<n;i++){
int temp=sc.nextInt();
list.add(temp);
}
Collections.sort(list);
if(n%2==0)
System.out.println(list.get((n/2)-1));
else
System.out.println(list.get(n/2));
}
}
|
nlogn
|
904.java
| 0.7 |
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] p = new int[n / 2];
for (int i = 0; i < p.length; i++) {
p[i] = sc.nextInt();
}
System.out.println(solve(p));
sc.close();
}
static int solve(int[] p) {
return Math.min(computeMoveNum(p, 1), computeMoveNum(p, 2));
}
static int computeMoveNum(int[] p, int offset) {
Arrays.sort(p);
return IntStream.range(0, p.length).map(i -> Math.abs(p[i] - (i * 2 + offset))).sum();
}
}
|
nlogn
|
907.java
| 0.7 |
import java.util.*;
import java.io.*;
public class Sol {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt();
int k = sc.nextInt();
int l = sc.nextInt();
Integer[] a = new Integer[n*k];
for(int i = 0; i < n*k; i++){
a[i] = sc.nextInt();
}
Arrays.sort(a);
if (a[n - 1] - a[0] > l) {
out.println(0);
} else {
int maxPos = n*k - 1;
for (int i = 0; i < n*k; i++) {
if (a[i] - a[0] > l) {
maxPos = i-1;
break;
}
}
long o = a[0];
int s = 0;
int t = 1;
for (int i = 1; i <= maxPos; i++) {
//System.out.print(a[i]);
if (s < k - 1 && maxPos-i+1 > n-t) {
//System.out.println(" @");
s++;
} else {
//System.out.println(" #");
s = 0;
t++;
o += a[i];
}
}
out.println(o);
}
out.close();
}
// -----------PrintWriter for faster output-------------
public static PrintWriter out;
// -----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// --------------------------------------------------------
}
|
nlogn
|
909.java
| 0.7 |
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
|
912.java
| 0.7 |
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
|
914.java
| 0.7 |
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
|
915.java
| 0.7 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class MicroWorld {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
Integer[] a = new Integer[n];
st = new StringTokenizer(br.readLine());
for(int i=0; i<n; i++){
a[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(a);
int count = 1;
int remaining = n;
for(int i=0; i<n-1; i++){
if((int)a[i] == (int)a[i+1]){
count++;
continue;
}
if((a[i] + k) >= a[i+1]){
remaining -= count;
}
count = 1;
}
System.out.println(remaining);
}
}
|
nlogn
|
919.java
| 0.7 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class MicroWorld {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] temp = new int[1000001];
StringTokenizer st1 = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++){
temp[Integer.parseInt(st1.nextToken())]++;
}
int b = k + 1;
for (int i = 1000000; i > 0; i--){
if (temp[i] > 0){
if (b <= k){
n -= temp[i];
}
b = 1;
}else{
b++;
}
}
System.out.println(n);
}
}
|
nlogn
|
920.java
| 0.7 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class gr1 {
static class InputReader {
public BufferedReader br;
public StringTokenizer token;
public InputReader(InputStream stream)
{
br=new BufferedReader(new InputStreamReader(stream),32768);
token=null;
}
public String next()
{
while(token==null || !token.hasMoreTokens())
{
try
{
token=new StringTokenizer(br.readLine());
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
return token.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
}
static class card{
long a;
int cnt;
int i;
public card(long a,int cnt,int i)
{
this.a=a;
this.cnt=cnt;
this.i=i;
}
}
static class ascend implements Comparator<pair>
{
public int compare(pair o1,pair o2)
{
if(o1.b!=o2.b)
return (int)(o1.b-o2.b);
else
return (int)(o1.a-o2.a);
}
}
/*static class descend implements Comparator<pair>
{
public int compare(pair o1,pair o2)
{
if(o1.a!=o2.a){
return (o1.a-o2.a)*-1;
} else {
return (o1.b-o2.b);
}
}
}*/
static class extra
{
static void shuffle(long a[])
{
List<Long> l=new ArrayList<>();
for(int i=0;i<a.length;i++)
l.add(a[i]);
Collections.shuffle(l);
for(int i=0;i<a.length;i++)
a[i]=l.get(i);
}
static long gcd(long a,long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
static boolean valid(int i,int j,int r,int c)
{
if(i>=0 && i<r && j>=0 && j<c)
return true;
else
return false;
}
static boolean v[]=new boolean[100001];
static List<Integer> l=new ArrayList<>();
static int t;
static void seive()
{
for(int i=2;i<100001;i++)
{
if(!v[i])
{
t++;
l.add(i);
for(int j=2*i;j<100001;j+=i)
v[j]=true;
}
}
}
static int binary(pair a[],int val,int n)
{
int mid=0,l=0,r=n-1,ans=0;
while(l<=r)
{
mid=(l+r)>>1;
if(a[mid].a==val)
{
r=mid-1;
ans=mid;
}
else if(a[mid].a>val)
r=mid-1;
else
{
l=mid+1;
ans=l;
}
}
return (ans);
}
}
static class pair{
long a;
int b;
public pair(long a,int n)
{
this.a=a;
this.b=n;
}
}
static InputReader sc=new InputReader(System.in);
static PrintWriter out=new PrintWriter(System.out);
public static void main(String[] args) {
solver s=new solver();
int t=1;
while(t>0)
{
s.solve();
t--;
}
}
static class solver
{
void solve()
{
int n=sc.nextInt();
int a[]=new int[n];
int sum=0;
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
sum+=a[i];
}
Arrays.sort(a);
int k=(int)Math.round(4.5*n)-sum;
// System.out.println((int)Math.round(4.5*n)+" "+k+" "+sum);
if(k<=0)
{
System.out.println(0);
}
else
{
int p=0,ans=0;
for(int i=0;i<n;i++)
{
if(a[i]!=5)
{
p+=5-a[i];
if(p>=k){
ans++;
System.out.println(ans);
break;
}
ans++;
}
}
}
}
}
}
|
nlogn
|
924.java
| 0.7 |
// Java implementation of counting the
// inversion using merge sort
class
Test {
/* This method sorts the input array and returns the
number of inversions in the array */
static
int
mergeSort(
int
arr[],
int
array_size)
{
int
temp[] =
new
int
[array_size];
return
_mergeSort(arr, temp,
0
, array_size -
1
);
}
/* An auxiliary recursive method that sorts the input array and
returns the number of inversions in the array. */
static
int
_mergeSort(
int
arr[],
int
temp[],
int
left,
int
right)
{
int
mid, inv_count =
0
;
if
(right > left) {
/* Divide the array into two parts and call _mergeSortAndCountInv()
for each of the parts */
mid = (right + left) /
2
;
/* Inversion count will be the sum of inversions in left-part, right-part
and number of inversions in merging */
inv_count = _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid +
1
, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid +
1
, right);
}
return
inv_count;
}
/* This method merges two sorted arrays and returns inversion count in
the arrays.*/
static
int
merge(
int
arr[],
int
temp[],
int
left,
int
mid,
int
right)
{
int
i, j, k;
int
inv_count =
0
;
i = left;
/* i is index for left subarray*/
j = mid;
/* j is index for right subarray*/
k = left;
/* k is index for resultant merged subarray*/
while
((i <= mid -
1
) && (j <= right)) {
if
(arr[i] <= arr[j]) {
temp[k++] = arr[i++];
}
else
{
temp[k++] = arr[j++];
/*this is tricky -- see above explanation/diagram for merge()*/
inv_count = inv_count + (mid - i);
}
}
/* Copy the remaining elements of left subarray
(if there are any) to temp*/
while
(i <= mid -
1
)
temp[k++] = arr[i++];
/* Copy the remaining elements of right subarray
(if there are any) to temp*/
while
(j <= right)
temp[k++] = arr[j++];
/*Copy back the merged elements to original array*/
for
(i = left; i <= right; i++)
arr[i] = temp[i];
return
inv_count;
}
// Driver method to test the above function
public
static
void
main(String[] args)
{
int
arr[] =
new
int
[] {
1
,
20
,
6
,
4
,
5
};
System.out.println(
"Number of inversions are "
+ mergeSort(arr,
5
));
}
}
|
nlogn
|
93.java
| 0.7 |
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.Map.*;
public class codeforces {
static int count =0;
static boolean f=false;
static int [] arr;
static PrintWriter pw=new PrintWriter(System.out);
static void solve(int index , int mask) {
if(index==arr.length) {
int sum1=0; int sum2=0;
for(int i=0;i<arr.length;i++) {
if((mask & 1<<i)!=0) sum1+=arr[i];
}
return;
}
solve(index+1, mask | 1<<index);
solve(index+1, mask);
}
public static void main(String [] args) throws IOException, InterruptedException {
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
int y=sc.nextInt();
pair [] arr=new pair[x];
for(int i=0;i<x;i++) arr[i]=new pair(i, sc.nextInt(),0);
for(int i=0;i<x;i++) arr[i].y=sc.nextInt();
Arrays.sort(arr);
PriorityQueue<Integer> qq=new PriorityQueue<>();
//pw.println(Arrays.toString(arr));
Long [] list=new Long [x];
long sum=0;
for(int i=0;i<x;i++) {
pair w=arr[i];
if(qq.size()<y) {
qq.add(w.y);
sum+=w.y;
list[w.i]=sum;
}else if(!qq.isEmpty()) {
sum+=w.y;
list[w.i]=sum;
int first=qq.poll();
if(w.y>first) {
sum-=first;
qq.add(w.y);
}else {
qq.add(first);
sum-=w.y;
}
} else list[w.i]=(long) w.y;
//pw.println(qq);
}
for(Long w:list) pw.print(w+" ");
pw.flush();
pw.close();
}
static class pair implements Comparable<pair>{
String name; int x,y,i ;
public pair(String name , int x) {
this.name=name; this.x=x;
}
public pair (int i,int x,int y) {
this.i=i; this.x=x; this.y=y;
}
public int compareTo(pair o) {
return x-o.x;
}
public int compareTo1(pair o) {
if(!name.equals(o.name))
return name.compareTo(o.name);
return x-o.x;
}
public String toString() {
return i+" "+x+" "+y;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
nlogn
|
930.java
| 0.7 |
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.security.SecureRandom;
public class WCS {
public static class Vector implements Comparable <Vector> {
long x, y;
int position;
Vector first, second;
boolean toReverse;
public Vector(long xx, long yy, int p) {
x = xx;
y = yy;
position = p;
first = null;
second = null;
toReverse = false;
}
public Vector negate() {
Vector vv = new Vector(-x, -y, position);
vv.first = first;
vv.second = second;
vv.toReverse = !toReverse;
return vv;
}
public Vector add(Vector v) {
Vector sum = new Vector(this.x + v.x, this.y + v.y, position);
sum.first = this;
sum.second = v;
return sum;
}
public Vector subtract(Vector v) {
return this.add(v.negate());
}
public double euclideanNorm() {
return Math.sqrt(x * x + y * y);
}
@Override
public int compareTo(Vector v) {
double thisa = Math.atan2(this.y, this.x);
double va = Math.atan2(v.y, v.x);
if(thisa < 0)
thisa += 2 * Math.PI;
if(va < 0)
va += 2 * Math.PI;
if(thisa < va)
return -1;
if(thisa > va)
return 1;
return Integer.compare(this.position, v.position);
}
@Override
public String toString() {
return x + " " + y;
}
}
public static void dfs(Vector curr, int[] ans) {
if(curr.first == null) {
ans[curr.position] = curr.toReverse ? -1 : 1;
return;
}
curr.first.toReverse ^= curr.toReverse;
curr.second.toReverse ^= curr.toReverse;
dfs(curr.first, ans);
dfs(curr.second, ans);
}
public static boolean ok(Vector v1, Vector v2) {
return v1.add(v2).euclideanNorm() <= Math.max(v1.euclideanNorm(), v2.euclideanNorm());
}
public static void stop(long k) {
long time = System.currentTimeMillis();
while(System.currentTimeMillis() - time < k);
}
public static void main(String[] args) throws IOException {
int n = in.nextInt();
TreeSet <Vector> vectors = new TreeSet <> ();
for(int i = 0; i < n; i ++) {
Vector v = new Vector(in.nextLong(), in.nextLong(), i);
vectors.add(v);
}
while(vectors.size() > 2) {
//System.out.println(vectors);
//stop(500);
TreeSet <Vector> support = new TreeSet <> ();
while(vectors.size() > 0) {
Vector curr = vectors.pollFirst();
Vector next1 = vectors.higher(curr);
Vector next2 = vectors.lower(curr.negate());
Vector next3 = vectors.higher(curr.negate());
Vector next4 = vectors.lower(curr);
//System.out.println("CURR: " + curr + "\n" + next1 + "\n" + next2);
if(next1 != null) {
if(ok(curr, next1)) {
support.add(curr.add(next1));
vectors.remove(next1);
continue;
}
}
if(next1 != null) {
if(ok(curr, next1.negate())) {
support.add(curr.subtract(next1));
vectors.remove(next1);
continue;
}
}
if(next2 != null) {
if(ok(curr, next2)) {
support.add(curr.add(next2));
vectors.remove(next2);
continue;
}
}
if(next2 != null) {
if(ok(curr, next2.negate())) {
support.add(curr.subtract(next2));
vectors.remove(next2);
continue;
}
}
if(next3 != null) {
if(ok(curr, next3)) {
support.add(curr.add(next3));
vectors.remove(next3);
continue;
}
}
if(next3 != null) {
if(ok(curr, next3.negate())) {
support.add(curr.subtract(next3));
vectors.remove(next3);
continue;
}
}
if(next4 != null) {
if(ok(curr, next4)) {
support.add(curr.add(next4));
vectors.remove(next4);
continue;
}
}
if(next4 != null) {
if(ok(curr, next4.negate())) {
support.add(curr.subtract(next4));
vectors.remove(next4);
continue;
}
}
support.add(curr);
}
vectors = support;
}
if(vectors.size() == 2) {
Vector curr = vectors.pollFirst();
Vector next = vectors.pollFirst();
Vector add = curr.add(next);
Vector sub = curr.subtract(next);
if(sub.euclideanNorm() <= add.euclideanNorm())
vectors.add(sub);
else
vectors.add(add);
}
//System.out.println(vectors.first().euclideanNorm());
StringBuilder buffer = new StringBuilder();
int[] ans = new int[n];
dfs(vectors.pollFirst(), ans);
for(int i = 0; i < n; i ++)
buffer.append(ans[i] + " ");
System.out.println(buffer);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
BigInteger nextBigInteger() {
return new BigInteger(in.next());
}
int nextInt() {
return Integer.parseInt(next());
}
char nextChar() {
return in.next().charAt(0);
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static FastReader in = new FastReader();
static OutputStream out = new BufferedOutputStream(System.out);
public static byte[] toByte(Object o) {
return String.valueOf(o).getBytes();
}
public static void sop(Object o) {
System.out.print(o);
}
}
|
nlogn
|
934.java
| 0.7 |
import org.omg.PortableServer.AdapterActivator;
import java.io.*;
import java.lang.reflect.Array;
import java.net.CookieHandler;
import java.util.*;
import java.math.*;
import java.lang.*;
import java.util.concurrent.LinkedBlockingDeque;
import static java.lang.Math.*;
public class TaskA implements Runnable {
long m = (int)1e9+7;
PrintWriter w;
InputReader c;
public void run() {
c = new InputReader(System.in);
w = new PrintWriter(System.out);
int n = c.nextInt();
int a[] = scanArrayI(n);
int maxtime = Integer.MAX_VALUE,ind = -1;
for(int i=0;i<n;i++){
int time = Integer.MAX_VALUE;
if(a[i]<i+1)
time = i;
else{
time = (int)ceil((a[i] - i)/(double)n) * n + i;
}
if(time<maxtime){
maxtime = time;
ind = i;
}
}
w.println(ind+1);
w.close();
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void sortbyColumn(int arr[][], int col){
Arrays.sort(arr, new Comparator<int[]>()
{
public int compare(int[] o1, int[] o2){
return(Integer.valueOf(o1[col]).compareTo(o2[col]));
}
});
}
public static class DJSet {
public int[] upper;
public DJSet(int n) {
upper = new int[n];
Arrays.fill(upper, -1);
}
public int root(int x) {
return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
}
public boolean equiv(int x, int y) {
return root(x) == root(y);
}
public boolean union(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (upper[y] < upper[x]) {
int d = x;
x = y;
y = d;
}
upper[x] += upper[y];
upper[y] = x;
}
return x == y;
}
}
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;
}
public void printArray(int[] a){
for(int i=0;i<a.length;i++)
w.print(a[i]+" ");
w.println();
}
public int[] scanArrayI(int n){
int a[] = new int[n];
for(int i=0;i<n;i++)
a[i] = c.nextInt();
return a;
}
public long[] scanArrayL(int n){
long a[] = new long[n];
for(int i=0;i<n;i++)
a[i] = c.nextLong();
return a;
}
public void printArray(long[] a){
for(int i=0;i<a.length;i++)
w.print(a[i]+" ");
w.println();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
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 String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public 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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new TaskA(),"TaskA",1<<26).start();
}
}
|
nlogn
|
936.java
| 0.7 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CoveredPointsCount {
//UPSOLVE
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
long[] myArray = new long[2 * n];
for (int i = 0; i < n; i++) {
StringTokenizer st1 = new StringTokenizer(br.readLine());
myArray[2 * i] = Long.parseLong(st1.nextToken()) * 2;
myArray[2 * i + 1] = Long.parseLong(st1.nextToken()) * 2 + 1;
}
Arrays.sort(myArray);
long[] ans = new long[n + 1];
int cnt = 0;
for (int i = 0; i < 2 * n - 1; i++) {
if (myArray[i] % 2 == 0) cnt++; else cnt--;
ans[cnt] += (myArray[i + 1] + 1) / 2 - (myArray[i] + 1) / 2;
}
StringBuilder answer = new StringBuilder();
for (int i = 1; i < n + 1; i++) {
answer.append(ans[i]);
answer.append(" ");
}
System.out.println(answer);
}
}
|
nlogn
|
945.java
| 0.7 |
import
java.util.*;
import
java.lang.*;
class
Main
{
static
void
minAbsSumPair(
int
arr[],
int
n)
{
// Variables to keep track of current sum and minimum sum
int
sum, min_sum =
999999
;
// left and right index variables
int
l =
0
, r = n-
1
;
// variable to keep track of the left and right pair for min_sum
int
min_l = l, min_r = n-
1
;
/* Array should have at least two elements*/
if
(n <
2
)
{
System.out.println(
"Invalid Input"
);
return
;
}
/* Sort the elements */
sort(arr, l, r);
while
(l < r)
{
sum = arr[l] + arr[r];
/*If abs(sum) is less then update the result items*/
if
(Math.abs(sum) < Math.abs(min_sum))
{
min_sum = sum;
min_l = l;
min_r = r;
}
if
(sum <
0
)
l++;
else
r--;
}
System.out.println(
" The two elements whose "
+
"sum is minimum are "
+
arr[min_l]+
" and "
+arr[min_r]);
}
// main function
public
static
void
main (String[] args)
{
int
arr[] = {
1
,
60
, -
10
,
70
, -
80
,
85
};
int
n = arr.length;
minAbsSumPair(arr, n);
}
/* Functions for QuickSort */
/* This function takes last element as pivot,
places the pivot element at its correct
position in sorted array, and places all
smaller (smaller than pivot) to left of
pivot and all greater elements to right
of pivot */
static
int
partition(
int
arr[],
int
low,
int
high)
{
int
pivot = arr[high];
int
i = (low-
1
);
// index of smaller element
for
(
int
j=low; j<high; j++)
{
// If current element is smaller than or
// equal to pivot
if
(arr[j] <= pivot)
{
i++;
// swap arr[i] and arr[j]
int
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int
temp = arr[i+
1
];
arr[i+
1
] = arr[high];
arr[high] = temp;
return
i+
1
;
}
/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
static
void
sort(
int
arr[],
int
low,
int
high)
{
if
(low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int
pi = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr, low, pi-
1
);
sort(arr, pi+
1
, high);
}
}
}
|
nlogn
|
95.java
| 0.7 |
import sun.reflect.generics.tree.Tree;
import java.io.*;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.util.*;
public class l {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// /////////
//////// /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// /////////
//////// /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static long mod = (int) (1e9 + 7);
static int n;
static StringBuilder sol;
static class pair implements Comparable<pair> {
int L,R;
public pair( int x,int y) {
L=x;R=y;
}
public int compareTo(pair o) {
if (L!=o.L)return L-o.L;
return o.R-R;
}
public String toString(){
return L+" "+R;
}
}
static boolean is;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
//FileWriter f = new FileWriter("C:\\Users\\Ibrahim\\out.txt");
PrintWriter pw = new PrintWriter(System.out);
int m = sc.nextInt();
int n = sc.nextInt();
int q = sc.nextInt();
TreeSet<Integer>length= new TreeSet<>();
length.add(0);
length.add(n);
TreeSet<Integer>width= new TreeSet<>();
width.add(0);
width.add(m);
TreeMap<Integer,Integer>len= new TreeMap<>();
len.put(n,1);
TreeMap<Integer,Integer>wid= new TreeMap<>();
wid.put(m,1);
while (q-->0){
String t= sc.next();
if (t.equals("H")) {
int x = sc.nextInt();
int k1 = length.ceiling(x);
int k2 = length.floor(x);
if (x != k1) {
int s = k1 - k2;
int con = len.get(s);
if (con == 1) len.remove(s);
else len.put(s, con - 1);
len.put((k1 - x), len.getOrDefault((k1 - x), 0) + 1);
len.put((x - k2), len.getOrDefault((x - k2), 0) + 1);
length.add(x);
}
}
else {
int x = sc.nextInt();
int k1 = width.ceiling(x);
int k2 = width.floor(x);
if (x != k1) {
int s = k1 - k2;
//System.out.println(s+" "+k1+" "+k2);
int con = wid.get(s);
if (con == 1) wid.remove(s);
else wid.put(s, con - 1);
wid.put((k1 - x), wid.getOrDefault((k1 - x), 0) + 1);
wid.put((x - k2), wid.getOrDefault((x - k2), 0) + 1);
width.add(x);
}
}
pw.println(1l*len.lastKey()*wid.lastKey());
}
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
nlogn
|
953.java
| 0.7 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] line = reader.readLine().split(" ");
int w = Integer.valueOf(line[0]);
int h = Integer.valueOf(line[1]);
int n = Integer.valueOf(line[2]);
Request[] requests = new Request[n];
for (int i = 0; i < n; i++) {
line = reader.readLine().split(" ");
requests[i] = new Request(line[0], Integer.valueOf(line[1]));
}
for (long e : solve(h, w, requests))
System.out.println(e);
// int w = 200000, h = 200000, n = 400000;
// Request[] requests = generate(w, h, n);
//
// long start = System.currentTimeMillis();
// solve(h, w, requests);
// long end = System.currentTimeMillis();
//
// System.out.println("Time: " + (end - start) + " ms");
}
private static Request[] generate(int w, int h, int n) {
Request[] requests = new Request[n];
Random rnd = new Random();
for (int i = 0; i < n; i++) {
requests[i] = rnd.nextBoolean() ? new Request("V", rnd.nextInt(w)) : new Request("H", rnd.nextInt(h));
}
return requests;
}
private static long[] solve(int h, int w, Request[] requests) {
TreeSet<Integer> hTree = new TreeSet<>();
TreeSet<Integer> wTree = new TreeSet<>();
Queue<CoordinateWithSize> hHeap = new PriorityQueue<>();
Queue<CoordinateWithSize> wHeap = new PriorityQueue<>();
hTree.add(0);
hTree.add(h);
wTree.add(0);
wTree.add(w);
hHeap.add(new CoordinateWithSize(0, h));
wHeap.add(new CoordinateWithSize(0, w));
long[] res = new long[requests.length];
for (int i = 0; i < requests.length; i++) {
Request request = requests[i];
switch (request.type) {
case "H": {
if (!hTree.contains(request.coordinate)) {
int higher = hTree.higher(request.coordinate);
int lower = hTree.lower(request.coordinate);
hHeap.add(new CoordinateWithSize(lower, request.coordinate - lower));
hHeap.add(new CoordinateWithSize(request.coordinate, higher - request.coordinate));
hTree.add(request.coordinate);
}
break;
}
case "V": {
if (!wTree.contains(request.coordinate)) {
int higher = wTree.higher(request.coordinate);
int lower = wTree.lower(request.coordinate);
wHeap.add(new CoordinateWithSize(lower, request.coordinate - lower));
wHeap.add(new CoordinateWithSize(request.coordinate, higher - request.coordinate));
wTree.add(request.coordinate);
}
break;
}
default:
throw new IllegalStateException("Unknown type [type=" + request.type + "]");
}
while (true) {
CoordinateWithSize c = hHeap.peek();
if (hTree.higher(c.coordinate) - c.coordinate == c.size)
break;
hHeap.remove();
}
while (true) {
CoordinateWithSize c = wHeap.peek();
if (wTree.higher(c.coordinate) - c.coordinate == c.size)
break;
wHeap.remove();
}
res[i] = 1L * hHeap.peek().size * wHeap.peek().size;
}
return res;
}
private static class CoordinateWithSize implements Comparable<CoordinateWithSize> {
private final int coordinate;
private final int size;
public CoordinateWithSize(int coordinate, int size) {
this.coordinate = coordinate;
this.size = size;
}
@Override public int compareTo(CoordinateWithSize o) {
return Integer.compare(o.size, size);
}
}
private static class Request {
private final String type;
private final int coordinate;
public Request(String type, int coordinate) {
this.type = type;
this.coordinate = coordinate;
}
}
}
|
nlogn
|
955.java
| 0.7 |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.TreeMap;
import java.util.Map;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Ribhav
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CGlassCarving solver = new CGlassCarving();
solver.solve(1, in, out);
out.close();
}
static class CGlassCarving {
public void solve(int testNumber, FastReader s, PrintWriter out) {
TreeMap<Long, Integer> mapH = new TreeMap<>();
TreeMap<Long, Integer> mapV = new TreeMap<>();
TreeMap<Long, Integer> hDiff = new TreeMap<>();
TreeMap<Long, Integer> vDiff = new TreeMap<>();
long width = s.nextInt();
long height = s.nextInt();
mapH.put(0L, 1);
mapV.put(0L, 1);
mapV.put(width, 1);
mapH.put(height, 1);
vDiff.put(width, 1);
hDiff.put(height, 1);
long maxV = height;
long maxH = width;
int n = s.nextInt();
for (int i = 0; i < n; i++) {
char ch = s.nextCharacter();
long cut = s.nextInt();
if (ch == 'H') {
Long next = mapH.higherKey(cut);
Long prev = mapH.lowerKey(cut);
Long diff = next - prev;
int freq = hDiff.get(diff);
if (freq == 1) {
hDiff.remove(diff);
} else {
hDiff.put(diff, freq - 1);
}
hDiff.put(next - cut, hDiff.getOrDefault(next - cut, 0) + 1);
hDiff.put(cut - prev, hDiff.getOrDefault(cut - prev, 0) + 1);
mapH.put(cut, mapH.getOrDefault(cut, 0) + 1);
} else {
Long next = mapV.higherKey(cut);
Long prev = mapV.lowerKey(cut);
Long diff = next - prev;
int freq = vDiff.get(diff);
if (freq == 1) {
vDiff.remove(diff);
} else {
vDiff.put(diff, freq - 1);
}
vDiff.put(next - cut, vDiff.getOrDefault(next - cut, 0) + 1);
vDiff.put(cut - prev, vDiff.getOrDefault(cut - prev, 0) + 1);
mapV.put(cut, mapV.getOrDefault(cut, 0) + 1);
}
out.println(hDiff.lastKey() * vDiff.lastKey());
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
nlogn
|
956.java
| 0.7 |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static void insert(TreeMap<Integer, Integer>map,int v,int d)
{
if(!map.containsKey(v))map.put(v, 0);
map.put(v, d+map.get(v));
if(map.get(v)==0)map.remove(v);
}
static void cut(TreeSet<Integer> cuts, TreeMap<Integer, Integer>segments,int v)
{
int upper = cuts.higher(v) , lower = cuts.lower(v);
insert(segments, upper-lower, -1);
insert(segments, upper-v, 1);
insert(segments, v-lower, 1);
cuts.add(v);
}
public static void main(String[] args) throws Throwable {
Scanner sc = new Scanner(System.in);
int w = sc.nextInt(), h = sc.nextInt() , n = sc.nextInt();
TreeSet<Integer> vCuts = new TreeSet<>() , hCuts = new TreeSet<>();
TreeMap<Integer, Integer> vSegments = new TreeMap<>() , hSegments = new TreeMap<>();
vCuts.add(0);vCuts.add(w);
hCuts.add(0);hCuts.add(h);
insert(vSegments, w, 1);
insert(hSegments, h, 1);
StringBuilder sb = new StringBuilder();
while(n-->0)
{
if(sc.next().equals("H"))
cut(hCuts, hSegments, sc.nextInt());
else
cut(vCuts, vSegments, sc.nextInt());
sb.append(1l*hSegments.lastKey() * vSegments.lastKey() + "\n");
}
System.out.println(sb);
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String file) throws FileNotFoundException {br = new BufferedReader(new FileReader(file));}
public String next() throws IOException {while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public int[] nexIntArray() throws Throwable {
st = new StringTokenizer(br.readLine());
int[] a = new int[st.countTokens()];
for (int i = 0; i < a.length; i++)a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {return br.ready();}
}
}
|
nlogn
|
957.java
| 0.7 |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author aryssoncf
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, OutputWriter out) {
try {
int n = in.readInt();
int[] x = new int[n], w = new int[n];
in.readIntArrays(x, w);
int[] begin = new int[n], end = new int[n];
Arrays.setAll(begin, i -> x[i] - w[i]);
Arrays.setAll(end, i -> x[i] + w[i]);
int m = ArrayUtils.compress(begin, end).length;
int[] dp = new int[m + 1], order = ArrayUtils.order(end);
int idx = 0;
for (int i = 0; i < m; i++) {
if (i > 0) {
dp[i] = dp[i - 1];
}
while (idx < n && end[order[idx]] == i) {
dp[i] = Math.max(dp[i], dp[begin[order[idx]]] + 1);
idx++;
}
}
int res = dp[m - 1];
out.printLine(res);
} catch (Exception e) {
e.printStackTrace();
}
}
}
static class Sorter {
private static final int INSERTION_THRESHOLD = 16;
private Sorter() {
}
public static void sort(IntList list, IntComparator comparator) {
quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1,
comparator);
}
private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) {
if (to - from < INSERTION_THRESHOLD) {
insertionSort(list, from, to, comparator);
return;
}
if (remaining == 0) {
heapSort(list, from, to, comparator);
return;
}
remaining--;
int pivotIndex = (from + to) >> 1;
int pivot = list.get(pivotIndex);
list.swap(pivotIndex, to);
int storeIndex = from;
int equalIndex = to;
for (int i = from; i < equalIndex; i++) {
int value = comparator.compare(list.get(i), pivot);
if (value < 0) {
list.swap(storeIndex++, i);
} else if (value == 0) {
list.swap(--equalIndex, i--);
}
}
quickSort(list, from, storeIndex - 1, remaining, comparator);
for (int i = equalIndex; i <= to; i++) {
list.swap(storeIndex++, i);
}
quickSort(list, storeIndex, to, remaining, comparator);
}
private static void heapSort(IntList list, int from, int to, IntComparator comparator) {
for (int i = (to + from - 1) >> 1; i >= from; i--) {
siftDown(list, i, to, comparator, from);
}
for (int i = to; i > from; i--) {
list.swap(from, i);
siftDown(list, from, i - 1, comparator, from);
}
}
private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) {
int value = list.get(start);
while (true) {
int child = ((start - delta) << 1) + 1 + delta;
if (child > end) {
return;
}
int childValue = list.get(child);
if (child + 1 <= end) {
int otherValue = list.get(child + 1);
if (comparator.compare(otherValue, childValue) > 0) {
child++;
childValue = otherValue;
}
}
if (comparator.compare(value, childValue) >= 0) {
return;
}
list.swap(start, child);
start = child;
}
}
private static void insertionSort(IntList list, int from, int to, IntComparator comparator) {
for (int i = from + 1; i <= to; i++) {
int value = list.get(i);
for (int j = i - 1; j >= from; j--) {
if (comparator.compare(list.get(j), value) <= 0) {
break;
}
list.swap(j, j + 1);
}
}
}
}
static interface IntList extends IntReversableCollection {
public abstract int get(int index);
public abstract void set(int index, int value);
public abstract void addAt(int index, int value);
public abstract void removeAt(int index);
default public void swap(int first, int second) {
if (first == second) {
return;
}
int temp = get(first);
set(first, get(second));
set(second, temp);
}
default public IntIterator intIterator() {
return new IntIterator() {
private int at;
private boolean removed;
public int value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at++;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at < size();
}
public void remove() {
removeAt(at);
at--;
removed = true;
}
};
}
default public void add(int value) {
addAt(size(), value);
}
default public IntList sort(IntComparator comparator) {
Sorter.sort(this, comparator);
return this;
}
default IntList unique() {
int last = Integer.MIN_VALUE;
IntList result = new IntArrayList();
int size = size();
for (int i = 0; i < size; i++) {
int current = get(i);
if (current != last) {
result.add(current);
last = current;
}
}
return result;
}
default public IntList subList(final int from, final int to) {
return new IntList() {
private final int shift;
private final int size;
{
if (from < 0 || from > to || to > IntList.this.size()) {
throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size());
}
shift = from;
size = to - from;
}
public int size() {
return size;
}
public int get(int at) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size());
}
return IntList.this.get(at + shift);
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int at, int value) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size());
}
IntList.this.set(at + shift, value);
}
public IntList compute() {
return new IntArrayList(this);
}
};
}
}
static interface IntComparator {
IntComparator DEFAULT = Integer::compare;
int compare(int first, int second);
}
static class Range {
public static IntList range(int from, int to) {
int[] result = new int[Math.abs(from - to)];
int current = from;
if (from <= to) {
for (int i = 0; i < result.length; i++) {
result[i] = current++;
}
} else {
for (int i = 0; i < result.length; i++) {
result[i] = current--;
}
}
return new IntArray(result);
}
}
static interface IntReversableCollection extends IntCollection {
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
IntIterator intIterator();
default Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
}
static interface IntCollection extends IntStream {
public int size();
default public void add(int value) {
throw new UnsupportedOperationException();
}
default public int[] toArray() {
int size = size();
int[] array = new int[size];
int i = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
array[i++] = it.value();
}
return array;
}
default public IntCollection addAll(IntStream values) {
for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) {
add(it.value());
}
return this;
}
}
static class IntArray extends IntAbstractStream implements IntList {
private int[] data;
public IntArray(int[] arr) {
data = arr;
}
public int size() {
return data.length;
}
public int get(int at) {
return data[at];
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int index, int value) {
data[index] = value;
}
}
static class ArrayUtils {
public static int[] range(int from, int to) {
return Range.range(from, to).toArray();
}
public static int[] createOrder(int size) {
return range(0, size);
}
public static int[] sort(int[] array, IntComparator comparator) {
return sort(array, 0, array.length, comparator);
}
public static int[] sort(int[] array, int from, int to, IntComparator comparator) {
if (from == 0 && to == array.length) {
new IntArray(array).sort(comparator);
} else {
new IntArray(array).subList(from, to).sort(comparator);
}
return array;
}
public static int[] order(final int[] array) {
return sort(createOrder(array.length), (first, second) -> Integer.compare(array[first], array[second]));
}
public static int[] unique(int[] array) {
return new IntArray(array).unique().toArray();
}
public static int[] compress(int[]... arrays) {
int totalLength = 0;
for (int[] array : arrays) {
totalLength += array.length;
}
int[] all = new int[totalLength];
int delta = 0;
for (int[] array : arrays) {
System.arraycopy(array, 0, all, delta, array.length);
delta += array.length;
}
sort(all, IntComparator.DEFAULT);
all = unique(all);
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++) {
array[i] = Arrays.binarySearch(all, array[i]);
}
}
return all;
}
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
static class IntArrayList extends IntAbstractStream implements IntList {
private int size;
private int[] data;
public IntArrayList() {
this(3);
}
public IntArrayList(int capacity) {
data = new int[capacity];
}
public IntArrayList(IntCollection c) {
this(c.size());
addAll(c);
}
public IntArrayList(IntStream c) {
this();
if (c instanceof IntCollection) {
ensureCapacity(((IntCollection) c).size());
}
addAll(c);
}
public IntArrayList(IntArrayList c) {
size = c.size();
data = c.data.clone();
}
public IntArrayList(int[] arr) {
size = arr.length;
data = arr.clone();
}
public int size() {
return size;
}
public int get(int at) {
if (at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size);
}
return data[at];
}
private void ensureCapacity(int capacity) {
if (data.length >= capacity) {
return;
}
capacity = Math.max(2 * data.length, capacity);
data = Arrays.copyOf(data, capacity);
}
public void addAt(int index, int value) {
ensureCapacity(size + 1);
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size) {
System.arraycopy(data, index, data, index + 1, size - index);
}
data[index] = value;
size++;
}
public void removeAt(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size - 1) {
System.arraycopy(data, index + 1, data, index, size - index - 1);
}
size--;
}
public void set(int index, int value) {
if (index >= size) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
data[index] = value;
}
public int[] toArray() {
return Arrays.copyOf(data, size);
}
}
static abstract class IntAbstractStream implements IntStream {
public String toString() {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
if (first) {
first = false;
} else {
builder.append(' ');
}
builder.append(it.value());
}
return builder.toString();
}
public boolean equals(Object o) {
if (!(o instanceof IntStream)) {
return false;
}
IntStream c = (IntStream) o;
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
if (it.value() != jt.value()) {
return false;
}
it.advance();
jt.advance();
}
return !it.isValid() && !jt.isValid();
}
public int hashCode() {
int result = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
result *= 31;
result += it.value();
}
return result;
}
}
}
|
nlogn
|
958.java
| 0.7 |
import java.util.*;
import java.io.*;
import static java.lang.System.in;
public class Main {
public static void main(String[] args)throws IOException{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] point = new int[n][];
for(int i=0;i<n;i++) point[i] = new int[]{sc.nextInt(),sc.nextInt()};
Arrays.sort(point,(a,b)->((a[0]-a[1])-(b[0]-b[1])));
TreeMap<Integer,Integer> tm = new TreeMap<>();
int ans = 0;
for(int i=n-1;i>=0;i--){
int x = point[i][0], w = point[i][1];
Map.Entry<Integer,Integer> cur = tm.ceilingEntry(x+w);
int curRes;
if(cur==null) curRes = 1;
else curRes = cur.getValue()+1;
ans = Math.max(ans,curRes);
Map.Entry<Integer,Integer> upper = tm.ceilingEntry(x-w);
if(upper==null||upper.getValue()<curRes) tm.put(x-w,curRes);
//Integer key = tm.
}
System.out.println(ans);
}
}
|
nlogn
|
960.java
| 0.7 |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
TaskD.Pair[] p = new TaskD.Pair[n];
for (int i = 0; i < n; ++i) {
p[i] = new TaskD.Pair(in.nextLong(), in.nextLong());
}
Arrays.sort(p);
int last = 0;
int ans = 1;
for (int i = 1; i < n; ++i) {
if (p[i].x - p[i].w >= p[last].x + p[last].w) {
last = i;
++ans;
}
}
out.println(ans);
}
static class Pair implements Comparable<TaskD.Pair> {
long x;
long w;
public Pair(long x, long w) {
this.x = x;
this.w = w;
}
public int compareTo(TaskD.Pair o) {
return Long.compare(x + w, o.x + o.w);
}
public String toString() {
return x + " " + w;
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
nlogn
|
961.java
| 0.7 |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
InputReader.OutputWriter out = new InputReader.OutputWriter(outputStream);
int n = in.nextInt();
int s = in.nextInt();
Lift [] lifts = new Lift[n];
for (int i = 0; i < n; i++) {
lifts[i] = new Lift(in.nextInt(),in.nextInt());
}
Arrays.sort(lifts,(x,y)->y.getLevel() - x.getLevel());
int ans = 0;
for (int i = 0; i < lifts.length; i++) {
Lift current = lifts[i];
ans+=s-current.getLevel();
if(current.getTime()>ans) {
ans+=current.getTime() - ans;
}
s = current.getLevel();
}
ans+=s;
out.println(ans);
out.flush();
}
}
class Lift {
int level;
int time;
public int getLevel() {
return level;
}
public int getTime() {
return time;
}
public Lift(int level, int time) {
this.level = level;
this.time = time;
}
}
class InputReader extends BufferedReader {
StringTokenizer tokenizer;
public InputReader(InputStream inputStream) {
super(new InputStreamReader(inputStream), 32768);
}
public InputReader(String filename) {
super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public Integer nextInt() {
return Integer.valueOf(next());
}
public Long nextLong() {return Long.valueOf(next());}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream outputStream) {
super(outputStream);
}
public OutputWriter(Writer writer) {
super(writer);
}
public OutputWriter(String filename) throws FileNotFoundException {
super(filename);
}
public void close() {
super.close();
}
}
}
|
nlogn
|
964.java
| 0.7 |
import java.io.*;
import java.util.*;
public class Main {
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
static class Pair {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int floor = sc.nextInt();
int time = 0;
Pair[] arr = new Pair[n];
for(int i=0;i<n;i++) arr[i] = new Pair(sc.nextInt(), sc.nextInt());
Arrays.sort(arr, (Pair cur, Pair other) -> (other.a - cur.a));
for(int i=0;i<n;i++) {
time += floor - arr[i].a;
floor = arr[i].a;
time = Math.max(time, arr[i].b);
//pw.println("time: " + time);
}
time += arr[n-1].a;
pw.println(time);
pw.close();
}
}
|
nlogn
|
966.java
| 0.7 |
import java.util.*;
import java.io.*;
import java.math.*;
public class loser
{
static class InputReader {
public BufferedReader br;
public StringTokenizer token;
public InputReader(InputStream stream)
{
br=new BufferedReader(new InputStreamReader(stream),32768);
token=null;
}
public String next()
{
while(token==null || !token.hasMoreTokens())
{
try
{
token=new StringTokenizer(br.readLine());
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
return token.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
static class card{
int l;
int r;
public card(int ch,int i)
{
this.l=ch;
this.r=i;
}
}
static class sort implements Comparator<card>
{
public int compare(card o1,card o2)
{
if(o1.l!=o2.l)
return (int)(o1.l-o2.l);
else
return (int)(o1.r-o2.r);
}
}
static void shuffle(long a[])
{
List<Long> l=new ArrayList<>();
for(int i=0;i<a.length;i++)
l.add(a[i]);
Collections.shuffle(l);
for(int i=0;i<a.length;i++)
a[i]=l.get(i);
}
/*static long gcd(long a,long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
static int ans1=Integer.MAX_VALUE,ans2=Integer.MAX_VALUE,ans3=Integer.MAX_VALUE,ans4=Integer.MAX_VALUE;
static boolean v[]=new boolean[101];
static void dfs(Integer so,Set<Integer> s[]){
if(!v[so.intValue()])
{
v[so]=true;
for(Integer h:s[so.intValue()])
{
if(!v[h.intValue()])
dfs(h,s);
}
}
}
static class Print{
public PrintWriter out;
Print(OutputStream o)
{
out=new PrintWriter(o);
}
}
static int CeilIndex(int A[], int l, int r, int key)
{
while (r - l > 1) {
int m = l + (r - l) / 2;
if (A[m] >= key)
r = m;
else
l = m;
}
return r;
}
static int LongestIncreasingSubsequenceLength(int A[], int size)
{
// Add boundary case, when array size is one
int[] tailTable = new int[size];
int len; // always points empty slot
tailTable[0] = A[0];
len = 1;
for (int i = 1; i < size; i++) {
if (A[i] < tailTable[0])
// new smallest value
tailTable[0] = A[i];
else if (A[i] > tailTable[len - 1])
// A[i] wants to extend largest subsequence
tailTable[len++] = A[i];
else
// A[i] wants to be current end candidate of an existing
// subsequence. It will replace ceil value in tailTable
tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i];
}
return len;
}*/
/*static int binary(int n)
{
int s=1;
while(n>0)
{
s=s<<1;
n--;
}
return s-1;
}
static StringBuilder bin(int i,int n)
{
StringBuilder s=new StringBuilder();
while(i>0)
{
s.append(i%2);
i=i/2;
}
while(s.length()!=n)
{
s.append(0);
}
return s.reverse();
}*/
static boolean valid(int i,int j,int n,int m)
{
if(i<n && i>=0 && j<m && j>=0)
return true;
else
return false;
}
public static void main(String[] args)
{
InputReader sc=new InputReader(System.in);
int n=sc.nextInt();
int s=sc.nextInt();
card c[]=new card[n];
for(int i=0;i<n;i++)
{
int x=sc.nextInt();
int y=sc.nextInt();
c[i]=new card(x,y);
}
Arrays.sort(c,new sort());
int time=0;
for(int i=n-1;i>=0;i--)
{
time+=s-c[i].l;
if((c[i].r-time)>0)
time+=c[i].r-time;
s=c[i].l;
}
if(c[0].l!=0)
time+=c[0].l;
System.out.println(time);
}
}
|
nlogn
|
967.java
| 0.7 |
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
public class ChainReaction implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
private class Beacon implements Comparable<Beacon> {
private int position, range, score;
private Beacon(int position, int range) {
this.position = position;
this.range = range;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Beacon o) {
return Integer.compare(this.position, o.position);
}
}
public void solve() {
int n = in.ni();
if (n == 1) {
out.println(0);
return;
}
beacons = new ArrayList<>();
for (int i = 0; i < n; i++) {
beacons.add(new Beacon(in.ni(), in.ni()));
}
beacons.sort(Comparator.naturalOrder());
for (int i = 1; i < n; i++) {
int left = 0, right = i - 1, position = beacons.get(i).position, range = beacons.get(i).range;
int leftmost = i;
while (left <= right) {
int mid = left + (right - left) / 2;
if (position - range <= beacons.get(mid).position) {
leftmost = Math.min(leftmost, mid);
right = mid - 1;
} else {
left = mid + 1;
}
}
beacons.get(i).setScore(i - leftmost);
}
dp = new Integer[n];
int ans = Integer.MAX_VALUE;
for (int i = n - 1; i >= 0; i--) {
ans = Math.min(n - 1 - i + recurse(i), ans);
}
out.println(ans);
}
private List<Beacon> beacons;
private Integer[] dp;
private int recurse(int idx) {
if (idx <= 0) return 0;
if (dp[idx] != null) return dp[idx];
int destroyed = beacons.get(idx).score;
int ans = destroyed + recurse(idx - destroyed - 1);
return dp[idx] = ans;
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (ChainReaction instance = new ChainReaction()) {
instance.solve();
}
}
}
|
nlogn
|
975.java
| 0.7 |
import javafx.util.Pair;
import java.io.*;
import java.util.*;
public class Beacon8 {
public static void main(String[] args) throws IOException {
// int[] arr = {1, 3, 7, 18};
// int bIndex = Arrays.binarySearch(arr, 4);
// System.out.println(bIndex);
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Map<Integer, Integer> beacons = new TreeMap<>();
for (int i = 0; i < n; i++) {
int index = scan.nextInt();
int power = scan.nextInt();
beacons.put(index, power);
}
int[] indicesArr = new int[n];
int arrInd = 0;
for (int index : beacons.keySet()) {
indicesArr[arrInd] = index;
arrInd++;
}
// Integer[] indicesArr = ((Integer[])beacons.keySet().toArray());
int[] nDestroys = new int[n];
for (int i = 0; i < n; i++) {
int bIndex = Arrays.binarySearch(indicesArr, indicesArr[i] - beacons.get(indicesArr[i]));
if (bIndex < 0)
bIndex = -(bIndex + 1);
nDestroys[i] = i - bIndex;
}
int[] totalBeacons = new int[n];
int maxBeacons = 1;
totalBeacons[0] = 1;
for (int i = 1; i < n; i++) {
if (nDestroys[i] == 0)
totalBeacons[i] = totalBeacons[i - 1] + 1;
else {
if ((i - nDestroys[i] - 1) >= 0)
totalBeacons[i] = totalBeacons[i - nDestroys[i] - 1] + 1;
else
totalBeacons[i] = 1;
}
// totalBeacons[i] = totalBeacons[i - nDestroys[i]] + 1;
//totalBeacons[i] = i - nDestroys[i] + totalBeacons[i - nDestroys[i]] + 1;
if(totalBeacons[i] > maxBeacons)
maxBeacons = totalBeacons[i];
}
// System.out.println("\ntotalBeacons array");
// for (int i = 0; i < n; i++) {
// System.out.print(totalBeacons[i] + " ");
// }
// if (maxBeacons == -1)
// System.out.println(n);
System.out.println(n - maxBeacons);
}
}
|
nlogn
|
980.java
| 0.7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.