exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k ⌀ | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k ⌀ | difficulty int64 -1 3.5k ⌀ | prob_desc_output_spec stringlengths 17 1.47k ⌀ | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 38dda0a2828dbb7ac3b77826054df0e4 | train_001.jsonl | 1539269400 | There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
public class Main implements Runnable {
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 Main(),"Main",1<<26).start();
}
static long gcd(long a,long b){ if(b==0)return a;return gcd(b,a%b); }
static long modPow(long a,long p,long m){ if(a==1)return 1;long ans=1;while (p>0){ if(p%2==1)ans=(ans*a)%m;a=(a*a)%m;p>>=1; }return ans; }
static long modInv(long a,long m){return modPow(a,m-2,m);}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
int k=sc.nextInt();
int a[]=new int[n];
int min=Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
a[i]=sc.nextInt();
min=Math.min(min,a[i]);
}
long h[]=new long[200001];
for (int i = 0; i <n ; i++) {
h[a[i]]++;
}
for (int i = 200000-1; i >=0 ; i--) {
h[i]+=h[i+1];
}
int i;
i=min;
int ans=0;
// out.println("i "+i);
for (int j = 200000; j >i ;) {
long sum=0;
int p=j;
while (p>i && p>=0 && sum+h[p]<=k){
sum+=h[p];
// out.println(p+" "+sum);
p--;
}
if(p!=i)ans++;
else{
if(sum!=0)ans++;
}
//out.println(p+" "+sum);
j=p;
// out.println(j+" "+i);
}
out.println(ans);
out.close();
}
} | Java | ["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"] | 2 seconds | ["2", "2"] | NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$). | Java 8 | standard input | [
"greedy"
] | 676729309dfbdf4c9d9d7c457a129608 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers. | 1,600 | Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth. | standard output | |
PASSED | 0f85c869b23aeb929fb1909542f250bc | train_001.jsonl | 1539269400 | There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so. | 256 megabytes |
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.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
public class q50 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
HashMap<Long,Long> hm = new HashMap<>();
long x[]= new long [n];
ArrayList<Long> y = new ArrayList<>();
long min =(int)1e9;
for(int i=0;i<n;i++) {
x[i]=sc.nextLong();
if(hm.get(x[i])==null) {
hm.put(x[i],1l);
y.add(x[i]);
min= Math.min(min, x[i]);
}else {
hm.put(x[i],hm.get(x[i])+1);
}
}
// Collections.sort(y);
long before=0;
for(long i=(int)2e5;i>0;i--) {
if(hm.get(i)==null) {
if(before!=0)
hm.put((long)i, before);
}else {
hm.put((long)i,hm.get(i)+before );
// System.out.println(hm.get(i));
before=hm.get(i);
}
}
int c=0;
long last =0;
long lastori=0;
for(int i=(int)2e5;i>0;i--) {
// long cur = y.get(i);
long cur =i;
if(cur==min)
break;
if(hm.get(cur)==null)
continue;
long curfreq = hm.get(cur);
// if(i==y.size()-1)
if(last+curfreq>k) {
c++;
last=curfreq;
}else {
last+=curfreq;
}
// if(i!=y.size()-1)
// if(last+curfreq+lastori>k) {
// c++;
// last=curfreq+lastori;
// }else {
// last+=curfreq+lastori;
// }
//
// lastori+=curfreq;
}
if(last!=0)
c++;
System.out.println(c);
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public Scanner (String file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
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 long nextlong() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
long 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();}
}
}
| Java | ["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"] | 2 seconds | ["2", "2"] | NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$). | Java 8 | standard input | [
"greedy"
] | 676729309dfbdf4c9d9d7c457a129608 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers. | 1,600 | Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth. | standard output | |
PASSED | 55f7141f71dac37a033dadbb54475121 | train_001.jsonl | 1539269400 | There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class first {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int hight[] = new int[n];
for(int i=0;i<n;i++){
hight[i] = in.nextInt();
}
int total = 0;
Arrays.sort(hight);
int same = 1;
int sum = 0;
boolean check = true;
for(int i=0;i<n-1;i++){
if(hight[i]!=hight[i+1]){
check = false;
break;
}
}
if(check){
System.out.println(0);
}else {
for (int i = n - 1; i > 0; i--) {
int temp2 = sum + same * (hight[i] - hight[i - 1]);
if (temp2 > k) {
int temp3 = sum;
for (int j = hight[i]; j > hight[i - 1]; j--) {
temp3 += same;
if (temp3 > k) {
// System.out.println(temp3);
total++;
temp3 = same;
}
}
sum = temp3;
same++;
} else {
sum += same * (hight[i] - hight[i - 1]);
same++;
}
}
System.out.println(total+1);
}
}
} | Java | ["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"] | 2 seconds | ["2", "2"] | NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$). | Java 8 | standard input | [
"greedy"
] | 676729309dfbdf4c9d9d7c457a129608 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers. | 1,600 | Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth. | standard output | |
PASSED | 2d6e2a80e1b550ea530a204f45d52fc8 | train_001.jsonl | 1539269400 | There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Abhas Jain
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.ni();
long k = in.nl();
long[] ar = new long[200002];
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; ++i) {
int curr = in.ni();
ar[curr - 1]++;
min = Math.min(min, curr);
}
for (int i = 200000; i > -1; --i) {
ar[i] = ar[i + 1] + ar[i];
}
long ans = 0;
long curr = 0;
for (int i = 200000; i >= min; --i) {
curr += ar[i];
if (curr >= k) {
ans++;
if (curr != k) curr = ar[i];
else curr = 0;
}
}
if (curr > 0) ans++;
out.print(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int ni() {
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 nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"] | 2 seconds | ["2", "2"] | NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$). | Java 8 | standard input | [
"greedy"
] | 676729309dfbdf4c9d9d7c457a129608 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers. | 1,600 | Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth. | standard output | |
PASSED | a0d5a829c8be8bb2877b4f1f02faafbe | train_001.jsonl | 1539269400 | There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so. | 256 megabytes | import java.util.*;
import java.io.*;
public class third{
public static void main(String[] args)throws IOException {
FastReader in=new FastReader(System.in);
int n=in.nextInt();
int k=in.nextInt();
long arr[]=new long[n];
long t,max;
int i,j;
for(i=0;i<n;i++)
arr[i]=in.nextInt();
Arrays.sort(arr);
for(i=0;i<(n/2);i++)
{
t=arr[i];
arr[i]=arr[n-1-i];
arr[n-1-i]=t;
}
long pre[]=new long[n];
pre[0]=arr[0];
for(i=1;i<n;i++)
pre[i]=pre[i-1]+arr[i];
long x=0,z,sum=0,del=0,count=0,val,temp=0;
int ind;
for(i=n-2;i>=0;i--)
{
if(arr[i+1]!=arr[i])
{
sum=pre[i]-arr[i+1]*(i+1);
break;
}
}
// System.out.println(sum);
outer:
for(i=1;i<n;i++)
{
if(arr[i]!=arr[i-1])
{
z=arr[i-1]-1;
while(z>=arr[i])
{
//System.out.println(i+" "+x+" "+count);
ind=i-1;
val=pre[ind]-(z)*i-del;
//System.out.println(val+" "+temp);
if(val<=k)
{
temp=val;
if(val+del==sum)
{
del+=val;
count++;
break outer;
}
}
else
{
x=temp;
del+=x;
count++;
if(del==sum)
break outer;
val=pre[ind]-z*i-del;
//System.out.println(val+" "+x);
temp=val;
if(val+del==sum)
{
del+=val;
count++;
break outer;
}
}
z--;
}
}
}
System.out.println(count);
}
}
class FastReader {
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c !=10 && c!=13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException{
int c;
for (c = scan(); c <= 32; c = scan());
return (char)c;
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
} | Java | ["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"] | 2 seconds | ["2", "2"] | NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$). | Java 8 | standard input | [
"greedy"
] | 676729309dfbdf4c9d9d7c457a129608 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers. | 1,600 | Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth. | standard output | |
PASSED | 3debd849256d38111bb3febbee7f4338 | train_001.jsonl | 1539269400 | There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so. | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int n = scn.nextInt(), k = scn.nextInt(), nax = (int) 2e5 + 5, max = 0;
long[] arr = new long[nax];
arr[0] = n;
for(int i = 0; i < n; i++) {
int x = scn.nextInt();
max = Math.max(max, x);
arr[x + 1]--;
}
for(int i = 1; i < nax; i++) {
arr[i] += arr[i - 1];
}
int ans = 0;
while(arr[max] != n) {
long sum = 0;
while(arr[max] != n && sum + arr[max] <= k) {
sum += arr[max--];
}
ans++;
}
out.println(ans);
}
void run() throws Exception {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) throws Exception {
new C().run();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
}
} | Java | ["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"] | 2 seconds | ["2", "2"] | NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$). | Java 8 | standard input | [
"greedy"
] | 676729309dfbdf4c9d9d7c457a129608 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers. | 1,600 | Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth. | standard output | |
PASSED | 8565a9294703d5cf916aee92019b003a | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void main(String args[]) throws IOException {
Scan input=new Scan();
StringBuilder ans=new StringBuilder("");
int n=input.scanInt();
int q=input.scanInt();
int arr[]=new int[n];
for(int i=0;i<n;i++) {
arr[i]=input.scanInt();
}
sort(arr,0,arr.length-1);
TreeMap<Integer,Integer> map=new TreeMap<>();
TreeMap<Integer,Integer> gap=new TreeMap<>();
for(int i=0;i<n;i++) {
if(!map.containsKey(arr[i])) {
map.put(arr[i],0);
}
map.replace(arr[i], map.get(arr[i])+1);
}
int total=0;
for(int i=0;i<n-1;i++) {
int diff=arr[i+1]-arr[i];
if(diff==0) {
continue;
}
total+=diff;
if(!gap.containsKey(diff)) {
gap.put(diff, 0);
}
gap.replace(diff, gap.get(diff)+1);
}
if(!gap.isEmpty()) {
ans.append(total-gap.lastKey());
}
else {
ans.append(0);
}
ans.append("\n");
for(int qq=1;qq<=q;qq++) {
int type=input.scanInt();
int ele=input.scanInt();
if(type==0) {
map.replace(ele, map.get(ele)-1);
if(map.get(ele)==0) {
map.remove(ele);
int less=-1,more=-1;
if(map.lowerKey(ele)!=null) {
less=map.lowerKey(ele);
gap.replace(ele-less, gap.get(ele-less)-1);
if(gap.get(ele-less)==0) {
gap.remove(ele-less);
}
total-=ele-less;
}
if(map.higherKey(ele)!=null) {
more=map.higherKey(ele);
gap.replace(more-ele, gap.get(more-ele)-1);
if(gap.get(more-ele)==0) {
gap.remove(more-ele);
}
total-=more-ele;
}
if(less!=-1 && more!=-1) {
if(!gap.containsKey(more-less)) {
gap.put(more-less, 0);
}
gap.replace(more-less, gap.get(more-less)+1);
total+=more-less;
}
}
}
else {
if(!map.containsKey(ele)) {
int less=-1,more=-1;
if(map.lowerKey(ele)!=null) {
less=map.lowerKey(ele);
if(!gap.containsKey(ele-less)) {
gap.put(ele-less, 0);
}
gap.replace(ele-less, gap.get(ele-less)+1);
total+=ele-less;
}
if(map.higherKey(ele)!=null) {
more=map.higherKey(ele);
if(!gap.containsKey(more-ele)) {
gap.put(more-ele, 0);
}
gap.replace(more-ele, gap.get(more-ele)+1);
total+=more-ele;
}
if(less!=-1 && more!=-1) {
gap.replace(more-less, gap.get(more-less)-1);
if(gap.get(more-less)==0) {
gap.remove(more-less);
}
total-=more-less;
}
map.put(ele, 0);
}
map.replace(ele, map.get(ele)+1);
}
if(!gap.isEmpty()) {
ans.append(total-gap.lastKey());
}
else {
ans.append(0);
}
ans.append("\n");
}
System.out.println(ans);
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | dca701525616001f5aca947190c740ab | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.*;
import java.util.*;
public class Codeforces
{
public static void main(String args[])throws Exception
{
BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
String s[]=bu.readLine().split(" ");
int n=Integer.parseInt(s[0]),q=Integer.parseInt(s[1]);
int i;
s=bu.readLine().split(" ");
for(i=0;i<n;i++)
add(Integer.parseInt(s[i]));
sb.append(ans()+"\n");
while(q-->0)
{
s=bu.readLine().split(" ");
int t=Integer.parseInt(s[0]); i=Integer.parseInt(s[1]);
if(t==0) remove(i);
else add(i);
sb.append(ans()+"\n");
}
System.out.print(sb);
}
static TreeMap<Integer,Integer> dc=new TreeMap<>();
static TreeSet<Integer> used=new TreeSet<>();
static void add(int n)
{
if(used.higher(n)!=null && used.lower(n)!=null)
{
int d=used.higher(n)-used.lower(n);
dec(dc,d);
}
used.add(n);
if(used.higher(n)!=null) inc(dc,used.higher(n)-n);
if(used.lower(n)!=null) inc(dc,n-used.lower(n));
}
static void remove(int n)
{
used.remove(n);
if (used.higher(n)!=null) dec(dc, used.higher(n)-n);
if (used.lower(n)!=null) dec(dc, n-used.lower(n));
if (used.higher(n)!=null && used.lower(n)!=null) inc(dc, used.higher(n)-used.lower(n));
}
static int ans()
{
if(used.size()<3) return 0;
int f=used.last()-used.first()-1;
int rem=dc.lastKey()-1;
return f-rem;
}
static void inc(TreeMap<Integer,Integer> m,int k)
{
m.put(k,m.getOrDefault(k,0)+1);
}
static void dec(TreeMap<Integer,Integer> m,int k)
{
if(m.get(k)==1) m.remove(k);
else m.put(k,m.get(k)-1);
}
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | aa77f161536122d1b000c85b307d2399 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SolutionD extends Thread {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
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;
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
}
private static final FastReader scanner = new FastReader();
private static final PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
new Thread(null, new SolutionD(), "Main", 1 << 26).start();
}
public void run() {
int t = 1;
for (int i = 0; i < t; i++) {
solve();
}
out.close();
}
private static void solve() {
int n = scanner.nextInt();
int q = scanner.nextInt();
TreeSet<Integer> a = new TreeSet<>();
TreeMap<Integer, Integer> b = new TreeMap<>();
for (int i = 0; i < n; i++) {
a.add(scanner.nextInt());
}
Integer prev = a.first();
for (int i = 0; i < n; i++) {
Integer next = a.higher(prev);
if (next != null) {
b.putIfAbsent(next - prev, 0);
b.put(next - prev, b.get(next - prev) + 1);
prev = next;
}
}
out.println(getResult(a, b));
for (int i = 0; i < q; i++) {
int ti = scanner.nextInt();
int xi = scanner.nextInt();
Integer lower = a.lower(xi);
Integer higher = a.higher(xi);
if (ti == 0) { //remove tile to coordinate x
a.remove(xi);
if (lower != null) {
removeFromB(b, xi - lower);
}
if (higher != null) {
removeFromB(b, higher - xi);
}
if (lower != null && higher != null) {
addToB(b, higher - lower);
}
} else { //add tile to coordinate x
a.add(xi);
if (higher != null && lower != null) {
removeFromB(b, higher - lower);
addToB(b, xi-lower);
addToB(b, higher - xi);
} else if (higher != null) {
addToB(b, higher - xi);
} else if (lower != null) {
addToB(b, xi - lower);
}
}
out.println(getResult(a, b));
}
}
private static int getResult(TreeSet<Integer> a, TreeMap<Integer, Integer> b) {
if (a.size() <= 2) {
return 0;
}
return a.last() - a.first() - b.lastKey();
}
private static void addToB(TreeMap<Integer, Integer> b, int key) {
b.putIfAbsent(key, 0);
b.put(key, b.get(key) + 1);
}
private static void removeFromB(TreeMap<Integer, Integer> b, int key) {
b.put(key, b.get(key) - 1);
if (b.get(key) == 0) {
b.remove(key);
}
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 7293a328fc81ccd27e47124544c6d07b | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// int tr = sc.nextInt();
// outer: while (tr-- > 0) {
int n = sc.nextInt();
int q=sc.nextInt();
TreeSet<Integer> piles=new TreeSet<>();
TreeMap<Integer,Integer> diff=new TreeMap<>();
for (int i = 0; i < n; i++) {
int val=sc.nextInt();
add(piles,diff,val);
}
System.out.println((piles.isEmpty()?0:piles.last())-
(piles.isEmpty()?0:piles.first())-(diff.isEmpty()?0:diff.lastKey()));
for (int i = 0; i < q; i++) {
int t=sc.nextInt();
int ind=sc.nextInt();
if(t==0)
{
remove(piles,diff,ind);
}
else
{
add(piles,diff,ind);
}
System.out.println((piles.isEmpty()?0:piles.last())-
(piles.isEmpty()?0:piles.first())-(diff.isEmpty()?0:diff.lastKey()));
}
// }
}
private static void add(TreeSet<Integer> piles, TreeMap<Integer, Integer> diff, Integer val) {
int low=-1;
int high=-1;
if(piles.lower(val)!=null)
low=piles.lower(val);
if(piles.higher(val)!=null)
high=piles.higher(val);
if(low!=-1&&high!=-1&&diff.get(high-low)==1)
diff.remove(high-low);
else
if(low!=-1&&high!=-1){
diff.put(high-low, diff.get(high-low)-1);
}
if(piles.lower(val)!=null)
diff.put(val-low, diff.getOrDefault(val-low, 0)+1);
if(high!=-1)
diff.put(high-val, diff.getOrDefault(high-val, 0)+1);
piles.add(val);
}
private static void remove(TreeSet<Integer> piles, TreeMap<Integer, Integer> diff, int val) {
piles.remove(val);
if(piles.lower(val)!=null)
{
if(diff.get(val-piles.lower(val))==1)
diff.remove(val-piles.lower(val));
else
{
diff.put(val-piles.lower(val), diff.get(val-piles.lower(val))-1);
}
}
if(piles.higher(val)!=null)
{
if(diff.get(-val+piles.higher(val))==1)
diff.remove(-val+piles.higher(val));
else
{
diff.put(-val+piles.higher(val), diff.get(-val+piles.higher(val))-1);
}
}
if(piles.lower(val)!=null&&piles.higher(val)!=null)
{
diff.put(piles.higher(val)-piles.lower(val),
diff.getOrDefault(piles.higher(val)-piles.lower(val),0)+1);
}
}
static boolean initialcon;
static boolean firstdfs;
static int max;
static int maxnode;
private static int dfs(boolean[] vis, ArrayList<Integer>[] nodes, int b,int aNode,int curdep,int da) {
int maxdep=1;
for (int child : nodes[b]) {
if(!vis[child])
{
if(child==aNode&&firstdfs)
{
if(curdep<=da)
initialcon=true;
}
maxdep=Math.max(maxdep, dfs(vis, nodes, child, aNode, curdep+1,da));
}
}
return maxdep;
}
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 90f7ed2a15a6e5a7965bee1117c88043 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.util.*;
public class Solution
{
public static void main(String []args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int q = sc.nextInt();
Integer arr[] = new Integer[n];
for(int i = 0 ; i < n ; i++)
{
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
// Hope this works lol
TreeMap<Integer , Integer> point = new TreeMap<Integer,Integer>();
TreeMap<Integer , Integer> diff = new TreeMap<Integer,Integer>();
for(int i = 0 ; i < n-1 ; i++)
{
if(diff.containsKey(arr[i+1]-arr[i]))
diff.replace(arr[i+1]-arr[i] , diff.get(arr[i+1]-arr[i])+1);
else
diff.put(arr[i+1]-arr[i] , 1);
point.put(arr[i],1);
}
point.put(arr[n-1],1);
if(point.size() <= 1)
System.out.println(0);
else
System.out.println(point.lastKey() - point.firstKey()-diff.lastKey());
while(q-- > 0)
{
int t = sc.nextInt();
int x = sc.nextInt();
if(t==0)
{
if(point.lowerKey(x) != null)
{
int dd = x-point.lowerKey(x);
if(diff.get(dd) == 1)
diff.remove(dd);
else
diff.replace(dd,diff.get(dd)-1);
}
if(point.higherKey(x) != null)
{
int dd = point.higherKey(x)-x;
if(diff.get(dd) == 1)
diff.remove(dd);
else
diff.replace(dd,diff.get(dd)-1);
}
if(point.lowerKey(x) != null && point.higherKey(x) != null)
{
int f = point.lowerKey(x);
int r = point.higherKey(x);
if(diff.containsKey(r-f))
diff.replace(r-f , diff.get(r-f)+1);
else
diff.put(r-f,1);
}
point.remove(x);
}
else
{
if(point.lowerKey(x) != null)
{
int dd = x-point.lowerKey(x);
if(diff.containsKey(dd))
diff.replace(dd,diff.get(dd)+1);
else
diff.put(dd,1);
}
if(point.higherKey(x) != null)
{
int dd = point.higherKey(x)-x;
if(diff.containsKey(dd))
diff.replace(dd,diff.get(dd)+1);
else
diff.put(dd,1);
}
if(point.lowerKey(x) != null && point.higherKey(x) != null)
{
int f = point.lowerKey(x);
int r = point.higherKey(x);
if(diff.get(r-f) == 1)
diff.remove(r-f);
else
diff.replace(r-f,diff.get(r-f)-1);
}
point.put(x,1);
}
if(point.size() <= 1)
System.out.println(0);
else
System.out.println(point.lastKey() - point.firstKey()-diff.lastKey());
}
}
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 60f23e61b0ab7cb522f9a03e09a346e5 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author htvu
*/
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);
DTrashProblem solver = new DTrashProblem();
solver.solve(1, in, out);
out.close();
}
static class DTrashProblem {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt(), q = in.nextInt();
TreeSet<Integer> piles = new TreeSet<>();
TreeSet<Pair<Integer, Integer>> gaps = new TreeSet<>();
int pre = 0;
List<Integer> ps = new ArrayList<>();
for (int i = 0; i < n; ++i)
ps.add(in.nextInt());
Collections.sort(ps);
for (int i = 0; i < n; ++i) {
piles.add(ps.get(i));
if (i > 0)
gaps.add(new Pair<>(ps.get(i) - ps.get(i - 1), ps.get(i - 1)));
}
out.println(piles.last() - piles.first() - (gaps.isEmpty() ? 0 : gaps.last().first));
while (q-- > 0) {
int t = in.nextInt(), x = in.nextInt();
if (t == 0) { // remove
Integer before = piles.lower(x);
Integer after = piles.higher(x);
if (before != null) {
gaps.remove(new Pair<>(x - before, before));
}
if (after != null) {
gaps.remove(new Pair<>(after - x, x));
}
if (before != null && after != null) {
gaps.add(new Pair<>(after - before, before));
}
piles.remove(x);
} else { // add
Integer before = piles.lower(x);
Integer after = piles.higher(x);
if (before != null) {
gaps.add(new Pair<>(x - before, before));
}
if (after != null) {
gaps.add(new Pair<>(after - x, x));
}
if (before != null && after != null) {
gaps.remove(new Pair<>(after - before, before));
}
piles.add(x);
}
out.println((piles.isEmpty() ? 0 : piles.last() - piles.first()) - (gaps.isEmpty() ? 0 : gaps.last().first));
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A, B>> {
public A first;
public B second;
public Pair(A a, B b) {
this.first = a;
this.second = b;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof Pair<?, ?>) {
Pair<?, ?> pair = (Pair<?, ?>) o;
return first.equals(pair.first) &&
second.equals(pair.second);
}
return false;
}
public int hashCode() {
return (first == null ? 0 : first.hashCode()) ^
(second == null ? 0 : second.hashCode());
}
public String toString() {
return "{" + first + "," + second + '}';
}
public int compareTo(Pair<A, B> o) {
int c = first.compareTo(o.first);
if (c != 0) return c;
return second.compareTo(o.second);
}
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | e8584b460ec20855ea049144d55da39c | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes |
import java.io.*;
import java.util.*;
public class d
{
public static void print(String str,long val){
System.out.println(str+" "+val);
}
public long gcd(long a, long b) {
if (b==0L) return a;
return gcd(b,a%b);
}
public static void debug(long[][] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.println(Arrays.toString(arr[i]));
}
}
public static void debug(int[][] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.println(Arrays.toString(arr[i]));
}
}
public static void debug(String[] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.println(arr[i]);
}
}
public static void print(int[] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.print(arr[i]+" ");
}
System.out.print('\n');
}
public static void print(Object[] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.print(arr[i]+" ");
}
System.out.print('\n');
}
public static void print(String[] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.print(arr[i]+" ");
}
System.out.print('\n');
}
public static void print(long[] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.print(arr[i]+" ");
}
System.out.print('\n');
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
public FastReader(String path) throws FileNotFoundException {
br = new BufferedReader(new FileReader(path));
}
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;
}
}
public static void main(String[] args) throws IOException {
FastReader s=new FastReader();
int n = s.nextInt();
int q = s.nextInt();
Integer[] arr = new Integer[n];
TreeSet<Integer> set = new TreeSet<>();
TreeSet<pair> gap_diff = new TreeSet<>(new Comparator<pair>() {
@Override
public int compare(pair o1, pair o2) {
int a = Integer.compare(o1.gap,o2.gap);
if(a!=0){
return -1*a;
}
a = Integer.compare(o1.x,o2.x);
return a;
}
});
for(int i=0;i<n;i++){
arr[i] = s.nextInt();
set.add(arr[i]);
}
Arrays.sort(arr);
for(int i=0;i<(n-1);i++){
int diff = arr[i+1]-arr[i];
pair p= new pair(arr[i],diff);
gap_diff.add(p);
}
OutputStream out = new BufferedOutputStream( System.out );
// System.out.println(gap_diff);
// System.out.println(set);
int ans =0;
if(set.size()>=2){
ans = set.last()-set.first()-gap_diff.first().gap;
System.out.println(ans);
}
else {
System.out.println(ans);
}
for(int i=0;i<q;i++){
int t = s.nextInt();
int x = s.nextInt();
if(t==0){
int prev=-1;
int next =-1;
set.remove(x);
if(set.size()==0){
out.write((0+" ").getBytes());
out.write('\n');
continue;
}
if(set.first()<x){
prev = set.lower(x);
}
if(set.last()>x){
next = set.higher(x);
}
if(next!=-1){
gap_diff.remove(new pair(x,next-x));
}
if(prev!=-1){
gap_diff.remove(new pair(prev,x-prev));
if(next!=-1){
gap_diff.add(new pair(prev,next-prev));
}
}
}
else {
int prev =-1;
int next =-1;
if(set.size()==0){
set.add(x);
out.write((0+" ").getBytes());
out.write('\n');
continue;
}
if(set.first()<x){
prev = set.lower(x);
}
if(set.last()>x){
next = set.higher(x);
}
set.add(x);
if(prev!=-1 && next!=-1){
gap_diff.remove(new pair(prev,next-prev));
}
if(prev!=-1){
gap_diff.add(new pair(prev,x-prev));
}
if(next!=-1){
gap_diff.add(new pair(x,next-x));
}
}
// System.out.println(gap_diff);
// System.out.println(set);
if(set.size()>=2){
ans = set.last()-set.first()-gap_diff.first().gap;
out.write((ans+" ").getBytes());
out.write('\n');
}
else {
out.write((0+" ").getBytes());
out.write('\n');
}
}
out.flush();
}
static class pair{
int x;
int gap;
pair(int x,int gap){
this.x = x;
this.gap = gap;
}
@Override
public boolean equals(Object obj) {
pair p = (pair)obj;
return this.x == p.x && this.gap == p.gap;
}
@Override
public String toString() {
return "[ "+this.x+" "+this.gap+" ]";
}
}
// static long solve(){
//
// }
// OutputStream out = new BufferedOutputStream( System.out );
// for(int i=1;i<n;i++){
// out.write((arr[i]+" ").getBytes());
// }
// out.flush();
// long start_time = System.currentTimeMillis();
// long end_time = System.currentTimeMillis();
// System.out.println((end_time - start_time) + "ms");
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | d9ca3b1f44fec2c95eb71bf94ded3921 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.PrintWriter;
import java.io.Writer;
import java.util.*;
public class T4 extends PrintWriter {
public T4() {
super(System.out);
}
public static void main(String[] args) {
T4 t4 = new T4();
t4.main();
t4.flush();
}
public void main() {
Scanner s = new Scanner(System.in);
int n = 1;
for (int i=0;i<n;i++) {
mainPrint(s);
}
// MyAVLTree myAVLTree = new MyAVLTree();
// long time =System.currentTimeMillis();
//
// for(int i=0;i<100000;i++){
// myAVLTree.add(i);
// }
// System.out.println(System.currentTimeMillis()-time);
}
public void mainPrint(Scanner s){
int n = s.nextInt();
int q = s.nextInt();
int[] nums = new int[n];
TreeSet<Integer> treeSet = new TreeSet<>();
int max = 1,min = (int) 1e9;
for(int i=0;i<n;i++){
nums[i] = s.nextInt();
max = Math.max(max,nums[i]);
min = Math.min(min,nums[i]);
treeSet.add(nums[i]);
}
nums = Arrays.stream(nums).boxed().sorted().mapToInt($->$).toArray();
// Queue<Integer> dis = new PriorityQueue<>((i1,i2)->{return i2-i1;});
TreeMap<Integer, Integer> m = new TreeMap<>();
for (int i=0;i<n-1;i++) add(nums[i+1]-nums[i],m);
int peek;
if(n>=2) {
peek = m.lastKey();
println(max - min - peek);
}
else println(0);
// System.out.println(max+" "+min+" "+peek);
boolean delete;
int num;
Integer next,last;
for (int i=0;i<q;i++){
delete = s.nextInt() == 0;
num = s.nextInt();
if(delete){
n--;
next = treeSet.higher(num);
last = treeSet.lower(num);
treeSet.remove(num);
if(next != null) remove(next - num,m);
else if(last != null) max = last;
else max = 1;
if(last != null) remove(num - last,m);
else if(next != null) min = next;
else min = (int) 1e9;
if(next != null && last != null) add(next - last,m);
}else {
n++;
treeSet.add(num);
next = treeSet.higher(num);
last = treeSet.lower(num);
if(next == null ) {
max = num;
if(last != null) add(num - last,m);
else min = num;
}else if (last == null){
min = num;
if(next != null) add(next - num,m);
}else {
remove(next - last,m);
add(num - last,m);
add(next - num,m);
}
}
if(n>=2) {
peek = m.lastKey();
println(max - min - peek);
}else {
println(0);
}
// System.out.println(max+" "+min+" "+peek);
}
}
public static void add(int val,TreeMap<Integer,Integer> m){
m.put(val,m.getOrDefault(val,0)+1);
}
public static void remove(int val,TreeMap<Integer,Integer> m) {
int k = m.get(val) - 1;
if (k == 0)
m.remove(val);
else
m.put(val, k);
}
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 450747ce3fec13dcf0a781f2bef1fef7 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.PrintWriter;
import java.io.Writer;
import java.util.*;
public class T4 extends PrintWriter {
public T4() {
super(System.out);
}
public static void main(String[] args) {
T4 t4 = new T4();
t4.main();
t4.flush();
}
public void main() {
Scanner s = new Scanner(System.in);
int n = 1;
for (int i=0;i<n;i++) {
mainPrint(s);
}
// MyAVLTree myAVLTree = new MyAVLTree();
// long time =System.currentTimeMillis();
//
// for(int i=0;i<100000;i++){
// myAVLTree.add(i);
// }
// System.out.println(System.currentTimeMillis()-time);
}
public void mainPrint(Scanner s){
int n = s.nextInt();
int q = s.nextInt();
int[] nums = new int[n];
MyAVLTree myAVLTree = new MyAVLTree();
int max = 1,min = (int) 1e9;
for(int i=0;i<n;i++){
nums[i] = s.nextInt();
max = Math.max(max,nums[i]);
min = Math.min(min,nums[i]);
myAVLTree.add(nums[i]);
}
nums = Arrays.stream(nums).boxed().sorted().mapToInt($->$).toArray();
// Queue<Integer> dis = new PriorityQueue<>((i1,i2)->{return i2-i1;});
TreeMap<Integer, Integer> m = new TreeMap<>();
for (int i=0;i<n-1;i++) add(nums[i+1]-nums[i],m);
int peek;
if(n>=2) {
peek = m.lastKey();
println(max - min - peek);
}
else println(0);
// System.out.println(max+" "+min+" "+peek);
boolean delete;
int num;
int next,last;
for (int i=0;i<q;i++){
delete = s.nextInt() == 0;
num = s.nextInt();
if(delete){
n--;
next = myAVLTree.queryNext(num);
last = myAVLTree.queryLast(num);
myAVLTree.delete(num);
if(next != Integer.MAX_VALUE) remove(next - num,m);
else if(last != Integer.MIN_VALUE) max = last;
else max = 1;
if(last != Integer.MIN_VALUE) remove(num - last,m);
else if(next != Integer.MAX_VALUE) min = next;
else min = (int) 1e9;
if(next != Integer.MAX_VALUE && last != Integer.MIN_VALUE) add(next - last,m);
}else {
n++;
myAVLTree.add(num);
next = myAVLTree.queryNext(num);
last = myAVLTree.queryLast(num);
if(next == Integer.MAX_VALUE ) {
max = num;
if(last != Integer.MIN_VALUE) add(num - last,m);
else min = num;
}else if (last == Integer.MIN_VALUE){
min = num;
if(next != Integer.MAX_VALUE) add(next - num,m);
}else {
remove(next - last,m);
add(num - last,m);
add(next - num,m);
}
}
if(n>=2) {
peek = m.lastKey();
println(max - min - peek);
}else {
println(0);
}
// System.out.println(max+" "+min+" "+peek);
}
}
public static void add(int val,TreeMap<Integer,Integer> m){
m.put(val,m.getOrDefault(val,0)+1);
}
public static void remove(int val,TreeMap<Integer,Integer> m) {
int k = m.get(val) - 1;
if (k == 0)
m.remove(val);
else
m.put(val, k);
}
}
class MyAVLTree {
private static class AVLTreeNode{
int val;
int height;
AVLTreeNode left;
AVLTreeNode right;
AVLTreeNode parent;
public AVLTreeNode(int val) {
this.val = val;
}
public AVLTreeNode() {
}
}
AVLTreeNode root;
public boolean query(int val){
return queryNode(val)!=null;
}
public int queryNext(int val){
AVLTreeNode node = queryNode(val);
if(node.right!=null){
AVLTreeNode next = node.right;
while (next.left!=null) next = next.left;
return next.val;
}else if(node.parent != null){
AVLTreeNode parent = node.parent;
AVLTreeNode child = node;
while (parent.left != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.left == child) return parent.val;
else return Integer.MAX_VALUE;
}else {
return Integer.MAX_VALUE;
}
}
public int queryLast(int val){
AVLTreeNode node = queryNode(val);
if(node.left!=null){
AVLTreeNode next = node.left;
while (next.right!=null) next = next.right;
return next.val;
}else if(node.parent != null ){
AVLTreeNode parent = node.parent;
AVLTreeNode child = node;
while (parent.right != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.right == child) return parent.val;
else return Integer.MIN_VALUE;
}else {
return Integer.MIN_VALUE;
}
}
AVLTreeNode queryNode(int val){
AVLTreeNode p = root;
if(p==null) return null;
while (p.val != val){
if(p.val>val && p.left!=null){
p=p.left;
continue;
}else if(p.val<val && p.right!=null){
p=p.right;
continue;
}
return null;
}
return p;
}
private void lRotate(AVLTreeNode node) {
// System.out.println("lRotate");
if(node.right==null){
try {
throw new Exception("right child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
AVLTreeNode nodeNew = node.right;
AVLTreeNode parent = node.parent;
AVLTreeNode a1 = node.left;
AVLTreeNode a2 = nodeNew.left;
AVLTreeNode a3 = nodeNew.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.right = a2;
nodeNew.left = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
countHeight(node);
countHeight(nodeNew);
}
private boolean countHeight(AVLTreeNode node){
int oldH = node.height;
node.height=Math.max(height(node.left),height(node.right))+1;
return oldH == node.height;
}
private void rRotate(AVLTreeNode node){
// System.out.println("rRotate");
if(node.left==null){
try {
throw new Exception("left child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
AVLTreeNode nodeNew = node.left;
AVLTreeNode parent = node.parent;
AVLTreeNode a1 = nodeNew.left;
AVLTreeNode a2 = nodeNew.right;
AVLTreeNode a3 = node.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.left = a2;
nodeNew.right = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
countHeight(node);
countHeight(nodeNew);
}
public void add(int val){
if(root==null) {
root = new AVLTreeNode(val);
return;
}
AVLTreeNode p = root;
while ((p.val>val && p.left!=null) || (p.val<val && p.right!=null)){
if(p.val>val) p = p.left;
else p = p.right;
}
if(p.val>val) {
p.left = new AVLTreeNode(val);
p.left.parent = p;
}else if(p.val<val){
p.right = new AVLTreeNode(val);
p.right.parent = p;
}
balance(p);
}
private void balance(AVLTreeNode p){
while (p!=null){
int leftHeight = height(p.left),rightHeight = height(p.right);
if(leftHeight-rightHeight>1) {
if(height(p.left.right)-height(p.left.left)==1) {
lRotate(p.left);
}
rRotate(p);
}else if(rightHeight - leftHeight>1){
if(height(p.right.left)-height(p.right.right)==1){
rRotate(p.right);
}
lRotate(p);
}
boolean b = countHeight(p);
if(b) break;
p=p.parent;
}
}
private int height(AVLTreeNode node){
return node==null?-1:node.height;
}
public void delete(int val){
AVLTreeNode node = queryNode(val);
if (node==null){
try {
throw new Exception("the AVLTree don't contain the value");
} catch (Exception e) {
e.printStackTrace();
}
}else {
delete(node);
}
}
private void delete(AVLTreeNode node){
if(node.left==null){
delete1(node);
}else if(node.left.right==null){
delete2(node);
}else {
delete3(node);
}
}
private void delete1(AVLTreeNode node){
AVLTreeNode nodeNew = node.right;
delete(node,nodeNew);
}
private void delete2(AVLTreeNode node){
AVLTreeNode nodeNew = node.left;
AVLTreeNode parent = node.parent;
AVLTreeNode right = node.right;
nodeNew.parent = parent;
nodeNew.right = right;
if(right!=null) right.parent = nodeNew;
if(parent == null) {
root = nodeNew;
nodeNew.parent = null;
} else {
if (parent.left == node) {
parent.left = nodeNew;
}else {
parent.right = nodeNew;
}
}
balance(nodeNew);
}
private void delete3(AVLTreeNode node){
AVLTreeNode p = node.left.right;
while (p.right!=null) p=p.right;
node.val = p.val;
delete(p,p.left);
}
private void delete(AVLTreeNode node,AVLTreeNode nodeNew){
AVLTreeNode parent = node.parent;
if(nodeNew != null) nodeNew.parent = parent;
if(parent==null) {
root = nodeNew;
}
else {
if(parent.right == node) parent.right = nodeNew;
else parent.left = nodeNew;
balance(parent);
}
}
@Override
public String toString() {
if(root==null) return "nullVal";
if(root.parent!=null) System.out.println("error");
Queue<AVLTreeNode> q = new LinkedList<>();
Queue<AVLTreeNode> q1 = new LinkedList<>();
q.add(root);
StringBuilder s = new StringBuilder();
boolean flag;
do {
flag = false;
while (!q.isEmpty()) {
AVLTreeNode get = q.poll();
if (get != null && get.parent == null && get != root) System.out.println("error");
if (get != null) {
q1.add(get.left);
q1.add(get.right);
if(get.left!=null || get.right!=null) flag = true;
if((get.left != null && get.left.parent!=get) || (get.right != null && get.right.parent !=get)) System.out.println("error");
s.append(" ").append(get.val);
} else {
q1.add(null);
q1.add(null);
s.append(" null");
}
}
s.append("\n");
q = q1;
q1 = new LinkedList<>();
} while (flag);
return s.toString();
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | ef68aa8cad80b4b10826775061d0239d | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1418D extends PrintWriter {
CF1418D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1418D o = new CF1418D(); o.main(); o.flush();
}
TreeMap<Integer, Integer> m = new TreeMap<>();
void add(int d) {
m.put(d, m.getOrDefault(d, 0) + 1);
}
void remove(int d) {
int k = m.get(d) - 1;
if (k == 0)
m.remove(d);
else
m.put(d, k);
}
void main() {
int n = sc.nextInt();
int q = sc.nextInt();
int[] xx = new int[n];
for (int i = 0; i < n; i++)
xx[i] = sc.nextInt();
xx = Arrays.stream(xx).boxed().sorted().mapToInt($->$).toArray();
TreeSet<Integer> s = new TreeSet<>();
for (int i = 0; i < n; i++) {
s.add(xx[i]);
if (i > 0)
add(xx[i] - xx[i - 1]);
}
println(n <= 2 ? 0 : s.last() - s.first() - m.lastKey());
while (q-- > 0) {
int t = sc.nextInt();
int x = sc.nextInt();
if (t == 0) {
Integer l = s.lower(x), r = s.higher(x);
s.remove(x); n--;
if (l == null && r == null)
;
else if (l == null)
remove(r - x);
else if (r == null)
remove(x - l);
else {
remove(r - x);
remove(x - l);
add(r - l);
}
} else {
Integer l = s.lower(x), r = s.higher(x);
s.add(x); n++;
if (l == null && r == null)
;
else if (l == null)
add(r - x);
else if (r == null)
add(x - l);
else {
add(r - x);
add(x - l);
remove(r - l);
}
}
println(n <= 2 ? 0 : s.last() - s.first() - m.lastKey());
}
}
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 4fae656e82477496b1403ab5e5860672 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.util.*;
public class T4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = 1;
for (int i=0;i<n;i++) {
mainPrint(s);
}
// MyAVLTree myAVLTree = new MyAVLTree();
// long time =System.currentTimeMillis();
//
// for(int i=0;i<100000;i++){
// myAVLTree.add(i);
// }
// System.out.println(System.currentTimeMillis()-time);
}
public static void mainPrint(Scanner s){
int n = s.nextInt();
int q = s.nextInt();
int[] nums = new int[n];
// TreeSet treeSet = new TreeSet();
// MyAVLTree myAVLTree = new MyAVLTree();
MyRBTree myRBTree = new MyRBTree();
int max = 1,min = (int) 1e9;
for(int i=0;i<n;i++){
nums[i] = s.nextInt();
max = Math.max(max,nums[i]);
min = Math.min(min,nums[i]);
myRBTree.add(nums[i]);
}
// Arrays.sort(nums);
nums = Arrays.stream(nums).boxed().sorted().mapToInt($->$).toArray();
// Queue<Integer> dis = new PriorityQueue<>((i1,i2)->{return i2-i1;});
TreeMap<Integer, Integer> m = new TreeMap<>();
for (int i=0;i<n-1;i++) add(nums[i+1]-nums[i],m);
int peek;
if(n>=2) {
peek = m.lastKey();
System.out.println(max - min - peek);
}
else System.out.println(0);
// System.out.println(max+" "+min+" "+peek);
boolean delete;
int num;
int next,last;
for (int i=0;i<q;i++){
delete = s.nextInt() == 0;
num = s.nextInt();
if(delete){
n--;
next = myRBTree.queryNext(num);
last = myRBTree.queryLast(num);
myRBTree.delete(num);
if(next != Integer.MAX_VALUE) remove(next - num,m);
else if(last != Integer.MIN_VALUE) max = last;
else max = 1;
if(last != Integer.MIN_VALUE) remove(num - last,m);
else if(next != Integer.MAX_VALUE) min = next;
else min = (int) 1e9;
if(next != Integer.MAX_VALUE && last != Integer.MIN_VALUE) add(next - last,m);
}else {
n++;
myRBTree.add(num);
next = myRBTree.queryNext(num);
last = myRBTree.queryLast(num);
if(next == Integer.MAX_VALUE ) {
max = num;
if(last != Integer.MIN_VALUE) add(num - last,m);
else min = num;
}else if (last == Integer.MIN_VALUE){
min = num;
if(next != Integer.MAX_VALUE) add(next - num,m);
}else {
remove(next - last,m);
add(num - last,m);
add(next - num,m);
}
}
if(n>=2) {
peek = m.lastKey();
System.out.println(max - min - peek);
}else {
System.out.println(0);
}
// System.out.println(max+" "+min+" "+peek);
}
}
public static void add(int val,TreeMap<Integer,Integer> m){
m.put(val,m.getOrDefault(val,0)+1);
}
public static void remove(int val,TreeMap<Integer,Integer> m) {
int k = m.get(val) - 1;
if (k == 0)
m.remove(val);
else
m.put(val, k);
}
}
class MyAVLTree {
private static class AVLTreeNode{
int val;
int height;
AVLTreeNode left;
AVLTreeNode right;
AVLTreeNode parent;
public AVLTreeNode(int val) {
this.val = val;
}
public AVLTreeNode() {
}
}
AVLTreeNode root;
public boolean query(int val){
return queryNode(val)!=null;
}
public int queryNext(int val){
AVLTreeNode node = queryNode(val);
if(node.right!=null){
AVLTreeNode next = node.right;
while (next.left!=null) next = next.left;
return next.val;
}else if(node.parent != null){
AVLTreeNode parent = node.parent;
AVLTreeNode child = node;
while (parent.left != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.left == child) return parent.val;
else return Integer.MAX_VALUE;
}else {
return Integer.MAX_VALUE;
}
}
public int queryLast(int val){
AVLTreeNode node = queryNode(val);
if(node.left!=null){
AVLTreeNode next = node.left;
while (next.right!=null) next = next.right;
return next.val;
}else if(node.parent != null ){
AVLTreeNode parent = node.parent;
AVLTreeNode child = node;
while (parent.right != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.right == child) return parent.val;
else return Integer.MIN_VALUE;
}else {
return Integer.MIN_VALUE;
}
}
AVLTreeNode queryNode(int val){
AVLTreeNode p = root;
if(p==null) return null;
while (p.val != val){
if(p.val>val && p.left!=null){
p=p.left;
continue;
}else if(p.val<val && p.right!=null){
p=p.right;
continue;
}
return null;
}
return p;
}
private void lRotate(AVLTreeNode node) {
// System.out.println("lRotate");
if(node.right==null){
try {
throw new Exception("right child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
AVLTreeNode nodeNew = node.right;
AVLTreeNode parent = node.parent;
AVLTreeNode a1 = node.left;
AVLTreeNode a2 = nodeNew.left;
AVLTreeNode a3 = nodeNew.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.right = a2;
nodeNew.left = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
countHeight(node);
countHeight(nodeNew);
}
private boolean countHeight(AVLTreeNode node){
int oldH = node.height;
node.height=Math.max(height(node.left),height(node.right))+1;
return oldH == node.height;
}
private void rRotate(AVLTreeNode node){
// System.out.println("rRotate");
if(node.left==null){
try {
throw new Exception("left child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
AVLTreeNode nodeNew = node.left;
AVLTreeNode parent = node.parent;
AVLTreeNode a1 = nodeNew.left;
AVLTreeNode a2 = nodeNew.right;
AVLTreeNode a3 = node.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.left = a2;
nodeNew.right = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
countHeight(node);
countHeight(nodeNew);
}
public void add(int val){
if(root==null) {
root = new AVLTreeNode(val);
return;
}
AVLTreeNode p = root;
while ((p.val>val && p.left!=null) || (p.val<val && p.right!=null)){
if(p.val>val) p = p.left;
else p = p.right;
}
if(p.val>val) {
p.left = new AVLTreeNode(val);
p.left.parent = p;
}else if(p.val<val){
p.right = new AVLTreeNode(val);
p.right.parent = p;
}
balance(p);
}
private void balance(AVLTreeNode p){
while (p!=null){
int leftHeight = height(p.left),rightHeight = height(p.right);
if(leftHeight-rightHeight>1) {
if(height(p.left.right)-height(p.left.left)==1) {
lRotate(p.left);
}
rRotate(p);
}else if(rightHeight - leftHeight>1){
if(height(p.right.left)-height(p.right.right)==1){
rRotate(p.right);
}
lRotate(p);
}
boolean b = countHeight(p);
if(b) break;
p=p.parent;
}
}
private int height(AVLTreeNode node){
return node==null?-1:node.height;
}
public void delete(int val){
AVLTreeNode node = queryNode(val);
if (node==null){
try {
throw new Exception("the AVLTree don't contain the value");
} catch (Exception e) {
e.printStackTrace();
}
}else {
delete(node);
}
}
private void delete(AVLTreeNode node){
if(node.left==null){
delete1(node);
}else if(node.left.right==null){
delete2(node);
}else {
delete3(node);
}
}
private void delete1(AVLTreeNode node){
AVLTreeNode nodeNew = node.right;
delete(node,nodeNew);
}
private void delete2(AVLTreeNode node){
AVLTreeNode nodeNew = node.left;
AVLTreeNode parent = node.parent;
AVLTreeNode right = node.right;
nodeNew.parent = parent;
nodeNew.right = right;
if(right!=null) right.parent = nodeNew;
if(parent == null) {
root = nodeNew;
nodeNew.parent = null;
} else {
if (parent.left == node) {
parent.left = nodeNew;
}else {
parent.right = nodeNew;
}
}
balance(nodeNew);
}
private void delete3(AVLTreeNode node){
AVLTreeNode p = node.left.right;
while (p.right!=null) p=p.right;
node.val = p.val;
delete(p,p.left);
}
private void delete(AVLTreeNode node,AVLTreeNode nodeNew){
AVLTreeNode parent = node.parent;
if(nodeNew != null) nodeNew.parent = parent;
if(parent==null) {
root = nodeNew;
}
else {
if(parent.right == node) parent.right = nodeNew;
else parent.left = nodeNew;
balance(parent);
}
}
@Override
public String toString() {
if(root==null) return "nullVal";
if(root.parent!=null) System.out.println("error");
Queue<AVLTreeNode> q = new LinkedList<>();
Queue<AVLTreeNode> q1 = new LinkedList<>();
q.add(root);
StringBuilder s = new StringBuilder();
boolean flag;
do {
flag = false;
while (!q.isEmpty()) {
AVLTreeNode get = q.poll();
if (get != null && get.parent == null && get != root) System.out.println("error");
if (get != null) {
q1.add(get.left);
q1.add(get.right);
if(get.left!=null || get.right!=null) flag = true;
if((get.left != null && get.left.parent!=get) || (get.right != null && get.right.parent !=get)) System.out.println("error");
s.append(" ").append(get.val);
} else {
q1.add(null);
q1.add(null);
s.append(" null");
}
}
s.append("\n");
q = q1;
q1 = new LinkedList<>();
} while (flag);
return s.toString();
}
}
class MyRBTree {
static class RBTreeNode {
int val;
RBTreeNode left;
RBTreeNode right;
RBTreeNode parent;
boolean red = true;
public RBTreeNode(int val) {
this.val = val;
}
}
RBTreeNode root;
public int queryNext(int val){
RBTreeNode node = queryNode(val);
if(node.right!=null){
RBTreeNode next = node.right;
while (next.left!=null) next = next.left;
return next.val;
}else if(node.parent != null){
RBTreeNode parent = node.parent;
RBTreeNode child = node;
while (parent.left != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.left == child) return parent.val;
else return Integer.MAX_VALUE;
}else {
return Integer.MAX_VALUE;
}
}
public int queryLast(int val){
RBTreeNode node = queryNode(val);
if(node.left!=null){
RBTreeNode next = node.left;
while (next.right!=null) next = next.right;
return next.val;
}else if(node.parent != null ){
RBTreeNode parent = node.parent;
RBTreeNode child = node;
while (parent.right != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.right == child) return parent.val;
else return Integer.MIN_VALUE;
}else {
return Integer.MIN_VALUE;
}
}
public boolean query(int val){
return queryNode(val)!=null;
}
RBTreeNode queryNode(int val){
RBTreeNode p = root;
if(p==null) return null;
while (p.val != val){
if(p.val>val && p.left!=null){
p=p.left;
continue;
}else if(p.val<val && p.right!=null){
p=p.right;
continue;
}
return null;
}
return p;
}
public void add(int val) {
if (query(val)) return;
if (root == null) {
root = new RBTreeNode(val);
root.red = false;
return;
}
RBTreeNode p = root;
while ((p.val > val && p.left != null) || (p.val < val && p.right != null)) {
if (p.val > val) p = p.left;
else p = p.right;
}
if (p.val > val) {
p.left = new RBTreeNode(val);
p.left.parent = p;
if(p.red) insertBalance(p.left);
} else {
p.right = new RBTreeNode(val);
p.right.parent = p;
if(p.red) insertBalance(p.right);
}
}
private void insertBalance(RBTreeNode node){
RBTreeNode parent = node.parent;
RBTreeNode grandParent = parent.parent;
RBTreeNode uncle = grandParent.left == parent ? grandParent.right:grandParent.left;
if(uncle == null || !uncle.red){
balance1(node,parent,grandParent,uncle);
}else {
balance2(node,parent,grandParent,uncle);
}
}
private void balance1(RBTreeNode node,RBTreeNode parent,RBTreeNode grandParent,RBTreeNode uncle){
if(node == parent.left && parent == grandParent.left){
rRotate(grandParent);
grandParent.red = true;
parent.red = false;
}else if(node == parent.right && parent == grandParent.left){
lRotate(parent);
rRotate(grandParent);
grandParent.red = true;
node.red = false;
}else if(node == parent.left && parent == grandParent.right){
rRotate(parent);
lRotate(grandParent);
grandParent.red = true;
node.red = false;
}else {
lRotate(grandParent);
grandParent.red = true;
parent.red = false;
}
}
private void balance2(RBTreeNode node,RBTreeNode parent,RBTreeNode grandParent,RBTreeNode uncle){
grandParent.red = true;
parent.red = false;
uncle.red = false;
if(grandParent == root) grandParent.red = false;
else if(grandParent.parent.red) insertBalance(grandParent);
}
private void lRotate(RBTreeNode node){
if(node.right==null){
try {
throw new Exception("right child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
RBTreeNode nodeNew = node.right;
RBTreeNode parent = node.parent;
RBTreeNode a1 = node.left;
RBTreeNode a2 = nodeNew.left;
RBTreeNode a3 = nodeNew.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.right = a2;
nodeNew.left = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
}
private void rRotate(RBTreeNode node){
if(node.left==null){
try {
throw new Exception("left child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
RBTreeNode nodeNew = node.left;
RBTreeNode parent = node.parent;
RBTreeNode a1 = nodeNew.left;
RBTreeNode a2 = nodeNew.right;
RBTreeNode a3 = node.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.left = a2;
nodeNew.right = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
}
public void delete(int val){
RBTreeNode node = queryNode(val);
if (node==null){
try {
throw new Exception("the RBTree don't contain the value");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
if(node.left == null && node.right == null && node.red){
justDelete(node);
}else if(node.left == null && node.right == null && !node.red){
delete1(node);
}else if(node.left == null){
delete2(node,node.right);
}else if(node.right == null){
delete2(node,node.left);
}else {
delete3(node);
}
}
private void justDelete(RBTreeNode node){
if(node.parent == null) {
root = null;
return;
}
RBTreeNode parent = node.parent;
if(parent.left == node) parent.left = null;
else parent.right = null;
}
private void delete1(RBTreeNode node){
balanceForDelete1(node);
justDelete(node);
}
private void balanceForDelete1(RBTreeNode node){
RBTreeNode parent = node.parent;
if(parent == null) {
return;
}
RBTreeNode brother = parent.left == node ? parent.right:parent.left;
if(!brother.red){
if((brother.left == null || !brother.left.red) && (brother.right == null || !brother.right.red)){
if(!parent.red){
brother.red = true;
balanceForDelete1(parent);
}
else {
brother.red = true;
parent.red = false;
}
}
else {
if(brother==parent.left && brother.left!=null && brother.left.red){
brother.left.red = false;
brother.red = parent.red;
parent.red = false;
rRotate(parent);
}else if(brother==parent.left && brother.right!=null && brother.right.red) {
brother.right.red = false;
brother.red =true;
lRotate(brother);
balanceForDelete1(node);
}else if(brother==parent.right && brother.right!=null && brother.right.red){
brother.right.red = false;
brother.red = parent.red;
parent.red = false;
lRotate(parent);
}else {
brother.left.red =false;
brother.red = true;
rRotate(brother);
balanceForDelete1(node);
}
}
}
else {
if(brother == parent.left){
rRotate(parent);
}
else {
lRotate(parent);
}
parent.red = true;
brother.red = false;
balanceForDelete1(node);
}
}
private void delete2(RBTreeNode node,RBTreeNode newNode){
RBTreeNode parent = node.parent;
if(parent == null){
root = newNode;
}else {
if(parent.left == node) {
parent.left = newNode;
}else {
parent.right = newNode;
}
}
newNode.parent = parent;
newNode.red = false;
}
private void delete3(RBTreeNode node){
RBTreeNode p = node.left;
while (p.right != null) p = p.right;
node.val = p.val;
if(p.left!=null) delete2(p,p.left);
else if(p.red) justDelete(p);
else delete1(p);
}
@Override
public String toString() {
if(root==null) return "nullVal";
if(root.parent!=null) System.out.println("error");
Queue<RBTreeNode> q = new LinkedList<>();
Queue<RBTreeNode> q1 = new LinkedList<>();
q.add(root);
StringBuilder s = new StringBuilder();
boolean flag;
do {
flag = false;
while (!q.isEmpty()) {
RBTreeNode get = q.poll();
if (get != null && get.parent == null && get != root) System.out.println("error");
if (get != null) {
q1.add(get.left);
q1.add(get.right);
if(get.left!=null || get.right!=null) flag = true;
if((get.left != null && get.left.parent!=get) || (get.right != null && get.right.parent !=get)) System.out.println("error");
s.append(" ").append(get.val).append(get.red ? "red":"black");
} else {
q1.add(null);
q1.add(null);
s.append(" null");
}
}
s.append("\n");
q = q1;
q1 = new LinkedList<>();
} while (flag);
return s.toString();
}
}
class MyHeap {
private int[] c = new int[16];
private int size=0;
public void add(int val){
if(size == c.length) grow();
c[size] = val;
up(size++);
}
public int deleteMin(){
int ans = c[0];
c[0] = c[size-1];
down(0);
return ans;
}
private void down(int index){
while ((2*index+1<size && c[index]>c[2*index+1])||(2*index+2<size && c[index]>c[2*index+2])){
if(2*index+2<size && c[index]>c[2*index+2]){
if(c[2*index+2]<c[2*index+1]) {
swap(2 * index + 2, index);
index = 2*index + 2;
}
else {
swap(2 * index + 1, index);
index = 2*index + 1;
}
}else {
swap(2*index+1,index);
index = 2*index + 1;
}
}
}
public int peek(){
return c[0];
}
private void up(int index){
while (c[index]<c[(index-1)/2]) {
swap(index,(index-1)/2);
index = index/2;
}
}
private void swap(int index1,int index2){
c[index1]^=c[index2];
c[index2]^=c[index1];
c[index1]^=c[index2];
}
private void grow() {
if(c.length>Integer.MAX_VALUE>>2) {
try {
throw new Exception("Can't create so large Heap!");
}catch (Exception e){
}
}
int[] newC = new int[c.length<<1];
System.arraycopy(c,0,newC,0,c.length);
c = newC;
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | f7a54cb1a45f956d993e64fad7ab3a17 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.util.*;
public class T4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = 1;
for (int i=0;i<n;i++) {
mainPrint(s);
}
// MyAVLTree myAVLTree = new MyAVLTree();
// long time =System.currentTimeMillis();
//
// for(int i=0;i<100000;i++){
// myAVLTree.add(i);
// }
// System.out.println(System.currentTimeMillis()-time);
}
public static void mainPrint(Scanner s){
int n = s.nextInt();
int q = s.nextInt();
int[] nums = new int[n];
MyRBTree myRBTree = new MyRBTree();
int max = 1,min = (int) 1e9;
for(int i=0;i<n;i++){
nums[i] = s.nextInt();
max = Math.max(max,nums[i]);
min = Math.min(min,nums[i]);
myRBTree.add(nums[i]);
}
nums = Arrays.stream(nums).boxed().sorted().mapToInt($->$).toArray();
// Queue<Integer> dis = new PriorityQueue<>((i1,i2)->{return i2-i1;});
TreeMap<Integer, Integer> m = new TreeMap<>();
for (int i=0;i<n-1;i++) add(nums[i+1]-nums[i],m);
int peek;
if(n>=2) {
peek = m.lastKey();
System.out.println(max - min - peek);
}
else System.out.println(0);
// System.out.println(max+" "+min+" "+peek);
boolean delete;
int num;
int next,last;
for (int i=0;i<q;i++){
delete = s.nextInt() == 0;
num = s.nextInt();
if(delete){
n--;
next = myRBTree.queryNext(num);
last = myRBTree.queryLast(num);
myRBTree.delete(num);
if(next != Integer.MAX_VALUE) remove(next - num,m);
else if(last != Integer.MIN_VALUE) max = last;
else max = 1;
if(last != Integer.MIN_VALUE) remove(num - last,m);
else if(next != Integer.MAX_VALUE) min = next;
else min = (int) 1e9;
if(next != Integer.MAX_VALUE && last != Integer.MIN_VALUE) add(next - last,m);
}else {
n++;
myRBTree.add(num);
next = myRBTree.queryNext(num);
last = myRBTree.queryLast(num);
if(next == Integer.MAX_VALUE ) {
max = num;
if(last != Integer.MIN_VALUE) add(num - last,m);
else min = num;
}else if (last == Integer.MIN_VALUE){
min = num;
if(next != Integer.MAX_VALUE) add(next - num,m);
}else {
remove(next - last,m);
add(num - last,m);
add(next - num,m);
}
}
if(n>=2) {
peek = m.lastKey();
System.out.println(max - min - peek);
}else {
System.out.println(0);
}
// System.out.println(max+" "+min+" "+peek);
}
}
public static void add(int val,TreeMap<Integer,Integer> m){
m.put(val,m.getOrDefault(val,0)+1);
}
public static void remove(int val,TreeMap<Integer,Integer> m) {
int k = m.get(val) - 1;
if (k == 0)
m.remove(val);
else
m.put(val, k);
}
}
class MyAVLTree {
private static class AVLTreeNode{
int val;
int height;
AVLTreeNode left;
AVLTreeNode right;
AVLTreeNode parent;
public AVLTreeNode(int val) {
this.val = val;
}
public AVLTreeNode() {
}
}
AVLTreeNode root;
public boolean query(int val){
return queryNode(val)!=null;
}
public int queryNext(int val){
AVLTreeNode node = queryNode(val);
if(node.right!=null){
AVLTreeNode next = node.right;
while (next.left!=null) next = next.left;
return next.val;
}else if(node.parent != null){
AVLTreeNode parent = node.parent;
AVLTreeNode child = node;
while (parent.left != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.left == child) return parent.val;
else return Integer.MAX_VALUE;
}else {
return Integer.MAX_VALUE;
}
}
public int queryLast(int val){
AVLTreeNode node = queryNode(val);
if(node.left!=null){
AVLTreeNode next = node.left;
while (next.right!=null) next = next.right;
return next.val;
}else if(node.parent != null ){
AVLTreeNode parent = node.parent;
AVLTreeNode child = node;
while (parent.right != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.right == child) return parent.val;
else return Integer.MIN_VALUE;
}else {
return Integer.MIN_VALUE;
}
}
AVLTreeNode queryNode(int val){
AVLTreeNode p = root;
if(p==null) return null;
while (p.val != val){
if(p.val>val && p.left!=null){
p=p.left;
continue;
}else if(p.val<val && p.right!=null){
p=p.right;
continue;
}
return null;
}
return p;
}
private void lRotate(AVLTreeNode node) {
// System.out.println("lRotate");
if(node.right==null){
try {
throw new Exception("right child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
AVLTreeNode nodeNew = node.right;
AVLTreeNode parent = node.parent;
AVLTreeNode a1 = node.left;
AVLTreeNode a2 = nodeNew.left;
AVLTreeNode a3 = nodeNew.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.right = a2;
nodeNew.left = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
countHeight(node);
countHeight(nodeNew);
}
private boolean countHeight(AVLTreeNode node){
int oldH = node.height;
node.height=Math.max(height(node.left),height(node.right))+1;
return oldH == node.height;
}
private void rRotate(AVLTreeNode node){
// System.out.println("rRotate");
if(node.left==null){
try {
throw new Exception("left child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
AVLTreeNode nodeNew = node.left;
AVLTreeNode parent = node.parent;
AVLTreeNode a1 = nodeNew.left;
AVLTreeNode a2 = nodeNew.right;
AVLTreeNode a3 = node.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.left = a2;
nodeNew.right = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
countHeight(node);
countHeight(nodeNew);
}
public void add(int val){
if(root==null) {
root = new AVLTreeNode(val);
return;
}
AVLTreeNode p = root;
while ((p.val>val && p.left!=null) || (p.val<val && p.right!=null)){
if(p.val>val) p = p.left;
else p = p.right;
}
if(p.val>val) {
p.left = new AVLTreeNode(val);
p.left.parent = p;
}else if(p.val<val){
p.right = new AVLTreeNode(val);
p.right.parent = p;
}
balance(p);
}
private void balance(AVLTreeNode p){
while (p!=null){
int leftHeight = height(p.left),rightHeight = height(p.right);
if(leftHeight-rightHeight>1) {
if(height(p.left.right)-height(p.left.left)==1) {
lRotate(p.left);
}
rRotate(p);
}else if(rightHeight - leftHeight>1){
if(height(p.right.left)-height(p.right.right)==1){
rRotate(p.right);
}
lRotate(p);
}
boolean b = countHeight(p);
if(b) break;
p=p.parent;
}
}
private int height(AVLTreeNode node){
return node==null?-1:node.height;
}
public void delete(int val){
AVLTreeNode node = queryNode(val);
if (node==null){
try {
throw new Exception("the AVLTree don't contain the value");
} catch (Exception e) {
e.printStackTrace();
}
}else {
delete(node);
}
}
private void delete(AVLTreeNode node){
if(node.left==null){
delete1(node);
}else if(node.left.right==null){
delete2(node);
}else {
delete3(node);
}
}
private void delete1(AVLTreeNode node){
AVLTreeNode nodeNew = node.right;
delete(node,nodeNew);
}
private void delete2(AVLTreeNode node){
AVLTreeNode nodeNew = node.left;
AVLTreeNode parent = node.parent;
AVLTreeNode right = node.right;
nodeNew.parent = parent;
nodeNew.right = right;
if(right!=null) right.parent = nodeNew;
if(parent == null) {
root = nodeNew;
nodeNew.parent = null;
} else {
if (parent.left == node) {
parent.left = nodeNew;
}else {
parent.right = nodeNew;
}
}
balance(nodeNew);
}
private void delete3(AVLTreeNode node){
AVLTreeNode p = node.left.right;
while (p.right!=null) p=p.right;
node.val = p.val;
delete(p,p.left);
}
private void delete(AVLTreeNode node,AVLTreeNode nodeNew){
AVLTreeNode parent = node.parent;
if(nodeNew != null) nodeNew.parent = parent;
if(parent==null) {
root = nodeNew;
}
else {
if(parent.right == node) parent.right = nodeNew;
else parent.left = nodeNew;
balance(parent);
}
}
@Override
public String toString() {
if(root==null) return "nullVal";
if(root.parent!=null) System.out.println("error");
Queue<AVLTreeNode> q = new LinkedList<>();
Queue<AVLTreeNode> q1 = new LinkedList<>();
q.add(root);
StringBuilder s = new StringBuilder();
boolean flag;
do {
flag = false;
while (!q.isEmpty()) {
AVLTreeNode get = q.poll();
if (get != null && get.parent == null && get != root) System.out.println("error");
if (get != null) {
q1.add(get.left);
q1.add(get.right);
if(get.left!=null || get.right!=null) flag = true;
if((get.left != null && get.left.parent!=get) || (get.right != null && get.right.parent !=get)) System.out.println("error");
s.append(" ").append(get.val);
} else {
q1.add(null);
q1.add(null);
s.append(" null");
}
}
s.append("\n");
q = q1;
q1 = new LinkedList<>();
} while (flag);
return s.toString();
}
}
class MyRBTree {
static class RBTreeNode {
int val;
RBTreeNode left;
RBTreeNode right;
RBTreeNode parent;
boolean red = true;
public RBTreeNode(int val) {
this.val = val;
}
}
RBTreeNode root;
public int queryNext(int val){
RBTreeNode node = queryNode(val);
if(node.right!=null){
RBTreeNode next = node.right;
while (next.left!=null) next = next.left;
return next.val;
}else if(node.parent != null){
RBTreeNode parent = node.parent;
RBTreeNode child = node;
while (parent.left != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.left == child) return parent.val;
else return Integer.MAX_VALUE;
}else {
return Integer.MAX_VALUE;
}
}
public int queryLast(int val){
RBTreeNode node = queryNode(val);
if(node.left!=null){
RBTreeNode next = node.left;
while (next.right!=null) next = next.right;
return next.val;
}else if(node.parent != null ){
RBTreeNode parent = node.parent;
RBTreeNode child = node;
while (parent.right != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.right == child) return parent.val;
else return Integer.MIN_VALUE;
}else {
return Integer.MIN_VALUE;
}
}
public boolean query(int val){
return queryNode(val)!=null;
}
RBTreeNode queryNode(int val){
RBTreeNode p = root;
if(p==null) return null;
while (p.val != val){
if(p.val>val && p.left!=null){
p=p.left;
continue;
}else if(p.val<val && p.right!=null){
p=p.right;
continue;
}
return null;
}
return p;
}
public void add(int val) {
if (query(val)) return;
if (root == null) {
root = new RBTreeNode(val);
root.red = false;
return;
}
RBTreeNode p = root;
while ((p.val > val && p.left != null) || (p.val < val && p.right != null)) {
if (p.val > val) p = p.left;
else p = p.right;
}
if (p.val > val) {
p.left = new RBTreeNode(val);
p.left.parent = p;
if(p.red) insertBalance(p.left);
} else {
p.right = new RBTreeNode(val);
p.right.parent = p;
if(p.red) insertBalance(p.right);
}
}
private void insertBalance(RBTreeNode node){
RBTreeNode parent = node.parent;
RBTreeNode grandParent = parent.parent;
RBTreeNode uncle = grandParent.left == parent ? grandParent.right:grandParent.left;
if(uncle == null || !uncle.red){
balance1(node,parent,grandParent,uncle);
}else {
balance2(node,parent,grandParent,uncle);
}
}
private void balance1(RBTreeNode node,RBTreeNode parent,RBTreeNode grandParent,RBTreeNode uncle){
if(node == parent.left && parent == grandParent.left){
rRotate(grandParent);
grandParent.red = true;
parent.red = false;
}else if(node == parent.right && parent == grandParent.left){
lRotate(parent);
rRotate(grandParent);
grandParent.red = true;
node.red = false;
}else if(node == parent.left && parent == grandParent.right){
rRotate(parent);
lRotate(grandParent);
grandParent.red = true;
node.red = false;
}else {
lRotate(grandParent);
grandParent.red = true;
parent.red = false;
}
}
private void balance2(RBTreeNode node,RBTreeNode parent,RBTreeNode grandParent,RBTreeNode uncle){
grandParent.red = true;
parent.red = false;
uncle.red = false;
if(grandParent == root) grandParent.red = false;
else if(grandParent.parent.red) insertBalance(grandParent);
}
private void lRotate(RBTreeNode node){
if(node.right==null){
try {
throw new Exception("right child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
RBTreeNode nodeNew = node.right;
RBTreeNode parent = node.parent;
RBTreeNode a1 = node.left;
RBTreeNode a2 = nodeNew.left;
RBTreeNode a3 = nodeNew.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.right = a2;
nodeNew.left = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
}
private void rRotate(RBTreeNode node){
if(node.left==null){
try {
throw new Exception("left child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
RBTreeNode nodeNew = node.left;
RBTreeNode parent = node.parent;
RBTreeNode a1 = nodeNew.left;
RBTreeNode a2 = nodeNew.right;
RBTreeNode a3 = node.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.left = a2;
nodeNew.right = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
}
public void delete(int val){
RBTreeNode node = queryNode(val);
if (node==null){
try {
throw new Exception("the RBTree don't contain the value");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
if(node.left == null && node.right == null && node.red){
justDelete(node);
}else if(node.left == null && node.right == null && !node.red){
delete1(node);
}else if(node.left == null){
delete2(node,node.right);
}else if(node.right == null){
delete2(node,node.left);
}else {
delete3(node);
}
}
private void justDelete(RBTreeNode node){
if(node.parent == null) {
root = null;
return;
}
RBTreeNode parent = node.parent;
if(parent.left == node) parent.left = null;
else parent.right = null;
}
private void delete1(RBTreeNode node){
balanceForDelete1(node);
justDelete(node);
}
private void balanceForDelete1(RBTreeNode node){
RBTreeNode parent = node.parent;
if(parent == null) {
return;
}
RBTreeNode brother = parent.left == node ? parent.right:parent.left;
if(!brother.red){
if((brother.left == null || !brother.left.red) && (brother.right == null || !brother.right.red)){
if(!parent.red){
brother.red = true;
balanceForDelete1(parent);
}
else {
brother.red = true;
parent.red = false;
}
}
else {
if(brother==parent.left && brother.left!=null && brother.left.red){
brother.left.red = false;
brother.red = parent.red;
parent.red = false;
rRotate(parent);
}else if(brother==parent.left && brother.right!=null && brother.right.red) {
brother.right.red = false;
brother.red =true;
lRotate(brother);
balanceForDelete1(node);
}else if(brother==parent.right && brother.right!=null && brother.right.red){
brother.right.red = false;
brother.red = parent.red;
parent.red = false;
lRotate(parent);
}else {
brother.left.red =false;
brother.red = true;
rRotate(brother);
balanceForDelete1(node);
}
}
}
else {
if(brother == parent.left){
rRotate(parent);
}
else {
lRotate(parent);
}
parent.red = true;
brother.red = false;
balanceForDelete1(node);
}
}
private void delete2(RBTreeNode node,RBTreeNode newNode){
RBTreeNode parent = node.parent;
if(parent == null){
root = newNode;
}else {
if(parent.left == node) {
parent.left = newNode;
}else {
parent.right = newNode;
}
}
newNode.parent = parent;
newNode.red = false;
}
private void delete3(RBTreeNode node){
RBTreeNode p = node.left;
while (p.right != null) p = p.right;
node.val = p.val;
if(p.left!=null) delete2(p,p.left);
else if(p.red) justDelete(p);
else delete1(p);
}
@Override
public String toString() {
if(root==null) return "nullVal";
if(root.parent!=null) System.out.println("error");
Queue<RBTreeNode> q = new LinkedList<>();
Queue<RBTreeNode> q1 = new LinkedList<>();
q.add(root);
StringBuilder s = new StringBuilder();
boolean flag;
do {
flag = false;
while (!q.isEmpty()) {
RBTreeNode get = q.poll();
if (get != null && get.parent == null && get != root) System.out.println("error");
if (get != null) {
q1.add(get.left);
q1.add(get.right);
if(get.left!=null || get.right!=null) flag = true;
if((get.left != null && get.left.parent!=get) || (get.right != null && get.right.parent !=get)) System.out.println("error");
s.append(" ").append(get.val).append(get.red ? "red":"black");
} else {
q1.add(null);
q1.add(null);
s.append(" null");
}
}
s.append("\n");
q = q1;
q1 = new LinkedList<>();
} while (flag);
return s.toString();
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | a5257de23c49a4cbc66f71358baa8f23 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.PrintWriter;
import java.io.Writer;
import java.util.*;
public class T4 extends PrintWriter {
public T4() {
super(System.out);
}
public static void main(String[] args) {
T4 t4 = new T4();
t4.main();
t4.flush();
}
public void main() {
Scanner s = new Scanner(System.in);
int n = 1;
for (int i=0;i<n;i++) {
mainPrint(s);
}
// MyAVLTree myAVLTree = new MyAVLTree();
// long time =System.currentTimeMillis();
//
// for(int i=0;i<100000;i++){
// myAVLTree.add(i);
// }
// System.out.println(System.currentTimeMillis()-time);
}
public void mainPrint(Scanner s){
int n = s.nextInt();
int q = s.nextInt();
int[] nums = new int[n];
MyRBTree myRBTree = new MyRBTree();
int max = 1,min = (int) 1e9;
for(int i=0;i<n;i++){
nums[i] = s.nextInt();
max = Math.max(max,nums[i]);
min = Math.min(min,nums[i]);
myRBTree.add(nums[i]);
}
nums = Arrays.stream(nums).boxed().sorted().mapToInt($->$).toArray();
// Queue<Integer> dis = new PriorityQueue<>((i1,i2)->{return i2-i1;});
TreeMap<Integer, Integer> m = new TreeMap<>();
for (int i=0;i<n-1;i++) add(nums[i+1]-nums[i],m);
int peek;
if(n>=2) {
peek = m.lastKey();
println(max - min - peek);
}
else println(0);
// System.out.println(max+" "+min+" "+peek);
boolean delete;
int num;
int next,last;
for (int i=0;i<q;i++){
delete = s.nextInt() == 0;
num = s.nextInt();
if(delete){
n--;
next = myRBTree.queryNext(num);
last = myRBTree.queryLast(num);
myRBTree.delete(num);
if(next != Integer.MAX_VALUE) remove(next - num,m);
else if(last != Integer.MIN_VALUE) max = last;
else max = 1;
if(last != Integer.MIN_VALUE) remove(num - last,m);
else if(next != Integer.MAX_VALUE) min = next;
else min = (int) 1e9;
if(next != Integer.MAX_VALUE && last != Integer.MIN_VALUE) add(next - last,m);
}else {
n++;
myRBTree.add(num);
next = myRBTree.queryNext(num);
last = myRBTree.queryLast(num);
if(next == Integer.MAX_VALUE ) {
max = num;
if(last != Integer.MIN_VALUE) add(num - last,m);
else min = num;
}else if (last == Integer.MIN_VALUE){
min = num;
if(next != Integer.MAX_VALUE) add(next - num,m);
}else {
remove(next - last,m);
add(num - last,m);
add(next - num,m);
}
}
if(n>=2) {
peek = m.lastKey();
println(max - min - peek);
}else {
println(0);
}
// System.out.println(max+" "+min+" "+peek);
}
}
public static void add(int val,TreeMap<Integer,Integer> m){
m.put(val,m.getOrDefault(val,0)+1);
}
public static void remove(int val,TreeMap<Integer,Integer> m) {
int k = m.get(val) - 1;
if (k == 0)
m.remove(val);
else
m.put(val, k);
}
}
class MyAVLTree {
private static class AVLTreeNode{
int val;
int height;
AVLTreeNode left;
AVLTreeNode right;
AVLTreeNode parent;
public AVLTreeNode(int val) {
this.val = val;
}
public AVLTreeNode() {
}
}
AVLTreeNode root;
public boolean query(int val){
return queryNode(val)!=null;
}
public int queryNext(int val){
AVLTreeNode node = queryNode(val);
if(node.right!=null){
AVLTreeNode next = node.right;
while (next.left!=null) next = next.left;
return next.val;
}else if(node.parent != null){
AVLTreeNode parent = node.parent;
AVLTreeNode child = node;
while (parent.left != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.left == child) return parent.val;
else return Integer.MAX_VALUE;
}else {
return Integer.MAX_VALUE;
}
}
public int queryLast(int val){
AVLTreeNode node = queryNode(val);
if(node.left!=null){
AVLTreeNode next = node.left;
while (next.right!=null) next = next.right;
return next.val;
}else if(node.parent != null ){
AVLTreeNode parent = node.parent;
AVLTreeNode child = node;
while (parent.right != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.right == child) return parent.val;
else return Integer.MIN_VALUE;
}else {
return Integer.MIN_VALUE;
}
}
AVLTreeNode queryNode(int val){
AVLTreeNode p = root;
if(p==null) return null;
while (p.val != val){
if(p.val>val && p.left!=null){
p=p.left;
continue;
}else if(p.val<val && p.right!=null){
p=p.right;
continue;
}
return null;
}
return p;
}
private void lRotate(AVLTreeNode node) {
// System.out.println("lRotate");
if(node.right==null){
try {
throw new Exception("right child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
AVLTreeNode nodeNew = node.right;
AVLTreeNode parent = node.parent;
AVLTreeNode a1 = node.left;
AVLTreeNode a2 = nodeNew.left;
AVLTreeNode a3 = nodeNew.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.right = a2;
nodeNew.left = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
countHeight(node);
countHeight(nodeNew);
}
private boolean countHeight(AVLTreeNode node){
int oldH = node.height;
node.height=Math.max(height(node.left),height(node.right))+1;
return oldH == node.height;
}
private void rRotate(AVLTreeNode node){
// System.out.println("rRotate");
if(node.left==null){
try {
throw new Exception("left child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
AVLTreeNode nodeNew = node.left;
AVLTreeNode parent = node.parent;
AVLTreeNode a1 = nodeNew.left;
AVLTreeNode a2 = nodeNew.right;
AVLTreeNode a3 = node.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.left = a2;
nodeNew.right = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
countHeight(node);
countHeight(nodeNew);
}
public void add(int val){
if(root==null) {
root = new AVLTreeNode(val);
return;
}
AVLTreeNode p = root;
while ((p.val>val && p.left!=null) || (p.val<val && p.right!=null)){
if(p.val>val) p = p.left;
else p = p.right;
}
if(p.val>val) {
p.left = new AVLTreeNode(val);
p.left.parent = p;
}else if(p.val<val){
p.right = new AVLTreeNode(val);
p.right.parent = p;
}
balance(p);
}
private void balance(AVLTreeNode p){
while (p!=null){
int leftHeight = height(p.left),rightHeight = height(p.right);
if(leftHeight-rightHeight>1) {
if(height(p.left.right)-height(p.left.left)==1) {
lRotate(p.left);
}
rRotate(p);
}else if(rightHeight - leftHeight>1){
if(height(p.right.left)-height(p.right.right)==1){
rRotate(p.right);
}
lRotate(p);
}
boolean b = countHeight(p);
if(b) break;
p=p.parent;
}
}
private int height(AVLTreeNode node){
return node==null?-1:node.height;
}
public void delete(int val){
AVLTreeNode node = queryNode(val);
if (node==null){
try {
throw new Exception("the AVLTree don't contain the value");
} catch (Exception e) {
e.printStackTrace();
}
}else {
delete(node);
}
}
private void delete(AVLTreeNode node){
if(node.left==null){
delete1(node);
}else if(node.left.right==null){
delete2(node);
}else {
delete3(node);
}
}
private void delete1(AVLTreeNode node){
AVLTreeNode nodeNew = node.right;
delete(node,nodeNew);
}
private void delete2(AVLTreeNode node){
AVLTreeNode nodeNew = node.left;
AVLTreeNode parent = node.parent;
AVLTreeNode right = node.right;
nodeNew.parent = parent;
nodeNew.right = right;
if(right!=null) right.parent = nodeNew;
if(parent == null) {
root = nodeNew;
nodeNew.parent = null;
} else {
if (parent.left == node) {
parent.left = nodeNew;
}else {
parent.right = nodeNew;
}
}
balance(nodeNew);
}
private void delete3(AVLTreeNode node){
AVLTreeNode p = node.left.right;
while (p.right!=null) p=p.right;
node.val = p.val;
delete(p,p.left);
}
private void delete(AVLTreeNode node,AVLTreeNode nodeNew){
AVLTreeNode parent = node.parent;
if(nodeNew != null) nodeNew.parent = parent;
if(parent==null) {
root = nodeNew;
}
else {
if(parent.right == node) parent.right = nodeNew;
else parent.left = nodeNew;
balance(parent);
}
}
@Override
public String toString() {
if(root==null) return "nullVal";
if(root.parent!=null) System.out.println("error");
Queue<AVLTreeNode> q = new LinkedList<>();
Queue<AVLTreeNode> q1 = new LinkedList<>();
q.add(root);
StringBuilder s = new StringBuilder();
boolean flag;
do {
flag = false;
while (!q.isEmpty()) {
AVLTreeNode get = q.poll();
if (get != null && get.parent == null && get != root) System.out.println("error");
if (get != null) {
q1.add(get.left);
q1.add(get.right);
if(get.left!=null || get.right!=null) flag = true;
if((get.left != null && get.left.parent!=get) || (get.right != null && get.right.parent !=get)) System.out.println("error");
s.append(" ").append(get.val);
} else {
q1.add(null);
q1.add(null);
s.append(" null");
}
}
s.append("\n");
q = q1;
q1 = new LinkedList<>();
} while (flag);
return s.toString();
}
}
class MyRBTree {
static class RBTreeNode {
int val;
RBTreeNode left;
RBTreeNode right;
RBTreeNode parent;
boolean red = true;
public RBTreeNode(int val) {
this.val = val;
}
}
RBTreeNode root;
public int queryNext(int val){
RBTreeNode node = queryNode(val);
if(node.right!=null){
RBTreeNode next = node.right;
while (next.left!=null) next = next.left;
return next.val;
}else if(node.parent != null){
RBTreeNode parent = node.parent;
RBTreeNode child = node;
while (parent.left != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.left == child) return parent.val;
else return Integer.MAX_VALUE;
}else {
return Integer.MAX_VALUE;
}
}
public int queryLast(int val){
RBTreeNode node = queryNode(val);
if(node.left!=null){
RBTreeNode next = node.left;
while (next.right!=null) next = next.right;
return next.val;
}else if(node.parent != null ){
RBTreeNode parent = node.parent;
RBTreeNode child = node;
while (parent.right != child && parent.parent != null){
child = parent;
parent = parent.parent;
}
if(parent.right == child) return parent.val;
else return Integer.MIN_VALUE;
}else {
return Integer.MIN_VALUE;
}
}
public boolean query(int val){
return queryNode(val)!=null;
}
RBTreeNode queryNode(int val){
RBTreeNode p = root;
if(p==null) return null;
while (p.val != val){
if(p.val>val && p.left!=null){
p=p.left;
continue;
}else if(p.val<val && p.right!=null){
p=p.right;
continue;
}
return null;
}
return p;
}
public void add(int val) {
if (query(val)) return;
if (root == null) {
root = new RBTreeNode(val);
root.red = false;
return;
}
RBTreeNode p = root;
while ((p.val > val && p.left != null) || (p.val < val && p.right != null)) {
if (p.val > val) p = p.left;
else p = p.right;
}
if (p.val > val) {
p.left = new RBTreeNode(val);
p.left.parent = p;
if(p.red) insertBalance(p.left);
} else {
p.right = new RBTreeNode(val);
p.right.parent = p;
if(p.red) insertBalance(p.right);
}
}
private void insertBalance(RBTreeNode node){
RBTreeNode parent = node.parent;
RBTreeNode grandParent = parent.parent;
RBTreeNode uncle = grandParent.left == parent ? grandParent.right:grandParent.left;
if(uncle == null || !uncle.red){
balance1(node,parent,grandParent,uncle);
}else {
balance2(node,parent,grandParent,uncle);
}
}
private void balance1(RBTreeNode node,RBTreeNode parent,RBTreeNode grandParent,RBTreeNode uncle){
if(node == parent.left && parent == grandParent.left){
rRotate(grandParent);
grandParent.red = true;
parent.red = false;
}else if(node == parent.right && parent == grandParent.left){
lRotate(parent);
rRotate(grandParent);
grandParent.red = true;
node.red = false;
}else if(node == parent.left && parent == grandParent.right){
rRotate(parent);
lRotate(grandParent);
grandParent.red = true;
node.red = false;
}else {
lRotate(grandParent);
grandParent.red = true;
parent.red = false;
}
}
private void balance2(RBTreeNode node,RBTreeNode parent,RBTreeNode grandParent,RBTreeNode uncle){
grandParent.red = true;
parent.red = false;
uncle.red = false;
if(grandParent == root) grandParent.red = false;
else if(grandParent.parent.red) insertBalance(grandParent);
}
private void lRotate(RBTreeNode node){
if(node.right==null){
try {
throw new Exception("right child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
RBTreeNode nodeNew = node.right;
RBTreeNode parent = node.parent;
RBTreeNode a1 = node.left;
RBTreeNode a2 = nodeNew.left;
RBTreeNode a3 = nodeNew.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.right = a2;
nodeNew.left = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
}
private void rRotate(RBTreeNode node){
if(node.left==null){
try {
throw new Exception("left child of the Node which lRotate can't be null");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
RBTreeNode nodeNew = node.left;
RBTreeNode parent = node.parent;
RBTreeNode a1 = nodeNew.left;
RBTreeNode a2 = nodeNew.right;
RBTreeNode a3 = node.right;
if(parent==null){
root = nodeNew;
} else {
if(parent.left==node) parent.left=nodeNew;
else parent.right=nodeNew;
}
node.parent = nodeNew;
node.left = a2;
nodeNew.right = node;
nodeNew.parent = parent;
if(a2!=null){
a2.parent = node;
}
}
public void delete(int val){
RBTreeNode node = queryNode(val);
if (node==null){
try {
throw new Exception("the RBTree don't contain the value");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
if(node.left == null && node.right == null && node.red){
justDelete(node);
}else if(node.left == null && node.right == null && !node.red){
delete1(node);
}else if(node.left == null){
delete2(node,node.right);
}else if(node.right == null){
delete2(node,node.left);
}else {
delete3(node);
}
}
private void justDelete(RBTreeNode node){
if(node.parent == null) {
root = null;
return;
}
RBTreeNode parent = node.parent;
if(parent.left == node) parent.left = null;
else parent.right = null;
}
private void delete1(RBTreeNode node){
balanceForDelete1(node);
justDelete(node);
}
private void balanceForDelete1(RBTreeNode node){
RBTreeNode parent = node.parent;
if(parent == null) {
return;
}
RBTreeNode brother = parent.left == node ? parent.right:parent.left;
if(!brother.red){
if((brother.left == null || !brother.left.red) && (brother.right == null || !brother.right.red)){
if(!parent.red){
brother.red = true;
balanceForDelete1(parent);
}
else {
brother.red = true;
parent.red = false;
}
}
else {
if(brother==parent.left && brother.left!=null && brother.left.red){
brother.left.red = false;
brother.red = parent.red;
parent.red = false;
rRotate(parent);
}else if(brother==parent.left && brother.right!=null && brother.right.red) {
brother.right.red = false;
brother.red =true;
lRotate(brother);
balanceForDelete1(node);
}else if(brother==parent.right && brother.right!=null && brother.right.red){
brother.right.red = false;
brother.red = parent.red;
parent.red = false;
lRotate(parent);
}else {
brother.left.red =false;
brother.red = true;
rRotate(brother);
balanceForDelete1(node);
}
}
}
else {
if(brother == parent.left){
rRotate(parent);
}
else {
lRotate(parent);
}
parent.red = true;
brother.red = false;
balanceForDelete1(node);
}
}
private void delete2(RBTreeNode node,RBTreeNode newNode){
RBTreeNode parent = node.parent;
if(parent == null){
root = newNode;
}else {
if(parent.left == node) {
parent.left = newNode;
}else {
parent.right = newNode;
}
}
newNode.parent = parent;
newNode.red = false;
}
private void delete3(RBTreeNode node){
RBTreeNode p = node.left;
while (p.right != null) p = p.right;
node.val = p.val;
if(p.left!=null) delete2(p,p.left);
else if(p.red) justDelete(p);
else delete1(p);
}
@Override
public String toString() {
if(root==null) return "nullVal";
if(root.parent!=null) System.out.println("error");
Queue<RBTreeNode> q = new LinkedList<>();
Queue<RBTreeNode> q1 = new LinkedList<>();
q.add(root);
StringBuilder s = new StringBuilder();
boolean flag;
do {
flag = false;
while (!q.isEmpty()) {
RBTreeNode get = q.poll();
if (get != null && get.parent == null && get != root) System.out.println("error");
if (get != null) {
q1.add(get.left);
q1.add(get.right);
if(get.left!=null || get.right!=null) flag = true;
if((get.left != null && get.left.parent!=get) || (get.right != null && get.right.parent !=get)) System.out.println("error");
s.append(" ").append(get.val).append(get.red ? "red":"black");
} else {
q1.add(null);
q1.add(null);
s.append(" null");
}
}
s.append("\n");
q = q1;
q1 = new LinkedList<>();
} while (flag);
return s.toString();
}
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 01d6f96a5be8dfe59b9182106ca1aee8 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Solve8 {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
new Solve8().solve(pw);
pw.flush();
pw.close();
}
public void solve(PrintWriter pw) throws IOException {
FastReader sc = new FastReader();
int n = sc.nextInt(), q = sc.nextInt();
TreeSet<Integer> ts = new TreeSet();
for (int i = 0; i < n; i++) {
ts.add(sc.nextInt());
}
TreeMap<Integer, Integer> hm = new TreeMap();
int p = ts.first();
for (int i = 0; i < n - 1; i++) {
int x = ts.higher(p);
hm.put(x - p, hm.getOrDefault(x - p, 0) + 1);
p = x;
}
if (ts.size() <= 1) {
pw.println(0);
} else {
pw.println(ts.last() - ts.first() - hm.lastKey());
}
while (q-- > 0) {
int t = sc.nextInt(), x = sc.nextInt();
if (t == 0) {
remove(ts, hm, x);
} else {
add(ts, hm, x);
}
if (ts.size() <= 1) {
pw.println(0);
} else {
pw.println(ts.last() - ts.first() - hm.lastKey());
}
}
}
public void remove(TreeSet<Integer> ts, TreeMap<Integer, Integer> hm, int x) {
Integer l = ts.lower(x), h = ts.higher(x);
if (h != null) {
hm.put(h - x, hm.get(h - x) - 1);
if (hm.get(h - x) == 0) {
hm.remove(h - x);
}
}
if (l != null) {
hm.put(x - l, hm.get(x - l) - 1);
if (hm.get(x - l) == 0) {
hm.remove(x - l);
}
}
if (l != null && h != null) {
hm.put(h - l, hm.getOrDefault(h - l, 0) + 1);
}
ts.remove(x);
}
public void add(TreeSet<Integer> ts, TreeMap<Integer, Integer> hm, int x) {
Integer l = ts.lower(x), h = ts.higher(x);
if (h != null) {
hm.put(h - x, hm.getOrDefault(h - x, 0) + 1);
}
if (l != null) {
hm.put(x - l, hm.getOrDefault(x - l, 0) + 1);
}
if (l != null && h != null) {
hm.put(h - l, hm.get(h - l) - 1);
if (hm.get(h - l) == 0) {
hm.remove(h - l);
}
}
ts.add(x);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
}
}
public String next() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
}
}
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() {
try {
return br.readLine();
} catch (Exception e) {
}
return null;
}
public boolean hasNext() throws IOException {
if (st != null && st.hasMoreTokens()) {
return true;
}
String s = br.readLine();
if (s == null || s.isEmpty()) {
return false;
}
st = new StringTokenizer(s);
return true;
}
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | c861c119f2d77080ab1d359b4e1be43f | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
int MAX = (int) 1e5, MOD = (int)1e9+7;
void solve(int TC) {
int n = ni(), q = ni();
TreeSet<Integer> P = new TreeSet<>();
TreeSet<int[]> gap = new TreeSet<>(new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if(a[1]-a[0] != b[1]-b[0]) return (a[1] - a[0]) - (b[1] - b[0]);
else if(a[0]!=b[0]) return a[0]-b[0];
return a[1]-b[1];
}
});
int last = 0;
for(int i=0;i<n;i++) P.add(ni());
for(int i: P) {
if(last != 0) {
int[] x = new int[] {last, i};
gap.add(x);
}
last = i;
}
int left,right,t,x,ans=0;
int[] tmp;
if(gap.isEmpty()) pn(0);
else {
tmp = gap.last();
ans = tmp[0] - P.first() + P.last() - tmp[1];
pn(ans);
}
while(q-->0) {
t = ni(); x = ni();
if(t == 0) {
left = x; right = x;
if(P.floor(x-1) != null) left = P.floor(x-1);
if(P.ceiling(x+1) != null) right = P.ceiling(x+1);
P.remove(x);
if(left!=x && right!=x) {
tmp = new int[] {x, right};
gap.remove(tmp);
tmp = new int[] {left, x};
gap.remove(tmp);
tmp = new int[] {left, right};
gap.add(tmp);
}
else if(right != x) {
tmp = new int[] {x, right};
gap.remove(tmp);
}
else if(left != x) {
tmp = new int[] {left, x};
gap.remove(tmp);
}
}
else {
left = x;
right = x;
if(P.floor(x)!=null) left = P.floor(x);
if(P.ceiling(x)!=null) right = P.ceiling(x);
if(left!=x && right!=x) {
tmp = new int[] {left, right};
gap.remove(tmp);
gap.add(new int[] {left, x});
gap.add(new int[] {x, right});
}
else if(right!=x) {
gap.add(new int[] {x, right});
}
else if(left!=x) {
gap.add(new int[] {left, x});
}
P.add(x);
}
if(gap.isEmpty()) {
pn(0);
continue;
}
tmp = gap.last();
left = P.first();
right = P.last();
ans = tmp[0] - left + right - tmp[1];
pn(ans);
}
}
boolean TestCases = false;
public static void main(String[] args) throws Exception { new Main().run(); }
long pow(long a, long b) {
if(b==0 || a==1) return 1;
long o = 1;
for(long p = b; p > 0; p>>=1) {
if((p&1)==1) o = (o*a) % MOD;
a = (a*a) % MOD;
} return o;
}
long inv(long x) {
long o = 1;
for(long p = MOD-2; p > 0; p>>=1) {
if((p&1)==1)o = (o*x)%MOD;
x = (x*x)%MOD;
} return o;
}
long gcd(long a, long b) { return (b==0) ? a : gcd(b,a%b); }
int gcd(int a, int b) { return (b==0) ? a : gcd(b,a%b); }
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
int T = TestCases ? ni() : 1;
for(int t=1;t<=T;t++) solve(t);
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
void p(Object o) { out.print(o); }
void pn(Object o) { out.println(o); }
void pni(Object o) { out.println(o);out.flush(); }
double PI = 3.141592653589793238462643383279502884197169399;
int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-') {
minus = true;
b = readByte();
}
while(true) {
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-') {
minus = true;
b = readByte();
}
while(true) {
if(b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
double nd() { return Double.parseDouble(ns()); }
char nc() { return (char)skip(); }
int BUF_SIZE = 1024 * 8;
byte[] inbuf = new byte[BUF_SIZE];
int lenbuf = 0, ptrbuf = 0;
int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
} return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))) {
sb.appendCodePoint(b); b = readByte();
} return sb.toString();
}
char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
} return n == p ? buf : Arrays.copyOf(buf, p);
}
void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 3bea95a51a29ddb0b368e474a349a39f | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
int MAX = (int) 1e5, MOD = (int)1e9+7;
void solve(int TC) {
int n = ni(), q = ni();
TreeSet<Integer> P = new TreeSet<>();
TreeSet<int[]> gap = new TreeSet<>(new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if(a[1]-a[0] != b[1]-b[0]) return (a[1] - a[0]) - (b[1] - b[0]);
else if(a[0]!=b[0]) return a[0] - b[0];
return a[1] - b[1];
}
});
int last = 0;
for(int i=0;i<n;i++) P.add(ni());
for(int i: P) {
if(last != 0) {
int[] x = new int[] {last, i};
gap.add(x);
}
last = i;
}
int left,right,t,x,ans=0;
int[] tmp;
if(gap.isEmpty()) pn(0);
else {
tmp = gap.last();
ans = tmp[0] - P.first() + P.last() - tmp[1];
pn(ans);
}
while(q-->0) {
t = ni(); x = ni();
if(t == 0) {
left = x; right = x;
if(P.floor(x-1) != null) left = P.floor(x-1);
if(P.ceiling(x+1) != null) right = P.ceiling(x+1);
P.remove(x);
if(left != x) gap.remove(new int[] {left, x});
if(right != x) gap.remove(new int[] {x, right});
if(left < x && x < right) gap.add(new int[] {left, right});
}
else {
left = x;
right = x;
if(P.floor(x) != null) left = P.floor(x);
if(P.ceiling(x) != null) right = P.ceiling(x);
if(left != right) gap.remove(new int[] {left, right});
if(left != x) gap.add(new int[] {left, x});
if(right != x) gap.add(new int[] {x, right});
P.add(x);
}
if(gap.isEmpty()) {
pn(0);
continue;
}
tmp = gap.last();
left = P.first();
right = P.last();
ans = tmp[0] - left + right - tmp[1];
pn(ans);
}
}
boolean TestCases = false;
public static void main(String[] args) throws Exception { new Main().run(); }
long pow(long a, long b) {
if(b==0 || a==1) return 1;
long o = 1;
for(long p = b; p > 0; p>>=1) {
if((p&1)==1) o = (o*a) % MOD;
a = (a*a) % MOD;
} return o;
}
long inv(long x) {
long o = 1;
for(long p = MOD-2; p > 0; p>>=1) {
if((p&1)==1)o = (o*x)%MOD;
x = (x*x)%MOD;
} return o;
}
long gcd(long a, long b) { return (b==0) ? a : gcd(b,a%b); }
int gcd(int a, int b) { return (b==0) ? a : gcd(b,a%b); }
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
int T = TestCases ? ni() : 1;
for(int t=1;t<=T;t++) solve(t);
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
void p(Object o) { out.print(o); }
void pn(Object o) { out.println(o); }
void pni(Object o) { out.println(o);out.flush(); }
double PI = 3.141592653589793238462643383279502884197169399;
int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-') {
minus = true;
b = readByte();
}
while(true) {
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-') {
minus = true;
b = readByte();
}
while(true) {
if(b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
double nd() { return Double.parseDouble(ns()); }
char nc() { return (char)skip(); }
int BUF_SIZE = 1024 * 8;
byte[] inbuf = new byte[BUF_SIZE];
int lenbuf = 0, ptrbuf = 0;
int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
} return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))) {
sb.appendCodePoint(b); b = readByte();
} return sb.toString();
}
char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
} return n == p ? buf : Arrays.copyOf(buf, p);
}
void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 08b46d3c16174e3d5148bbb8d95fbb0a | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1418D extends PrintWriter {
CF1418D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1418D o = new CF1418D(); o.main(); o.flush();
}
TreeMap<Integer, Integer> m = new TreeMap<>();
void add(int d) {
m.put(d, m.getOrDefault(d, 0) + 1);
}
void remove(int d) {
int k = m.get(d) - 1;
if (k == 0)
m.remove(d);
else
m.put(d, k);
}
void main() {
int n = sc.nextInt();
int q = sc.nextInt();
int[] xx = new int[n];
for (int i = 0; i < n; i++)
xx[i] = sc.nextInt();
xx = Arrays.stream(xx).boxed().sorted().mapToInt($->$).toArray();
TreeSet<Integer> s = new TreeSet<>();
for (int i = 0; i < n; i++) {
s.add(xx[i]);
if (i > 0)
add(xx[i] - xx[i - 1]);
}
println(n <= 2 ? 0 : s.last() - s.first() - m.lastKey());
while (q-- > 0) {
int t = sc.nextInt();
int x = sc.nextInt();
if (t == 0) {
Integer l = s.lower(x), r = s.higher(x);
s.remove(x); n--;
if (l == null && r == null)
;
else if (l == null)
remove(r - x);
else if (r == null)
remove(x - l);
else {
remove(r - x);
remove(x - l);
add(r - l);
}
} else {
Integer l = s.lower(x), r = s.higher(x);
s.add(x); n++;
if (l == null && r == null)
;
else if (l == null)
add(r - x);
else if (r == null)
add(x - l);
else {
add(r - x);
add(x - l);
remove(r - l);
}
}
println(n <= 2 ? 0 : s.last() - s.first() - m.lastKey());
}
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 68e2e91cca81dc2ee51302a9d14715a9 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
TreeMap<Integer, Integer> cnt = new TreeMap<>();
TreeSet<Integer> visited = new TreeSet<>();
public static void main(String[] args) {
new Main().run();
}
void solve_test(Scanner in, PrintWriter out) {
int n = in.nextInt(), q = in.nextInt();
for (int i = 0; i < n; i++) {
int value = in.nextInt();
insert(value);
}
out.println(getAns());
for (int iq = 0; iq < q; iq++) {
int type = in.nextInt();
int x = in.nextInt();
if (type == 1)
insert(x);
else
remove(x);
out.println(getAns());
}
}
int getAns() {
if (visited.size() < 3)
return 0;
int total = visited.last() - visited.first() - 1;
int maxHole = cnt.lastKey() - 1;
return total - maxHole;
}
void remove(int value) {
visited.remove(value);
if (visited.higher(value) != null)
decrement(visited.higher(value) - value);
if (visited.lower(value) != null)
decrement(value - visited.lower(value));
if (visited.lower(value) != null && visited.higher(value) != null)
increment(visited.higher(value) - visited.lower(value));
}
void insert(int value) {
if (visited.higher(value) != null && visited.lower(value) != null)
decrement(visited.higher(value) - visited.lower(value));
visited.add(value);
if (visited.higher(value) != null)
increment(visited.higher(value) - value);
if (visited.lower(value) != null)
increment(value - visited.lower(value));
}
void increment(int value) {
cnt.put(value, 1 + cnt.getOrDefault(value, 0));
}
void decrement(int value) {
if (cnt.get(value) == 1)
cnt.remove(value);
else
cnt.put(value, cnt.get(value) - 1);
}
void run() {
try (
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out)
) {
solve_test(in, out);
}
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 1d852a962293bc81dc3fd3bfa2e1b2f3 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.util.*;
import java.io.*;
public class D{
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int mod = (int)(1e9+7);
public static long pow(long a,long b)
{
long ans = 1;
while(b> 0)
{
if((b & 1)==1){
ans = (ans*a) % mod;
}
a = (a*a) % mod;
b = b>>1;
}
return ans;
}
static void add(TreeMap<Long,Integer> map,long val)
{
map.put(val,map.getOrDefault(val, 0)+1);
}
static void remove(TreeMap<Long,Integer> map,long val)
{
if(map.get(val)==1)
map.remove(val);
else
map.put(val,map.get(val)-1);
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int n = in.nextInt(),q = in.nextInt();
int[] arr = in.nextIntArray(n);
long sum = 0;
// TreeSet<Long> pq = new TreeSet<>((a,b)->(Long.compare(b, a)));
TreeSet<Long> set = new TreeSet<>();
TreeMap<Long,Integer> map = new TreeMap<>();
for(int x:arr){
set.add((long)x);
}
long prev = set.first();
for(Long x:set)
{
Long diff = (x-prev);
sum+=diff;
add(map,diff);
prev = x;
}
if(set.size()<=1)
out.printLine(0);
else
out.printLine(sum-map.lastKey());
while(q-- >0)
{
int type = in.nextInt();
long val = in.nextLong();
if(type==0)
{
set.remove(val);
Long higher = set.higher(val);
Long lower = set.lower(val);
if(higher==null && lower==null)
{
// out.printLine(0);
sum=0;
map.clear();
// continue outer;
}
else if(lower==null)
{
long diff = higher-val;
sum-=diff;
remove(map,diff);
}
else if(higher==null)
{
long diff = val-lower;
sum-=diff;
remove(map,diff);
}
else
{
long diff1 = val-lower;
long diff2 = higher-val;
remove(map,diff1);
remove(map,diff2);
add(map,higher-lower);
// max = Math.max(max,higher-lower);
}
// out.printLine(set + " " + sum + " " + max);
if(set.size()<=1)
out.printLine(0);
else
out.printLine(sum-map.lastKey());
}
else
{
set.add(val);
Long higher = set.higher(val);
Long lower = set.lower(val);
if(higher==null && lower==null)
{
// out.printLine(0);
sum=0;
// continue outer;
}
else if(lower==null)
{
long diff = higher-val;
sum+=diff;
add(map,diff);
}
else if(higher==null)
{
long diff = val-lower;
sum+=diff;
add(map,diff);
}
else
{
long diff1 = val-lower;
long diff2 = higher-val;
remove(map,(higher-lower));
add(map,diff1);
add(map,diff2);
}
// out.printLine(set + " " + sum + " " + max);
if(set.size()<=1)
out.printLine(0);
else
out.printLine(sum-map.lastKey());
}
out.flush();
}
out.flush();
out.close();
}
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | cc7a218cf8b9126dbc3eaae7d98ec4b4 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes |
// Problem: D. Trash Problem
// Contest: Codeforces - Educational Codeforces Round 95 (Rated for Div. 2)
// URL: https://codeforces.com/contest/1418/problem/D
// Memory Limit: 256 MB
// Time Limit: 3000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)
import java.io.*;
import java.util.*;
public class Main {
private static PrintWriter pw = new PrintWriter(System.out);
private static InputReader sc = new InputReader();
private static final int intmax = Integer.MAX_VALUE, intmin = Integer.MIN_VALUE;
static class Pair{
int first, second;
Pair(int first, int second){
this.first = first;
this.second = second;
}
}
static class InputReader{
private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer tk;
private void next()throws IOException{
while(tk == null || !tk.hasMoreTokens())
tk = new StringTokenizer(r.readLine());
}
private int nextInt()throws IOException{
next();
return Integer.parseInt(tk.nextToken());
}
private long nextLong()throws IOException{
next();
return Long.parseLong(tk.nextToken());
}
private String readString()throws IOException{
next();
return tk.nextToken();
}
private double nextDouble()throws IOException{
next();
return Double.parseDouble(tk.nextToken());
}
private int[] intArray(int n)throws IOException{
next();
int arr[] = new int[n];
for(int i=0; i<n; i++)
arr[i] = nextInt();
return arr;
}
private long[] longArray(int n)throws IOException{
next();
long arr[] = new long[n];
for(int i=0; i<n; i++)
arr[i] = nextLong();
return arr;
}
}
public static void main(String args[])throws IOException{
int t = 1;
while(t-->0) solve();
pw.flush();
pw.close();
}
private static TreeMap<Integer, Integer> map;
private static TreeSet<Integer> set;
private static void increment(int key){
int value = map.getOrDefault(key, 0) + 1;
map.put(key, value);
}
private static void decrement(int key){
try{
int value = map.get(key) - 1;
if(value == 0) map.remove(key);
else map.put(key, value);
}
catch(Exception e){
System.out.println(key);
}
}
private static void insert(int value){
if(set.ceiling(value) != null && set.floor(value) != null)
decrement(set.ceiling(value) - set.floor(value));
if(set.ceiling(value) != null)
increment(set.ceiling(value) - value);
if(set.floor(value) != null)
increment(value - set.floor(value));
set.add(value);
}
private static void delete(int value){
set.remove(value);
if(set.ceiling(value) != null && set.floor(value) != null)
increment(set.ceiling(value) - set.floor(value));
if(set.ceiling(value) != null)
decrement(set.ceiling(value) - value);
if(set.floor(value) != null)
decrement(value - set.floor(value));
}
private static int getAns(){
if(set.size() <= 2) return 0;
return set.last() - set.first() - map.lastKey();
}
private static void solve()throws IOException{
int n = sc.nextInt(), q = sc.nextInt();
map = new TreeMap<>();
set = new TreeSet<>();
for(int i = 0; i < n; i++)
insert(sc.nextInt());
System.out.println(getAns());
while(q-->0){
int ch = sc.nextInt(), pos = sc.nextInt();
if(ch == 0) delete(pos);
else insert(pos);
System.out.println(getAns());
}
}
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 7226c34b021f809382c00b0dfbeda236 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.*;
import java.util.*;
public class D_TrashProblem {
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static final PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
private static StringTokenizer st;
private static int readInt() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());
}
public static void main(String[] args) throws IOException {
solve();
pw.close();
}
private static void solve() throws IOException {
int n = readInt();
int q = readInt();
piles = new TreeSet<>();
diffs = new TreeMap<>();
for (int i = 1; i <= n + q; i++) {
boolean removal = i > n && readInt() == 0;
int pos = readInt();
Integer lower = piles.lower(pos);
Integer higher = piles.higher(pos);
if (removal) {
if (lower != null) remove(pos - lower);
if (higher != null) remove(higher - pos);
if (lower != null && higher != null) add(higher - lower);
piles.remove(pos);
} else {
if (lower != null) add(pos - lower);
if (higher != null) add(higher - pos);
if (lower != null && higher != null) remove(higher - lower);
piles.add(pos);
}
if (i >= n) {
if (piles.size() <= 2) pw.println(0);
else pw.println(piles.last() - piles.first() - diffs.lastKey());
}
}
}
static NavigableSet<Integer> piles;
static SortedMap<Integer, Integer> diffs;
static void remove(Integer diff) {
Integer existingCount = diffs.get(diff);
if (existingCount == 1) diffs.remove(diff); // must remove so to enable lastKey()
else diffs.put(diff, existingCount - 1);
}
static void add(Integer diff) {
diffs.put(diff, diffs.getOrDefault(diff, 0) + 1);
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 44d372dca0695995653ea3f890bf145a | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1418d {
public static void main(String[] args) throws IOException {
int n = rni(), q = ni(), p[] = ria(n);
rsort(p);
TreeMap<Integer, Integer> diff = new TreeMap<>();
TreeSet<Integer> set = new TreeSet<>();
diff.put(0, 1);
set.add(p[0]);
for (int i = 1; i < n; ++i) {
diff.put(p[i] - p[i - 1], diff.getOrDefault(p[i] - p[i - 1], 0) + 1);
set.add(p[i]);
}
prln(set.size() <= 2 ? 0 : set.last() - set.first() - ((NavigableSet<Integer>) diff.keySet()).last());
for (int i = 0; i < q; ++i) {
int t = rni(), x = ni();
Integer lower = set.lower(x), higher = set.higher(x);
if (t == 0) {
if (lower != null) {
diff.put(x - lower, diff.get(x - lower) - 1);
if (diff.get(x - lower) == 0) {
diff.remove(x - lower);
}
}
if (higher != null) {
diff.put(higher - x, diff.get(higher - x) - 1);
if (diff.get(higher - x) == 0) {
diff.remove(higher - x);
}
}
if (lower != null && higher != null) {
diff.put(higher - lower, diff.getOrDefault(higher - lower, 0) + 1);
}
set.remove(x);
} else {
if (lower != null && higher != null) {
diff.put(higher - lower, diff.get(higher - lower) - 1);
if (diff.get(higher - lower) == 0) {
diff.remove(higher - lower);
}
}
if (lower != null) {
diff.put(x - lower, diff.getOrDefault(x - lower, 0) + 1);
}
if (higher != null){
diff.put(higher - x, diff.getOrDefault(higher - x, 0) + 1);
}
set.add(x);
}
prln(set.size() <= 2 ? 0 : set.last() - set.first() - ((NavigableSet<Integer>) diff.keySet()).last());
}
close();
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;};
static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;}
static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 29b118fc535b3e3c1a13c698c2b956d3 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | //package edu95;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class D {
static Random rand;
static boolean CONSTRUCTIVE = false;
static long MOD = (long) 1e9 + 7;
static long BIG = (long) 2e9;
static class Multiset<T extends Comparable<T>> {
SortedMap<T, Integer> freqMap;
public Multiset() {
this.freqMap = new TreeMap<>();
}
public void add(T elt) {
freqMap.put(elt, 1 + freqMap.getOrDefault(elt, 0));
}
public void remove(T elt) {
int freq = freqMap.getOrDefault(elt, 0);
if (freq == 0) {
throw new IllegalArgumentException("Set doesn't contain " + elt);
}
if (freq == 1) {
freqMap.remove(elt);
} else {
freqMap.put(elt, freq - 1);
}
}
// returns 0 if it doesn't contain the element
public int count(T elt) {
return freqMap.getOrDefault(elt, 0);
}
T first() {
return freqMap.firstKey();
}
T last() {
return freqMap.lastKey();
}
}
public static void solve(Reader in, PrintWriter out) {
int n = in.nextInt(), q = in.nextInt();
SortedSet<Long> coords = new TreeSet<>();
Multiset<Long> gaps = new Multiset<>();
for (int i = 0; i < n; i++) {
coords.add(in.nextLong());
}
long last = coords.first();
for (long coord : coords) {
if (coord != last) {
gaps.add(coord - last);
last = coord;
}
}
out.println(totCleanup(coords, gaps));
for (int i = 0; i < q; i++) {
boolean add = in.nextInt() == 1;
long loc = in.nextLong();
if (add) {
SortedSet<Long> before = coords.headSet(loc);
SortedSet<Long> after = coords.tailSet(loc);
if (!before.isEmpty() && !after.isEmpty()) {
long dist = after.first() - before.last();
gaps.remove(dist);
}
if (!before.isEmpty()) {
long dist = loc - before.last();
gaps.add(dist);
}
if (!after.isEmpty()) {
long dist = after.first() - loc;
gaps.add(dist);
}
coords.add(loc);
} else {
SortedSet<Long> before = coords.headSet(loc);
SortedSet<Long> after = coords.tailSet(loc + 1);
if (!before.isEmpty()) {
long dist = loc - before.last();
gaps.remove(dist);
}
if (!after.isEmpty()) {
long dist = after.first() - loc;
gaps.remove(dist);
}
if (!before.isEmpty() && !after.isEmpty()) {
long dist = after.first() - before.last();
gaps.add(dist);
}
coords.remove(loc);
}
// System.out.println(coords);
// System.out.println(gaps);
out.println(totCleanup(coords, gaps));
}
}
static long totCleanup(SortedSet<Long> coords, Multiset<Long> gaps) {
if (coords.size() <= 2) return 0;
long l = coords.first();
long r = coords.last();
return r - l - gaps.last();
}
// static long totCleanup(SortedSet<Long> coords) {
// if (coords.size() <= 2) return 0;
// long l = coords.first();
// long r = coords.last();
// long midpoint = l + (r-l)/2; // rounded toward l
//// System.out.println(l + " " + midpoint + " " + r);
// long m1 = coords.headSet(midpoint+1).last();
// long m2 = coords.tailSet(midpoint+1).first();
// return (m1 - l) + (r - m2);
// }
public static void main(String[] args) throws IOException {
Reader in = null;
PrintWriter out = null;
for (String arg : args) {
if (arg.startsWith("input")) {
in = new Reader(arg);
} else if (arg.startsWith("output")) {
out = new PrintWriter(new FileWriter(arg));
}
}
if (in == null) in = new Reader();
if (out == null) out = new PrintWriter(new OutputStreamWriter(System.out));
// int tests = in.nextInt();
// for (int t = 0; t < tests; t++) {
solve(in, out);
// }
out.flush();
}
static class Tester {
public static void main(String[] args) throws IOException {
Validator validator = new Validator();
File currentDir = new File(".");
long before;
long after;
for (File inputFile : Arrays.stream(currentDir.listFiles())
.sorted(Comparator.comparing(File::getName))
.collect(Collectors.toList())) {
if (!inputFile.getName().startsWith("input")
|| inputFile.getName().contains("sight")
|| inputFile.getName().contains("big")) continue;
System.out.println("Test file: " + inputFile.getName());
before = System.nanoTime();
String outputFileName = "output" + inputFile.getName().substring(5);
D.main(new String[]{inputFile.getName(), outputFileName});
after = System.nanoTime();
File outputFile = new File(outputFileName);
if (!outputFile.exists()) {
throw new IllegalStateException("Missing output file " + outputFile);
}
// TODO if verifier is implemented, remove this
if (CONSTRUCTIVE) {
System.out.println("INPUT:");
printFile(inputFile);
System.out.printf("\nOUTPUT: (%d milliseconds)\n", (after - before) / 1000000L);
printFile(outputFile);
continue;
}
if (validator.validate(inputFile, outputFile)) {
System.out.printf("OK (%d milliseconds)\n", (after - before) / 1000000L);
} else {
System.out.println("FAILED");
System.out.println("\nInput: ");
printFile(inputFile);
System.out.println("\nIncorrect Output: ");
printFile(outputFile);
return;
}
}
System.out.println("\n-----------------\n");
File sightTestInput = new File("input-sight");
if (sightTestInput.exists()) {
System.out.println("Running sight test... Input:");
printFile(sightTestInput);
before = System.nanoTime();
System.out.println("\nOutput: ");
D.main(new String[]{"input-sight"});
after = System.nanoTime();
System.out.printf("(%d milliseconds)\n", (after - before) / 1000000L);
System.out.println("\n-----------------\n");
}
File bigTestInput = new File("input-big");
if (bigTestInput.exists()) {
System.out.println("Running big test...");
before = System.nanoTime();
D.main(new String[] {"input-big"});
after = System.nanoTime();
System.out.printf("(%d milliseconds)\n", (after - before) / 1000000L);
}
}
static void printFile(File file) throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(file));
reader.lines().forEach(System.out::println);
}
}
static class Validator {
boolean validate(File inputFile, File outputFile) throws IOException {
File expectedOutputFile = new File("expected-output" + inputFile.getName().substring(5));
if (CONSTRUCTIVE || !expectedOutputFile.exists()) {
return validateManual(inputFile, outputFile);
}
return areSame(outputFile, expectedOutputFile);
}
private boolean validateManual(File inputFile, File outputFile) throws IOException {
if (CONSTRUCTIVE) {
// Validate output against input
Reader inputReader = new Reader(inputFile.getName());
Reader outputReader = new Reader(outputFile.getName());
// TODO implement manual validation
throw new IllegalStateException("Missing expected output file");
} else {
File naiveOutput = new File("naive-" + outputFile.getName());
Naive.main(new String[]{inputFile.getName(), naiveOutput.getName()});
return areSame(outputFile, naiveOutput);
}
}
private boolean areSame(File file1, File file2) throws IOException {
BufferedReader reader1 = new BufferedReader(new FileReader(file1));
BufferedReader reader2 = new BufferedReader(new FileReader(file2));
String line1;
while ((line1 = reader1.readLine()) != null) {
String line2 = reader2.readLine();
if (line2 == null) line2 = ""; // ok if one has an extra newline
if (!line1.trim().equals(line2.trim())) {
return false;
}
}
String line2;
while ((line2 = reader2.readLine()) != null) {
if (!line2.trim().isEmpty()) {
return false;
}
}
return true;
}
}
static class Naive {
public static void solveNaive(Reader in, PrintWriter out) {
throw new IllegalStateException("missing expected output file");
}
public static void main(String[] args) throws IOException {
Reader in = null;
PrintWriter out = null;
for (String arg : args) {
if (arg.startsWith("input")) {
in = new Reader(arg);
} else if (arg.startsWith("naive-output")) {
out = new PrintWriter(new FileWriter(arg));
}
}
if (in == null) in = new Reader();
if (out == null) out = new PrintWriter(new OutputStreamWriter(System.out));
int tests = in.nextInt();
for (int t = 0; t < tests; t++) {
solve(in, out);
}
out.flush();
out.close();
}
}
static long pair(int x, int y) {
return x * BIG + y;
}
static int x(long pair) {
return (int) (pair / BIG);
}
static int y(long pair) {
return (int) (pair % BIG);
}
static void ruffleSort(int[] a) {
if (rand == null) rand = new Random();
int n=a.length;
for (int i=0; i<n; i++) {
int oi=rand.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void insist(boolean bool) {
if (!bool) throw new IllegalStateException();
}
static class Reader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public Reader(String fileName) throws FileNotFoundException {
reader = new BufferedReader(new FileReader(fileName));
}
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 int[] nextInts(int n) {
int[] out = new int[n];
for (int i = 0; i < n; i++) {
out[i] = nextInt();
}
return out;
}
public long[] nextLongs(int n) {
long[] out = new long[n];
for (int i = 0; i < n; i++) {
out[i] = nextLong();
}
return out;
}
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 45d59d1b3a2afd0c80c91e99577e18d1 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | //package edu95;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class D {
static Random rand;
static boolean CONSTRUCTIVE = false;
static long MOD = (long) 1e9 + 7;
static long BIG = (long) 2e9;
public static void solve(Reader in, PrintWriter out) {
int n = in.nextInt(), q = in.nextInt();
SortedSet<Long> coords = new TreeSet<>();
SortedMap<Long, Integer> gaps = new TreeMap<>();
for (int i = 0; i < n; i++) {
coords.add(in.nextLong());
}
long last = coords.first();
for (long coord : coords) {
if (coord != last) {
gaps.put(coord - last, gaps.getOrDefault(coord - last, 0) + 1);
last = coord;
}
}
out.println(totCleanup(coords, gaps));
for (int i = 0; i < q; i++) {
boolean add = in.nextInt() == 1;
long loc = in.nextLong();
if (add) {
SortedSet<Long> before = coords.headSet(loc);
SortedSet<Long> after = coords.tailSet(loc);
if (!before.isEmpty() && !after.isEmpty()) {
long dist = after.first() - before.last();
gaps.put(dist, gaps.get(dist) - 1);
if (gaps.get(dist) == 0) {
gaps.remove(after.first() - before.last());
}
}
if (!before.isEmpty()) {
long dist = loc - before.last();
gaps.put(dist, gaps.getOrDefault(dist, 0) + 1);
}
if (!after.isEmpty()) {
long dist = after.first() - loc;
gaps.put(dist, gaps.getOrDefault(dist, 0) + 1);
}
coords.add(loc);
} else {
SortedSet<Long> before = coords.headSet(loc);
SortedSet<Long> after = coords.tailSet(loc + 1);
if (!before.isEmpty()) {
long dist = loc - before.last();
gaps.put(dist, gaps.get(dist) - 1);
if (gaps.get(dist) == 0) {
gaps.remove(dist);
}
}
if (!after.isEmpty()) {
long dist = after.first() - loc;
gaps.put(dist, gaps.get(dist) - 1);
if (gaps.get(dist) == 0) {
gaps.remove(dist);
}
}
if (!before.isEmpty() && !after.isEmpty()) {
long dist = after.first() - before.last();
gaps.put(dist, gaps.getOrDefault(dist, 0) + 1);
}
coords.remove(loc);
}
// System.out.println(coords);
// System.out.println(gaps);
out.println(totCleanup(coords, gaps));
}
}
static long totCleanup(SortedSet<Long> coords, SortedMap<Long, Integer> gaps) {
if (coords.size() <= 2) return 0;
long l = coords.first();
long r = coords.last();
return r - l - gaps.lastKey();
}
// static long totCleanup(SortedSet<Long> coords) {
// if (coords.size() <= 2) return 0;
// long l = coords.first();
// long r = coords.last();
// long midpoint = l + (r-l)/2; // rounded toward l
//// System.out.println(l + " " + midpoint + " " + r);
// long m1 = coords.headSet(midpoint+1).last();
// long m2 = coords.tailSet(midpoint+1).first();
// return (m1 - l) + (r - m2);
// }
public static void main(String[] args) throws IOException {
Reader in = null;
PrintWriter out = null;
for (String arg : args) {
if (arg.startsWith("input")) {
in = new Reader(arg);
} else if (arg.startsWith("output")) {
out = new PrintWriter(new FileWriter(arg));
}
}
if (in == null) in = new Reader();
if (out == null) out = new PrintWriter(new OutputStreamWriter(System.out));
// int tests = in.nextInt();
// for (int t = 0; t < tests; t++) {
solve(in, out);
// }
out.flush();
}
static class Tester {
public static void main(String[] args) throws IOException {
Validator validator = new Validator();
File currentDir = new File(".");
long before;
long after;
for (File inputFile : Arrays.stream(currentDir.listFiles())
.sorted(Comparator.comparing(File::getName))
.collect(Collectors.toList())) {
if (!inputFile.getName().startsWith("input")
|| inputFile.getName().contains("sight")
|| inputFile.getName().contains("big")) continue;
System.out.println("Test file: " + inputFile.getName());
before = System.nanoTime();
String outputFileName = "output" + inputFile.getName().substring(5);
D.main(new String[]{inputFile.getName(), outputFileName});
after = System.nanoTime();
File outputFile = new File(outputFileName);
if (!outputFile.exists()) {
throw new IllegalStateException("Missing output file " + outputFile);
}
// TODO if verifier is implemented, remove this
if (CONSTRUCTIVE) {
System.out.println("INPUT:");
printFile(inputFile);
System.out.printf("\nOUTPUT: (%d milliseconds)\n", (after - before) / 1000000L);
printFile(outputFile);
continue;
}
if (validator.validate(inputFile, outputFile)) {
System.out.printf("OK (%d milliseconds)\n", (after - before) / 1000000L);
} else {
System.out.println("FAILED");
System.out.println("\nInput: ");
printFile(inputFile);
System.out.println("\nIncorrect Output: ");
printFile(outputFile);
return;
}
}
System.out.println("\n-----------------\n");
File sightTestInput = new File("input-sight");
if (sightTestInput.exists()) {
System.out.println("Running sight test... Input:");
printFile(sightTestInput);
before = System.nanoTime();
System.out.println("\nOutput: ");
D.main(new String[]{"input-sight"});
after = System.nanoTime();
System.out.printf("(%d milliseconds)\n", (after - before) / 1000000L);
System.out.println("\n-----------------\n");
}
File bigTestInput = new File("input-big");
if (bigTestInput.exists()) {
System.out.println("Running big test...");
before = System.nanoTime();
D.main(new String[] {"input-big"});
after = System.nanoTime();
System.out.printf("(%d milliseconds)\n", (after - before) / 1000000L);
}
}
static void printFile(File file) throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(file));
reader.lines().forEach(System.out::println);
}
}
static class Validator {
boolean validate(File inputFile, File outputFile) throws IOException {
File expectedOutputFile = new File("expected-output" + inputFile.getName().substring(5));
if (CONSTRUCTIVE || !expectedOutputFile.exists()) {
return validateManual(inputFile, outputFile);
}
return areSame(outputFile, expectedOutputFile);
}
private boolean validateManual(File inputFile, File outputFile) throws IOException {
if (CONSTRUCTIVE) {
// Validate output against input
Reader inputReader = new Reader(inputFile.getName());
Reader outputReader = new Reader(outputFile.getName());
// TODO implement manual validation
throw new IllegalStateException("Missing expected output file");
} else {
File naiveOutput = new File("naive-" + outputFile.getName());
Naive.main(new String[]{inputFile.getName(), naiveOutput.getName()});
return areSame(outputFile, naiveOutput);
}
}
private boolean areSame(File file1, File file2) throws IOException {
BufferedReader reader1 = new BufferedReader(new FileReader(file1));
BufferedReader reader2 = new BufferedReader(new FileReader(file2));
String line1;
while ((line1 = reader1.readLine()) != null) {
String line2 = reader2.readLine();
if (line2 == null) line2 = ""; // ok if one has an extra newline
if (!line1.trim().equals(line2.trim())) {
return false;
}
}
String line2;
while ((line2 = reader2.readLine()) != null) {
if (!line2.trim().isEmpty()) {
return false;
}
}
return true;
}
}
static class Naive {
public static void solveNaive(Reader in, PrintWriter out) {
throw new IllegalStateException("missing expected output file");
}
public static void main(String[] args) throws IOException {
Reader in = null;
PrintWriter out = null;
for (String arg : args) {
if (arg.startsWith("input")) {
in = new Reader(arg);
} else if (arg.startsWith("naive-output")) {
out = new PrintWriter(new FileWriter(arg));
}
}
if (in == null) in = new Reader();
if (out == null) out = new PrintWriter(new OutputStreamWriter(System.out));
int tests = in.nextInt();
for (int t = 0; t < tests; t++) {
solve(in, out);
}
out.flush();
out.close();
}
}
static long pair(int x, int y) {
return x * BIG + y;
}
static int x(long pair) {
return (int) (pair / BIG);
}
static int y(long pair) {
return (int) (pair % BIG);
}
static void ruffleSort(int[] a) {
if (rand == null) rand = new Random();
int n=a.length;
for (int i=0; i<n; i++) {
int oi=rand.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void insist(boolean bool) {
if (!bool) throw new IllegalStateException();
}
static class Reader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public Reader(String fileName) throws FileNotFoundException {
reader = new BufferedReader(new FileReader(fileName));
}
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 int[] nextInts(int n) {
int[] out = new int[n];
for (int i = 0; i < n; i++) {
out[i] = nextInt();
}
return out;
}
public long[] nextLongs(int n) {
long[] out = new long[n];
for (int i = 0; i < n; i++) {
out[i] = nextLong();
}
return out;
}
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | 0406a857adee32f156360999ee8fd2e4 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
long startTime = System.currentTimeMillis();
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
Output out = new Output(outputStream);
DTrashProblem solver = new DTrashProblem();
solver.solve(1, in, out);
out.close();
System.err.println(System.currentTimeMillis()-startTime+"ms");
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28);
thread.start();
thread.join();
}
static class DTrashProblem {
public DTrashProblem() {
}
public void solve(int kase, InputReader in, Output pw) {
int n = in.nextInt(), q = in.nextInt();
TreeSet<Integer> ts = new TreeSet<>();
for(int i = 0; i<n; i++) {
ts.add(in.nextInt());
}
TreeMap<Integer, Integer> segs = new TreeMap<>();
{
Integer[] arr = ts.toArray(new Integer[0]);
for(int i = 0; i<n-1; i++) {
segs.put(arr[i+1]-arr[i], segs.getOrDefault(arr[i+1]-arr[i], 0)+1);
}
}
if(ts.isEmpty()||segs.isEmpty()) {
pw.println(0);
}else {
pw.println(ts.last()-ts.first()-segs.lastKey());
}
while(q-->0) {
int type = in.nextInt(), val = in.nextInt();
if(type==0) {
ts.remove(val);
int sum = 0;
Integer l = ts.lower(val);
if(l!=null) {
sum += val-l;
int cnt = segs.remove(val-l)-1;
if(cnt>0) {
segs.put(val-l, cnt);
}
}
Integer r = ts.higher(val);
if(r!=null) {
sum += r-val;
int cnt = segs.remove(r-val)-1;
if(cnt>0) {
segs.put(r-val, cnt);
}
}
if(r!=null&&l!=null) {
segs.put(sum, segs.getOrDefault(sum, 0)+1);
}
}else {
Integer l = ts.lower(val), r = ts.higher(val);
ts.add(val);
if(l!=null||r!=null) {
if(l==null) {
segs.put(r-val, segs.getOrDefault(r-val, 0)+1);
}else if(r==null) {
segs.put(val-l, segs.getOrDefault(val-l, 0)+1);
}else {
int cnt = segs.remove(r-l)-1;
if(cnt>0) {
segs.put(r-l, cnt);
}
segs.put(val-l, segs.getOrDefault(val-l, 0)+1);
segs.put(r-val, segs.getOrDefault(r-val, 0)+1);
}
}
}
if(ts.isEmpty()||segs.isEmpty()) {
pw.println(0);
}else {
pw.println(ts.last()-ts.first()-segs.lastKey());
}
Utilities.Debug.dbg(ts, segs);
}
}
}
static class FastReader implements InputReader {
final private int BUFFER_SIZE = 1<<16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer;
private int bytesRead;
public FastReader(InputStream is) {
din = new DataInputStream(is);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public int nextInt() {
int ret = 0;
byte c = skipToDigit();
boolean neg = (c=='-');
if(neg) {
c = read();
}
do {
ret = ret*10+c-'0';
} while((c = read())>='0'&&c<='9');
if(neg) {
return -ret;
}
return ret;
}
private boolean isDigit(byte b) {
return b>='0'&&b<='9';
}
private byte skipToDigit() {
byte ret;
while(!isDigit(ret = read())&&ret!='-') ;
return ret;
}
private void fillBuffer() {
try {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
}catch(IOException e) {
e.printStackTrace();
throw new InputMismatchException();
}
if(bytesRead==-1) {
buffer[0] = -1;
}
}
private byte read() {
if(bytesRead==-1) {
throw new InputMismatchException();
}else if(bufferPointer==bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
}
static interface InputReader {
int nextInt();
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
public String lineSeparator;
public Output(OutputStream os) {
this(os, 1<<16);
}
public Output(OutputStream os, int bs) {
BUFFER_SIZE = bs;
sb = new StringBuilder(BUFFER_SIZE);
this.os = new BufferedOutputStream(os, 1<<17);
lineSeparator = System.lineSeparator();
}
public void println(int i) {
println(String.valueOf(i));
}
public void println(String s) {
sb.append(s);
println();
if(sb.length()>BUFFER_SIZE >> 1) {
flushToBuffer();
}
}
public void println() {
sb.append(lineSeparator);
}
private void flushToBuffer() {
try {
os.write(sb.toString().getBytes());
}catch(IOException e) {
e.printStackTrace();
}
sb = new StringBuilder(BUFFER_SIZE);
}
public void flush() {
try {
flushToBuffer();
os.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
public void close() {
flush();
try {
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
static class Utilities {
public static class Debug {
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static <T> String ts(T t) {
if(t==null) {
return "null";
}
try {
return ts((Iterable) t);
}catch(ClassCastException e) {
if(t instanceof int[]) {
String s = Arrays.toString((int[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}
try {
return ts((Object[]) t);
}catch(ClassCastException e1) {
return t.toString();
}
}
}
private static <T> String ts(T[] arr) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: arr) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
private static <T> String ts(Iterable<T> iter) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: iter) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
public static void dbg(Object... o) {
if(LOCAL) {
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
}
}
}
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | acbcda797f1304fd0e2a30e501a59019 | train_001.jsonl | 1600094100 | Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment. $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example. | 256 megabytes | import java.util.*;
import java.io.*;
public class A {
static final FastReader in = new FastReader();
static final PrintWriter out = new PrintWriter(System.out);
static TreeSet<Pair> lset = new TreeSet<>();
static TreeSet<Integer> set = new TreeSet<>();
static void add(int x) {
Integer lower = set.lower(x), higher = set.higher(x);
if(lower != null) lset.add(new Pair(lower,x));
if(higher != null) lset.add(new Pair(x,higher));
if(lower != null && higher != null) {
lset.remove(new Pair(lower,higher));
}
set.add(x);
}
static void rem(int x) {
Integer lower = set.lower(x), higher = set.higher(x);
if(lower != null) lset.remove(new Pair(lower,x));
if(higher != null) lset.remove(new Pair(x,higher));
if(lower != null && higher != null) {
lset.add(new Pair(lower,higher));
}
set.remove(x);
}
static int get() {
Pair p = new Pair(0,0);
if(lset.size()>0) p = lset.first();
int last = 0, first = 0;
if(set.size() > 0) {
last = set.last();
first = set.first();
}
//out.println(last + " " + first + " " + (p.y-p.x) + " " + p);
return last-first-(p.y-p.x);
}
public static void main(String[] args) {
int n = in.nextInt(), q = in.nextInt();
for(int i=0; i<n; i++) {
add(in.nextInt());
}
out.println(get());
for(int i=0; i<q; i++) {
int t= in.nextInt(), x = in.nextInt();
if(t == 0) {
rem(x);
}else {
add(x);
}
out.println(get());
}
out.close();
}
static long power(long a, long b, int mod) {
if (b == 0)
return 1;
long res = power(a, b / 2, mod);
res = res * res % mod;
if (b % 2 == 1)
res = res * a % mod;
return res;
}
static class Pair implements Comparable<Pair> {
public int x;
public int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if(o.y-o.x == y-x) return Integer.compare(x, o.x);
return Integer.compare(o.y-o.x,y-x);
}
@Override
public String toString() {
String val = "(" + x + "," + y + ")";
return val;
}
@Override
public int hashCode() {
return 31 * x + y;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (this.getClass() != o.getClass())
return false;
Pair p = (Pair) o;
return (x == p.x && y == p.y);
}
}
static int[] readIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
return a;
}
static long[] readLongArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = in.nextLong();
return a;
}
static int[][] readIntMat(int n, int m) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = in.nextInt();
return a;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
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;
}
}
}
| Java | ["5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50", "5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000"] | 3 seconds | ["5\n7\n7\n5\n4\n8\n49", "3\n2\n1\n0\n0\n0\n0\n0\n499999999"] | NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too. | Java 11 | standard input | [
"data structures",
"implementation"
] | ef6535b1788c59146d5782041188920d | The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles. | 2,100 | Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries. | standard output | |
PASSED | b27c17e82552cd69bba98fd1ae1198c0 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | // Working program using Reader Class
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class xor
{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws IOException
{
Reader z=new Reader();
int n=z.nextInt();
int max=-1;
Stack<Integer> s=new Stack<Integer>();
int a[]=new int[n];
for(int x=0;x<n;x++)
{
a[x]=z.nextInt();
}
for(int x=0;x<n;x++)
{ //System.out.println("CHCEK1 "+s);
if(s.isEmpty()==true || s.peek()>a[x])
s.push(a[x]);
else
{
int k=(Integer)s.pop();
int t=k^a[x];
if(t>max)
{max=t;}
//System.out.println("check 2 "+k+" "+a[x]+" "+max);}
if(s.isEmpty()==false)
{
int y=(Integer)s.peek();
y=y^k;
if(y>max)
{max=y;}
//System.out.println("check 33 "+k+" "+y+" "+max);}
}
--x;
}
}
while(s.isEmpty()==false)
{
int m=(Integer)s.pop();
if(s.isEmpty()==true)
break;
else
{
int j=(Integer)s.peek();
j=m^j;
if(j>max)
max=j;}
}
System.out.println(max);
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 50c56fba63638d7201b21c8c359faccc | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | //package codeforces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class D281 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
int[] arr = new int[n];
String[] s = in.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(s[i]);
}
int result = maxXor(arr);
for (int i = 0, j = n - 1; i < j; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
System.out.println(Math.max(result, maxXor(arr)));
}
private static int maxXor(int[] arr) {
int n = arr.length;
Stack<Integer> list = new Stack<>();
int result = arr[0] ^ arr[1];
for (int value : arr) {
while (!list.isEmpty() && list.peek() < value) list.pop();
if (!list.empty()) {
result = Math.max(result, list.peek() ^ value);
}
list.push(value);
}
return result;
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 4033729a13748e151a4604fbe72925aa | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes |
import java.io.*;
import java.util.*;
public class MXSEC {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] ip = br.readLine().split(" ");
long[] ary = new long[n];
for(int i = 0 ; i < n ; i++) {
ary[i] = Long.parseLong(ip[i]);
}
System.out.println(solve(ary));
}
public static long solve (long[] ary) {
Deque<Long> stack = new ArrayDeque<>();
long max_xor = Long.MIN_VALUE;
int i = 0;
int n = ary.length;
while ( i < n ) {
if(stack.isEmpty() || stack.peek() > ary[i]) {
if(!stack.isEmpty()) {
long temp = stack.peek() ^ ary[i];
if ( max_xor < temp )
max_xor = temp;
}
stack.push(ary[i++]);
}
else {
long temp = stack.pop() ^ ary[i];
if ( max_xor < temp )
max_xor = temp;
}
}
/*while(!stack.isEmpty()) {
long a=0;
long b=0;
a = stack.pop();
if(stack.isEmpty())
break;
b = stack.peek();
long temp = a^b;
if ( max_xor < temp )
max_xor = temp;
}*/
return max_xor;
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 4b10be28482ab91c1081f58e73c01f93 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.util.Scanner;
import java.util.Stack;
public class MaximumXorSecondary {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int ans = -1;
Stack<Integer> s = new Stack<>();
int[] arr = new int[n];
for(int i=0; i<n; i++) {
arr[i] = in.nextInt();
}
for(int i=0; i<n; i++) {
while(!s.isEmpty() && arr[s.peek()] <= arr[i]) {
ans = Math.max(ans, arr[s.pop()] ^ arr[i]);
}
if(!s.isEmpty()) {
ans = Math.max(ans, arr[s.peek()] ^ arr[i]);
}
s.push(i);
}
s.clear();
for(int i=n-1; i>=0; i--) {
while(!s.isEmpty() && arr[s.peek()] <= arr[i]) {
ans = Math.max(ans, arr[s.pop()] ^ arr[i]);
}
if(!s.isEmpty()) {
ans = Math.max(ans, arr[s.peek()] ^ arr[i]);
}
s.push(i);
}
System.out.println(ans);
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | a5c273e72bf6874702996488dd91a4fd | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.*;
import java.util.*;
public final class Maxxor
{
static class Input
{
BufferedReader br;
StringTokenizer st;
public Input()
{
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());
}
}
public static void main(String[] args)
{
Input in=new Input();
int n=in.nextInt();
int xor=0;
Stack<Integer> st=new Stack<Integer>();
while(n-->0)
{
int tmp=in.nextInt();
while(!st.isEmpty()&&tmp>st.peek())
{
int txor=st.peek()^tmp;
if(txor>xor)
{
xor=txor;
}
st.pop();
}
if(!st.isEmpty()&&tmp<st.peek())
{
int txor=st.peek()^tmp;
if(txor>xor)
{
xor=txor;
}
}
st.push(tmp);
}
System.out.println(xor);
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | e6f12f38a6a7087dbab7efb0e3d8f8be | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
Stack<Integer> stk = new Stack<Integer>();
int n = sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
int ans = 0;
for(int i=0;i<n;i++)
{
while(!stk.empty())
{
if(a[i]<stk.peek())
{
ans = (Math.max(ans,stk.peek()^a[i]));
break;
}
else
{
ans = (Math.max(ans,stk.peek()^a[i]));
stk.pop();
}
}
stk.push(a[i]);
}
System.out.println(ans);
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 66ea86d1eb57fbd9fef86abaf8129f99 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.*;
import java.util.*;
public class Code0108 {
static long answer(int a[]){
List<Integer> one = new ArrayList<>();
int n = a.length;
int len[] = new int[a.length];
int maxlen = 0;
for (int i = 0; i < n; i++) {
int x = a[i];
int c = 0;
while (x > 0){
x = x/2;
c++;
}
len[i] = c;
maxlen = Math.max(maxlen,len[i]);
}
if(maxlen == 0){
return 0;
}
long pow = (long)Math.pow(2,maxlen-1);
for (int i = 0; i <n ; i++) {
if(len[i] == maxlen){
one.add(i);
}
}
if(one.size() == n){
for (int i = 0; i <n ; i++) {
a[i] -= pow;
// System.out.print(a[i]+" ");
}
// System.out.println();
return answer(a);
}
long maxans = 0;
for (int i = 0; i <one.size() ; i++) {
int pos = one.get(i);
int left = 0;
int right = n-1;
if(i>0){
left = one.get(i-1)+1;
}
if((i+1)<one.size()){
right = one.get(i+1) - 1;
}
int secmax = 0;
for (int j = pos-1; j >= left ; j--) {
secmax = Math.max(secmax,a[j]);
maxans = Math.max(maxans,a[pos]^secmax);
// System.out.println(a[pos] + " " + secmax+ " "+ maxans);
}
secmax = 0;
for (int j = pos+1; j <= right ; j++) {
secmax = Math.max(secmax,a[j]);
maxans = Math.max(maxans,a[pos]^secmax);
}
}
return maxans;
}
public static void main(String args[]){
Reader s = new Reader();
int n = s.nextInt();
int a[] = new int[n];
for (int i = 0; i <n ; i++) {
a[i] = s.nextInt();
}
System.out.println(answer(a));
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 3f7fbfc35e5b4ac1623c5d3bb2930d6c | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int size = Integer.parseInt(br.readLine());
int[] array = getIntArray(br.readLine().split(" "));
Stack<Integer> stack = new Stack<>();
int ans = Integer.MIN_VALUE;
for (int num : array) {
if (stack.isEmpty()) {
stack.push(num);
} else if (stack.peek() < num) {
while (!stack.isEmpty() && stack.peek() < num) {
int poppedEle = stack.pop();
int currentAns = num ^ poppedEle;
if (currentAns > ans) {
ans = currentAns;
}
}
if(!stack.isEmpty()) {
int topEle = stack.peek();
int currentAns = num ^ topEle;
if (currentAns > ans) {
ans = currentAns;
}
}
stack.push(num);
} else {
int topEle = stack.peek();
int currentAns = num ^ topEle;
if (currentAns > ans) {
ans = currentAns;
}
stack.push(num);
}
}
System.out.println(ans);
}
// 134189790
public static int[] getIntArray(String[] arr) {
int[] array = new int[arr.length];
int index = 0;
for (String temp : arr) {
array[index++] = Integer.parseInt(temp);
}
return array;
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 3112ecd2620de78681abb40f9200e15a | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.util.*;
import java.util.Scanner;
public class Code {
public Code(){}
public static void main(String args[]){
Scanner X=new Scanner(System.in);
int N=X.nextInt();
int n=0,stack[]=new int[100005],ans=0;
for (int i=1;i<=N;i++){
int x=X.nextInt();
while (n>0&&x>stack[n]) {ans=Math.max(ans,x^stack[n]);n--;}
if (n>0) ans=Math.max(ans,x^stack[n]);
n++;
stack[n]=x;
}
System.out.println(ans);
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 73046d0eadedd70f4f074394102d022f | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] brr = br.readLine().split(" ");
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(brr[i]);
}
Stack<Integer> stk = new Stack<Integer>();
stk.push(arr[0]);
long max = 0;
for(int i = 1; i < arr.length; i++) {
if(stk.isEmpty() || stk.peek() > arr[i]) {
max = Math.max(max, arr[i] ^ stk.peek());
stk.push(arr[i]);
} else {
while(!stk.isEmpty() && stk.peek() < arr[i]) {
max = Math.max(max, arr[i] ^ stk.pop());
}
if(!stk.isEmpty()) {
max = Math.max(max, arr[i] ^ stk.peek());
}
stk.push(arr[i]);
}
}
System.out.println(max);
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | d115457b91a2389d51cc1b8b020fb92f | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.*;
import java.util.Stack;
public class Main
{
public static void main(String args[])
{
InputReader in=new InputReader(System.in);
int n=in.readInt();
int arr[]=new int[n];
int arr1[]=new int[n];
for(int i=0;i<n;i++)
{
arr1[n-1-i]=arr[i]=in.readInt();
}
System.out.println(Math.max(f(arr),f(arr1)));
}
static long f(int arr[])
{
Stack<Integer> s=new Stack<Integer>();
long maxim=0;
for(int i:arr)
{
while((!s.isEmpty()) && (s.peek()<i))
s.pop();
if(!s.isEmpty())
maxim=Math.max((s.peek()^i),maxim);
s.push(i);
}
return maxim;
}
}
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 RuntimeException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new RuntimeException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String readString() {
final StringBuilder stringBuilder = new StringBuilder();
int c = read();
while (isSpaceChar(c))
c = read();
do {
stringBuilder.appendCodePoint(c);
c = read(); } while (!isSpaceChar(c));
return stringBuilder.toString();
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
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 {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 7d12563e6046a424bee68accd84edb03 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.*;
import java.util.*;
public class test {
int INF = (int)1e9;
int MOD = 1000000007;
void solve(InputReader in, PrintWriter out) throws IOException {
int n = in.nextInt();
int max = 0;
Stack<Integer> stack = new Stack<>();
for(int i=0; i<n; i++) {
int a = in.nextInt();
while(stack.size()>0) {
if(stack.peek() <= a) {
int x = stack.pop();
max = Math.max(max, x^a);
} else {
break;
}
}
if(stack.size()>0) {
int x = stack.peek();
max = Math.max(max, x^a);
}
stack.push(a);
}
// int max = 0;
// int a = stack.pop();
// while(stack.size()>0) {
// int b = stack.pop();
// max = Math.max(max, a^b);
// a = b;
// }
out.println(max);
}
public static void main(String[] args) throws IOException {
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;//in.nextInt();
while(t-- >0) {
new test().solve(in, out);
}
out.close();
}
static class InputReader {
static BufferedReader br;
static StringTokenizer st;
public InputReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
class Pair implements Comparable<Pair> {
long f, s;
Pair(long f, long s) {
this.f=f;
this.s=s;
}
public int hashCode() {
int hf = (int) (f ^ (f >>> 32));
int hs = (int) (s ^ (s >>> 32));
return 31 * hf + hs;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return s == other.s && f == other.f;
}
public int compareTo(Pair p) {
return Long.compare(this.s, p.s);
}
public String toString() {
return "(" + f + ", " + s + ")";
}
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | a25304c6d112e7fc8a30f9056b9efdd3 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayDeque;
public final class Solution {
public static void main(String[] args) throws IOException {
solution();
}
public static int LINE_LENGTH = 1000000;
//No need of nextLine after integer as in Scanner
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextLine() throws IOException {
byte[] buf = new byte[LINE_LENGTH]; // line length
int cnt = 0, c;
while ((c = next()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = next();
while (c <= ' ')
c = next();
boolean neg = (c == '-');
if (neg)
c = next();
do {
ret = ret * 10 + c - '0';
} while ((c = next()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = next();
while (c <= ' ')
c = next();
boolean neg = (c == '-');
if (neg)
c = next();
do {
ret = ret * 10 + c - '0';
}
while ((c = next()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = next();
while (c <= ' ')
c = next();
boolean neg = (c == '-');
if (neg)
c = next();
do {
ret = ret * 10 + c - '0';
}
while ((c = next()) >= '0' && c <= '9');
if (c == '.') {
while ((c = next()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte next() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
public static void solution() throws IOException {
Reader in = new Reader();
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
int result = problem281DUtil(arr);
int max = result;
result = problem281DUtil(reverse(arr));
max = max > result ? max : result;
System.out.println(max);
in.close();
}
private static int[] reverse(int arr[]) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
return arr;
}
private static int problem281DUtil(int arr[]) {
int result = arr[0] ^ arr[1];
ArrayDeque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < arr.length; i++) {
while (!stack.isEmpty() && stack.peek() < arr[i]) {
stack.pop();
}
int max = Integer.MIN_VALUE;
if (!stack.isEmpty()) {
max = stack.peek();
}
stack.push(arr[i]);
if (stack.size() >= 2) {
result = result > (max ^ arr[i]) ? result : max ^ arr[i];
}
}
return result;
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 685ade5142dfe9561fb531e26c04762f | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.*;
import java.util.*;
public class MaximumXorSecondary {
public static void main(String[] args){
FastReader reader = new FastReader();
int len = reader.nextInt();
List<Integer> list = new ArrayList(len);
for(int i = 0; i< len; i++){
list.add(reader.nextInt());
}
System.out.println(maxXor(list));
}
public static int maxXor(List<Integer> list) {
if(list == null || list.size() < 1) throw new IllegalArgumentException("Minimum two elements required");
int max = Integer.MIN_VALUE;
int i = 0;
// push first element
Deque<Integer> stack = new LinkedList<>(); // monotonically decreasing stack
stack.push(list.get(i++));
while(i < list.size()) {
if(!stack.isEmpty())
max = Math.max(max, list.get(i) ^ stack.peek()); // xor with top
if(!stack.isEmpty() && list.get(i) > stack.peek()) {
// violation of monotonically decreasing sequence, thus pop.
// it also means new element can be a new maximum or second maximum element in new subarray
stack.pop();
continue;
}
else {
stack.push(list.get(i));
i++;
}
}
return max;
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 93cec2ae8fe25d53ce12bae69e648157 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;
public class Xor {
private static long max = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
solve(br.readLine());
}
private static void solve(String input) {
max = 0;
Stack<Long> stack = new Stack<>();
StringTokenizer tokens = new StringTokenizer(input);
int pre = Integer.MAX_VALUE;
while (tokens.hasMoreTokens()) {
int num = Integer.parseInt(tokens.nextToken());
if (num > pre) {
de(stack, num);
} else en(stack, num);
pre = num;
}
if (!stack.isEmpty()) setResult(stack);
System.out.println(max);
}
private static void setResult(Stack<Long> stack) {
long pre = stack.pop();
while (!stack.isEmpty()) {
long num = stack.pop();
checkMax(pre ^ num);
pre = num;
}
}
private static void checkMax(long num) {
if (num > max) max = num;
}
private static void en(Stack<Long> stack, long num) {
stack.push(num);
}
private static void de(Stack<Long> stack, long num) {
while (!stack.isEmpty() && stack.peek() < num) {
long pop = stack.pop();
checkMax(num ^ pop);
if (!stack.isEmpty()) checkMax(stack.peek() ^ pop);
}
en(stack, num);
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 6048a09f626609fdbe9680e5c80d9203 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
public class Xor {
private static long max = 0;
private static long max2 = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
solve(br.readLine());
// int t = 10;
// while (t-- > 0) {
// if (!generate()) break;
// }
}
private static boolean generate() {
Random random = new Random();
int n = 0;
while (n == 0) {
n = random.nextInt(7);
}
StringBuilder builder = new StringBuilder();
while (n-- > 0) {
int num = 0;
while (num == 0) {
num = random.nextInt(10);
}
builder.append(num).append(" ");
}
String input = builder.toString();
solve(input);
test(input);
System.out.println(input + " solve : " + max + " test : " + max2);
if (max2 != max) {
System.out.println(input + " failed");
return false;
}
return true;
}
private static void test(String input) {
max2 = 0;
StringTokenizer tokens = new StringTokenizer(input);
int arr[] = new int[tokens.countTokens()];
int index = 0;
while (tokens.hasMoreTokens()) {
arr[index++] = Integer.parseInt(tokens.nextToken());
}
int m1, m2;
for (int i = 0; i < arr.length; i++) {
m1 = arr[i];
m2 = -1;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] > m1) {
m1 = arr[j];
m2 = arr[i];
} else if (arr[j] > m2) {
m2 = arr[j];
}
long mm = m1 ^ m2;
if (mm > max2) max2 = mm;
}
}
}
private static void solve(String input) {
max = 0;
Stack<Long> stack = new Stack<>();
StringTokenizer tokens = new StringTokenizer(input);
int pre = Integer.MAX_VALUE;
while (tokens.hasMoreTokens()) {
int num = Integer.parseInt(tokens.nextToken());
if (num > pre) {
de(stack, num);
} else en(stack, num);
pre = num;
}
if (!stack.isEmpty()) setResult(stack);
System.out.println(max);
}
private static void setResult(Stack<Long> stack) {
long pre = stack.pop();
while (!stack.isEmpty()) {
long num = stack.pop();
checkMax(pre ^ num);
pre = num;
}
}
private static void checkMax(long num) {
if (num > max) max = num;
}
private static void en(Stack<Long> stack, long num) {
stack.push(num);
}
private static void de(Stack<Long> stack, long num) {
while (!stack.isEmpty() && stack.peek() < num) {
long pop = stack.pop();
checkMax(num ^ pop);
if (!stack.isEmpty()) checkMax(stack.peek() ^ pop);
}
en(stack, num);
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | c525771b134400eaddeff80a827dae70 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static final int max = Integer.MAX_VALUE;
public static void main (String[] args) throws IOException{
FastReader f=new FastReader();
int n = f.nextInt();
int[] a = new int[n];
for (int i=0;i<n;i++) a[i] = f.nextInt();
Stack<Integer> st = new Stack<>();
st.push(a[0]);
int ans = 0;
for (int i=1;i<n;i++) {
while (!st.isEmpty() && a[i]>st.peek()) {
ans = Math.max(ans, st.pop()^a[i]);
}
st.push(a[i]);
}
st = new Stack<>();
st.push(a[n-1]);
for (int i=n-2;i>=0;i--) {
while (!st.isEmpty() && a[i]>st.peek()) {
ans = Math.max(ans, st.pop()^a[i]);
}
st.push(a[i]);
}
System.out.println(ans);
}
public static int binlog( int bits ){
int log = 0;
if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
if( bits >= 256 ) { bits >>>= 8; log += 8; }
if( bits >= 16 ) { bits >>>= 4; log += 4; }
if( bits >= 4 ) { bits >>>= 2; log += 2; }
return log + ( bits >>> 1 );
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
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;
}
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 58abc7c7cf0462efaebf3e42389fb55a | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
Stack s=new Stack();
s.push(a[0]);
long ans=0;
long mx=-1;
for(int i=1;i<n;i++)
{
if(a[i]<(int)(s.peek()))
{
ans=a[i]^((int)s.peek());
// System.out.println("ashjasd "+ans);
s.push(a[i]);
if(ans>mx)
mx=ans;
}
else
{
while((!s.empty()&&(int)s.peek()<a[i]))
{
ans=(int)s.pop()^(a[i]);
// System.out.println("akdas "+ans);
if(ans>mx)
mx=ans;
}
if(!s.empty())
{
ans=(int)s.peek()^(a[i]);
if(ans>mx)
mx=ans;}
s.push(a[i]);
}
}
System.out.println(mx);
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 801e29247acd5bb2c7bcbfd2794d7982 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.io.*;
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try{
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n) {
int[] arr = new int[n];
for(int i=0; i<n; ++i)
arr[i]=nextInt();
return arr;
}
public long[] readLongArray(int n) {
long[] arr = new long[n];
for(int i=0; i<n; ++i)
arr[i]=nextLong();
return arr;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void solve(String query) {
}
public static void main(String args[]) {
FastReader sc = new FastReader();
long start = System.currentTimeMillis();
int n = sc.nextInt();
int[] arr = sc.readIntArray(n);
long max = 0;
Stack<Integer> thestack = new Stack<>();
for(int i=0; i<n; ++i) {
while(!thestack.empty()&&arr[i]>=thestack.peek()) {
long a=thestack.peek();
thestack.pop();
max= Math.max(a^arr[i], max);
}
thestack.push(arr[i]);
}
thestack=new Stack<Integer>();
for(int i=n-1; i>=0; --i) {
while(!thestack.empty()&&arr[i]>=thestack.peek()) {
int a=thestack.peek();
thestack.pop();
max=Math.max(a^arr[i], max);
}
thestack.push(arr[i]);
}
System.out.println(max);
long end = System.currentTimeMillis();
NumberFormat formatter = new DecimalFormat("#0.00000");
//System.out.print("Execution time is " + formatter.format((end - start) / 1000d) + " seconds");
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 49ad907fd5e74605298414a8f954d4b6 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.util.Scanner;
import java.util.Stack;
public class MaxXORSecondary {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=in.nextInt();
}
Stack<Integer> s= new Stack<Integer>();
int ans=-1;
for(int i=0;i<n;i++)
{
while(!s.isEmpty())
{
if(s.peek()<a[i])
{
ans=Math.max(ans,s.peek() ^ a[i]);
s.pop();
}
else
{
ans=Math.max(ans,s.peek() ^ a[i]);
break;
}
}
s.push(a[i]);
}
System.out.println(ans);
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 2e08c5334da669928bc0323f5c8820b2 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes |
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String args[]){
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int N = Integer.parseInt(str);
str = s.nextLine().trim();
String[] str2 = str.split(" ");
int a[] = new int[N];
for(int i=0;i<N;i++){
a[i] = Integer.parseInt(str2[i]);
}
Stack<Integer> stack= new Stack<>();
int ans = 0;
for(int i=0;i<N;i++){
while(!stack.isEmpty()){
if(a[i] >= stack.peek()){
ans = Math.max(ans,(a[i]^stack.pop()));
}else{
ans = Math.max(ans,(a[i]^stack.peek()));
break;
}
}
stack.push(a[i]);
}
System.out.println(ans);
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | cdbb83abcdf79aaf685d545ceb0a4aad | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]){
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static int mod = (int)1e9+7;
static class Task{
public void solve(int testNumber, InputReader in, PrintWriter out) {
// int T = in.nextInt();
// while (T-->0){
//
// }
int N = in.nextInt();
int a[] = new int[N];
for (int i = 0; i < N; i++)
a[i] = in.nextInt();
Stack<Integer> stack = new Stack<>();
int res = 0;
for (int i = 0; i < N; i++){
while (!stack.isEmpty()){
int top = stack.peek();
int xor = top ^ a[i];
res = Math.max(res, xor);
if (a[i] > top){
stack.pop();
}else
break;
}
stack.push(a[i]);
}
out.println(res);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader() {
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;
}
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | f7cdf29d3e3d795bb64fc4c1b3515e36 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
static String[] data;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
data = reader.readLine().split(" ");
int[] input = new int[n];
for (int i = 0; i < n; i++) {
input[i] = Integer.parseInt(data[i]);
}
Stack<Integer> s = new Stack<>();
s.push(input[0]);
int maxLuckyNum = 0;
for (int i = 1; i < n; i++) {
while (!s.isEmpty() && s.peek() < input[i]) {
maxLuckyNum = Math.max(maxLuckyNum, s.pop() ^ input[i]);
}
if(!s.isEmpty()){
maxLuckyNum = Math.max(maxLuckyNum,s.peek() ^ input[i]);
}
s.push(input[i]);
}
int temp1 = s.pop();
while (!s.isEmpty()) {
int temp2 = s.pop();
maxLuckyNum = Math.max(maxLuckyNum, temp1 ^ temp2);
temp1 = temp2;
}
System.out.println(maxLuckyNum);
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | e608c865a60bb5c9276106c5726e75dd | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
static String[] data;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
data = reader.readLine().split(" ");
int[] input = new int[n];
for (int i = 0; i < n; i++) {
input[i] = Integer.parseInt(data[i]);
}
Stack<Integer> s = new Stack<>();
s.push(input[0]);
int maxLuckyNum = 0;
for (int i = 1; i < n; i++) {
while (!s.isEmpty() && s.peek() < input[i]) {
maxLuckyNum = Math.max(maxLuckyNum, s.pop() ^ input[i]);
}
if(!s.isEmpty()){
maxLuckyNum = Math.max(maxLuckyNum,s.peek() ^ input[i]);
}
s.push(input[i]);
}
/*int temp1 = s.pop();
while (!s.isEmpty()) {
int temp2 = s.pop();
maxLuckyNum = Math.max(maxLuckyNum, temp1 ^ temp2);
temp1 = temp2;
}*/
System.out.println(maxLuckyNum);
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 2115d5250b6ea511b83c4ebd327172e9 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main {
static long result = 0;
public static void main(String[] args) {
FastReader in=new FastReader();
Stack<Long> stack = new Stack<Long>();
int n=in.nextInt();
while(n-->0) {
long t=in.nextInt();
while(stack.size() > 0 && stack.peek() <= t) {
result = Math.max(result, t^stack.pop());
}
if(stack.size() > 0)result = Math.max(result, t^stack.peek());
stack.push(t);
}
System.out.println(result);
}
public static class FastReader{
BufferedReader br ;
StringTokenizer st ;
FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
st = null;
}
public String next(){
if(st==null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | a84625669d8ed0487eb48ac15ed89ff5 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.util.*;
import java.io.*;
public final class Solution
{
static int maxSecXor(int []arr,int n)
{
Stack<Integer> fwd=new Stack<>();
int res=Integer.MIN_VALUE;
fwd.push(0);
for(int i=1;i<n;i++)
{
while(!fwd.isEmpty()&&arr[fwd.peek()]<arr[i])
{
res=(int)Math.max(res,arr[i]^arr[fwd.peek()]);
fwd.pop();
}
fwd.push(i);
}
fwd.clear();
fwd.push(n-1);
for(int i=n-2;i>=0;i--)
{
while(!fwd.isEmpty()&&arr[fwd.peek()]<arr[i])
{
res=(int)Math.max(res,arr[i]^arr[fwd.peek()]);
fwd.pop();
}
fwd.push(i);
}
return res;
}
public static void main(String []args) throws Exception
{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(bf.readLine());
int arr[]=new int[n];
String s[]=bf.readLine().trim().split("\\s+");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(s[i]);
System.out.println(maxSecXor(arr,n));
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 57529b71967af0c64830457f0df69ff9 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Tarek
*/
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);
DMaximumXorSecondary solver = new DMaximumXorSecondary();
solver.solve(1, in, out);
out.close();
}
static class DMaximumXorSecondary {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int a[] = new int[111111];
int e = 0, ans = 0;
for (int i = 0; i < n; i++) {
int x = in.nextInt();
while (e > 0) {
if ((x ^ a[e]) > ans) ans = x ^ a[e];
if (x > a[e]) e--;
else break;
}
a[++e] = x;
}
out.println(ans);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 0cf6de3fd1843f1f6f5ea3898c44f65b | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Stack;
import java.util.StringTokenizer;
public class MaxXorSeconday {
static int n;
static int arr[];
static int rev[];
public static long solve(int a[])
{
int aux[] = new int[n];
Stack<Integer> s = new Stack<Integer>();
Arrays.fill(aux,-1);
long res = 0;
for(int i = 0 ; i < n ; ++i)
{
int curr = a[i];
while(!s.isEmpty() && a[(Integer)(s.peek())] < curr)
{
aux[s.pop()] = curr;
}
s.push(i);
}
for(int i = 0 ; i < n ; ++i)
{
//System.out.println(a[i] +" "+aux[i]);
if(aux[i] != -1)
res = Math.max(res, (long)(a[i] ^ aux[i]));
}
return res;
}
public static void main(String[]args)throws Throwable
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
arr = new int[n];
rev = new int[n];
int lst = n - 1;
for(int i = 0 ; i < n ; ++i)
{
arr[i] = sc.nextInt();
rev[lst--] = arr[i];
}
System.out.println(Math.max(solve(arr), solve(rev)));
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); }
String next() throws IOException
{
while(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 9c4b1668dd8b4edecbf0311ee0d19345 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main
{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static String[] data;
public static void main (String[] args) throws java.lang.Exception
{
Reader s=new Reader();
int n = s.nextInt();
ArrayList<Long> list = new ArrayList<Long>();
//while(n != 0) {
for(int i = 0; i < n; i++){
list.add(s.nextLong());
}
long maxNo = solve(list);
Collections.reverse(list);
System.out.println(Math.max(maxNo, solve(list)));
//}
}
static long solve(ArrayList<Long> list) {
Stack<Long> stack = new Stack<Long>();
long maxNo = -1;
int n = list.size();
for(int i = 0; i < n; i++){
while (!stack.empty() && stack.peek() < list.get(i))
stack.pop();
stack.push(list.get(i));
long temp = stack.pop();
if(stack.size() >= 1)
maxNo = Math.max(maxNo, temp ^ stack.peek());
stack.push(temp);
}
return maxNo;
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | b572dac60f3bee4379151b6c88c92fc0 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes |
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Stack;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ListIterator;
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
//Scanner sc = new Scanner (System.in);
//System.out.println("enter");
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = sc.nextInt();
int i ,max=0;
int a[] = new int [n];
for(i=0 ;i<n;i++)
a[i] =sc.nextInt();
Stack <Integer> st = new Stack ();
int ans =0;
int top;
for (i=0 ;i<n;i++)
{
if(!st.isEmpty())
{
top = st.peek();
if((top ^ a[i] )> max)
max = top ^ a[i];
if(top > a[i] )
{ st.push(a[i]);
continue;
}
st.pop();
while(!st.isEmpty() )
{
top = st.peek();
if((top ^ a[i] )> max)
max = top ^ a[i];
if(top > a[i])
break;
else
st.pop();
}
}
st.push(a[i]);
}
w.println(max);
w.close();
}
}
class InputReader {
private final InputStream st;
private final byte[] buf = new byte[8192];
private int cc, sc;
private SpaceCharFilter f;
public InputReader(InputStream st) {
this.st = st;
}
public int t() {
if (sc == -1)
throw new InputMismatchException();
if (cc >= sc) {
cc = 0;
try {
sc = st.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (sc <= 0)
return -1;
}
return buf[cc++];
}
public int nextInt() {
int c = t();
while (isSpaceChar(c)) {
c = t();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = t();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = t();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = t();
while (isSpaceChar(c)) {
c = t();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = t();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = t();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = t();
while (isSpaceChar(c)) {
c = t();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = t();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = t();
while (isSpaceChar(c))
c = t();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = t();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (f != null)
return f.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | bb5eb9b07da1965c55ed47690e902f80 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;
/**ID: sinbadc1
LANG: JAVA
TASK: wormhole
*/
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[] ar=new int[n];
String s=br.readLine();
StringTokenizer st=new StringTokenizer(s);
for(int i=0;i<n;i++){
ar[i]=Integer.parseInt(st.nextToken());
}
Stack<Integer> stack=new Stack<>();
int res=-1;
for(int i=0;i<n;i++){
int curr=ar[i];
if(stack.isEmpty()){
stack.push(curr);
}
else{
while(!stack.isEmpty() && curr>stack.peek()){
res=Math.max(res, curr^stack.pop());
}
if(!stack.isEmpty()){
res=Math.max(res, curr^stack.peek());
}
stack.push(curr);
}
}
System.out.println(res);
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 98642150cb79b4c05f8999e9380d15ca | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
//--------Solution-------------------------------------------------------//
int n = sc.nextInt();
long ans=0;
ArrayDeque<Long> a = new ArrayDeque<>(n);
boolean next=true;
long s = sc.nextLong();
long f = s;
a.push(s);
for(int i=0; i<n-1; i++){
if(next) s = sc.nextLong();
if(a.isEmpty()) {a.push(s); next=true;}
else if(a.getFirst()>s) {
ans = Math.max(ans,s^a.getFirst());
a.push(s);
next=true;
}
else{
next = false;
long c = a.pop()^s;
ans = Math.max(ans,c);
i--;
}
}
out.println(ans);
//-----------------------------------------------------------------------//
out.close();
}
//-----------Helper Functions------------------------------------------------//
static int[] readIntArray(MyScanner sc,int n){
int[] a = new int[n];
for(int i=0;i<n;i++) a[i]= sc.nextInt();
return a;
}
static long[] readLongArray(MyScanner sc,int n){
long[] a = new long[n];
for(int i=0;i<n;i++) a[i]=sc.nextLong();
return a;
}
static void printIntArray(PrintWriter out,int[] a){
for(int i:a) out.print(i+" ");
out.println();
}
static boolean nextPermutation(int[] a){
int i = a.length - 1;
while(i>0 && a[i-1]>=a[i]) i--;
if(i==0) return false;
int j = a.length - 1;
while(a[j]<=a[i-1]) j--;
int temp = a[i-1];
a[i-1]=a[j];
a[j]=temp;
j = a.length - 1;
while(i<j){
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++; j--;
}
return true;
}
static long max_subarray(long[] a){
long lmax = a[0], gmax=a[0];
for(int i=1; i<a.length; i++){
lmax = Math.max(a[i],lmax+a[i]);
gmax = Math.max(lmax,gmax);
}
return gmax;
}
//-----------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;
}
}
}
//-----------------------Helper Classes------------------------------------------//
class Pair implements Comparable<Pair>
{
int first;
int second;
Pair(int f,int s){
first=f;
second=s;
}
public int compareTo(Pair p){
return this.first - p.first;
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 7f1ce6c7b18e5aca969dd30e32418b96 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String arg[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] ip = br.readLine().split(" ");
int[] arr = new int[ip.length];
for(int i=0; i<arr.length; i++) arr[i] = Integer.parseInt(ip[i]);
int max = -1;
Stack<Integer> st = new Stack<>();
for(int i=0; i<arr.length; i++) {
while(!st.empty()) {
int top = st.peek();
max = max < (top ^ arr[i]) ? top ^ arr[i] : max;
if(top > arr[i]) break;
st.pop();
}
st.push(arr[i]);
}
System.out.println(max);
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | e372204cfe45df22c83c566a9964370f | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;
public class MaximumXor {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
// code goes here
int n = nextInt(br);
int[] arr = nextIntArray(br, n);
Stack<Pair<Long, Integer>> stack = new Stack<>();
long max = Integer.MIN_VALUE;
for(int i = 0; i < n; i++){
if(stack.size() < 1){
stack.add(new Pair<>((long) arr[i], i));
}else {
if(stack.peek().first >= arr[i]) {
stack.add(new Pair<>((long) arr[i], i));
continue;
}
while (!stack.isEmpty()){
if(stack.peek().first >= arr[i]) break;
Pair<Long, Integer> pair = stack.pop();
max = Math.max(max, pair.first ^ arr[i]);
if(!stack.isEmpty())
max = Math.max(max, pair.first ^ stack.peek().first);
}
stack.add(new Pair<>((long) arr[i], i));
}
}
while (!stack.isEmpty()){
Pair<Long, Integer> pair = stack.pop();
if(!stack.isEmpty())
max = Math.max(max, pair.first ^ stack.peek().first);
}
sb.append(max);
System.out.print(sb.toString());
}
private static int nextInt(BufferedReader br) throws IOException{
return Integer.parseInt(br.readLine());
}
private static int[] nextIntArray(BufferedReader br, int n) throws IOException{
StringTokenizer st = new StringTokenizer(br.readLine());
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = Integer.parseInt(st.nextToken());
}
return arr;
}
static class Pair<A, B>{
A first;
B second;
public Pair(A first, B second){
this.first = first;
this.second = second;
}
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | c92df7f520a842b7498207b8e95f3b21 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Stack;
import java.util.StringTokenizer;
public class MaximumXorSecondry {
static InputStream in = System.in ;
PrintWriter out;
private static byte[] inbuf = new byte[1024 * 1024];
public static int lenbuf = 0;
public static int ptrbuf = 0;
public static int MOD = 1000000007;
public static void main(String args[]) {
int n = ni();
int[] arr = new int[n + 1];
for (int i = 1; i <= n; i++)
arr[i] = ni();
long maxXor = 0;
Stack<Integer> st = new Stack<>();
st.push(arr[1]);
for (int i = 2; i <= n; i++) {
int tempXor = 0;
tempXor = arr[i] ^ st.peek();
if (tempXor > maxXor)
maxXor = tempXor;
while (!st.isEmpty() && arr[i] > st.peek()) {
st.pop();
if (!st.isEmpty()){
tempXor = arr[i] ^ st.peek();
if (tempXor > maxXor)
maxXor = tempXor;
}
}
st.push(arr[i]);
}
System.out.println(maxXor);
}
class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
private static int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = in.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean inSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && inSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(inSpaceChar(b))) { // when nextLine, (inSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(inSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private static int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = true;
// private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (!oj)
System.out.println(Arrays.deepToString(o));
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 4b1faa68b03c6c676e09020ec94c9330 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes |
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class j6 implements Runnable {
long md=1000000007;
long power(long x, long y, long p)
{
long res = 1;
x=x % p;
while (y > 0)
{
if((y & 1)==1)
res = ((res%p) * (x%p))% p;
y =y >> 1;
x =((x%p)*(x%p))%p;
}
return res;
}
public void run(){
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n=in.nextInt();
long maxor=0;
Stack<Long> s=new Stack<Long>();
if(n>=2)
{
long x=in.nextLong();
s.push(x);
long y=in.nextLong();
s.push(y);
maxor=x^y;
//w.println("maxor: "+maxor);
for(int i=2;i<n;i++)
{
long a=in.nextLong();
if(a<s.peek())
{ maxor=Long.max(maxor, a^s.peek());
s.push(a);
//w.println("i is: "+i+" maxor: "+maxor+" stack "+s);
}
else if(a>s.peek())
{
long popp=-1;
popp=s.pop();
maxor=Long.max(maxor, a^popp);
while(!s.isEmpty() && s.peek()>popp && a>s.peek())
{
popp=s.pop();
maxor=Long.max(maxor, a^popp);
}
if(!s.isEmpty() && s.peek()>popp)
maxor=Long.max(maxor, a^s.peek());
s.push(a);
}
//w.println("i is: "+i+" maxor: "+maxor+" stack "+s);
}
}
else if(n==1)
maxor=in.nextLong();
w.println(maxor);
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
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 j6(),"j6",1<<26).start();
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | a67db297024050afbb0fdcc2a0cfee81 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | //package practice;
import java.util.*;
public class Main
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}
long max = -1;
int top;
Stack<Integer> stack = new Stack<>();
int i=0;
while(i<n)
{
int a = arr[i];
if(stack.isEmpty())
{
stack.push(a);
i++;
}
else
{
top = stack.peek();
if(stack.peek()>a)
{
stack.push(arr[i]);
i++;
}
else
stack.pop();
max = Math.max(max, top^a);
}
}
System.out.println(max);
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 52e9adfb8d092e0df475a8727e73a3e5 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.util.*;
import java.io.*;
public class a {
static long mod = 1000000007;
public static void main(String[] args) throws IOException
{
input.init(System.in);
PrintWriter out = new PrintWriter(new PrintStream(System.out));
//input.init(new FileInputStream(new File("input.txt")));
//PrintWriter out = new PrintWriter(new File("output.txt"));
int n = input.nextInt();
int[] data = new int[n];
for(int i = 0; i<n; i++) data[i] = input.nextInt();
int res = 0;
int[] stk = new int[n+2];
for(int i = 0; i<n; i++)
{
int at = data[i];
while(stk[0]>0)
{
int x = stk[stk[0]];
res = Math.max(res, at^x);
if(x<at) stk[stk[0]--] = 0;
else break;
}
stk[++stk[0]] = at;
//out.println(stk[0]+" "+stk[stk[0]]);
//if(stk[0] >= 2) res = Math.max(res, stk[stk[0]] ^ stk[stk[0]+1]);
}
out.println(res);
out.close();
}
static class State implements Comparable<State>
{
int at, dist;
public State(int a, int d)
{
at = a;
dist = d;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(State o) {
// TODO(mkirsche): Auto-generated method stub
return this.dist - o.dist;
}
}
static class Edge
{
int to, len;
public Edge(int t, int l)
{
to = t; len = l;
}
}
static long[][] comb(int n)
{
long[][] res = new long[n+1][n+1];
Arrays.fill(res[0], 0);
for(int i = 0; i<=n; i++) res[i][0] = 1;
for(int i = 1; i<=n; i++)
for(int j = 1; j<=n; j++)
res[i][j] = (res[i-1][j-1] + res[i-1][j])%mod;
return res;
}
static long gcd(long a, long b)
{
if(b==0) return a;
return gcd(b, a%b);
}
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("");
}
/**
* @return
*/
public static boolean hasNext() {
// TODO(mkirsche): Auto-generated method stub
return tokenizer.hasMoreTokens();
}
/** 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();
}
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 55c7e692f9ec573f28aa13c371656048 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.util.Scanner;
import java.util.Stack;
public class MaxXOR {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
long arr[] = new long[n];
for(int i=0; i<n; i++) {
arr[i] = sc.nextLong();
}
long ans =0;
Stack<Long> st = new Stack<>();
for(int i=0; i<n; i++) {
while(!st.isEmpty()) {
if(arr[i] > st.peek()) {
ans = Math.max(ans, (st.peek()^arr[i]));
st.pop();
}else {
ans = Math.max(ans, st.peek()^arr[i]);
break;
}
}
st.push(arr[i]);
}
System.out.println(ans);
}catch(Exception e) {
return;
}
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | ba89fad48418b42daf9589e66a3439de | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
FastReader f = new FastReader();
solve(f);
}
private static void solve(FastReader scr) {
int n = scr.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scr.nextInt();
}
Stack<Integer> s = new Stack<>();
long max = 0, ans = 0;
for (int i = 0; i < n; ) {
if (s.isEmpty() || s.peek().compareTo(arr[i]) > 0) {
if (!s.empty()) {
ans = s.peek() ^ arr[i];
if (max < ans) max = ans;
}
s.push(arr[i]);
i++;
} else {
while (!s.isEmpty() && s.peek().compareTo(arr[i]) < 0) {
ans = arr[i] ^ s.pop();
if (max < ans) max = ans;
}
}
}
System.out.println(max);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
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;
}
}
} | Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | ad8e005e33b9446fd3fa66f4465de2c0 | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | 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.Stack;
import java.util.StringTokenizer;
public class MaximumXorSecondary implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
public void solve() {
int n = in.ni();
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.ni();
}
Stack<Integer> stack = new Stack<>();
int result = 0;
for (int i = 0; i < n; i++) {
while (!stack.isEmpty()) {
int top = stack.peek();
int xor = x[i] ^ top;
result = Math.max(xor, result);
if (x[i] > top) {
stack.pop();
} else break;
}
stack.push(x[i]);
}
out.println(result);
}
@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 (MaximumXorSecondary instance = new MaximumXorSecondary()) {
instance.solve();
}
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 5500ba0926b5a4fe5a8a2bc3193af64b | train_001.jsonl | 1362929400 | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
// int t = sc.nextInt();
// while(t-- > 0) {
int n = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
long ans = getMax(arr);
System.out.println(ans);
// }
}
public static long getMax(int[] arr) {
Stack<Integer> st = new Stack<>();
int[] nge = new int[arr.length];
long maxXOR = 0;
for(int i = 0; i < arr.length; i++) {
while(!st.isEmpty() && arr[i] > arr[st.peek()]) {
nge[st.peek()] = arr[i];
st.pop();
}
st.push(i);
}
for(int i = 0; i < arr.length; i++) {
if(nge[i] != 0) {
maxXOR = Math.max(maxXOR, arr[i]^nge[i]);
nge[i] = 0;
}
}
st = new Stack<>();
for(int i = arr.length-1; i >= 0; i--) {
while(!st.isEmpty() && arr[i] > arr[st.peek()]) {
nge[st.peek()] = arr[i];
st.pop();
}
st.push(i);
}
for(int i = 0; i < arr.length; i++) {
if(nge[i] != 0) {
maxXOR = Math.max(maxXOR, arr[i]^nge[i]);
}
}
return maxXOR;
}
}
| Java | ["5\n5 2 1 4 3", "5\n9 8 3 5 7"] | 1 second | ["7", "15"] | NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}. | Java 8 | standard input | [
"two pointers"
] | c9b9c56d50eaf605e7bc088385a42a1d | The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109). | 1,800 | Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r]. | standard output | |
PASSED | 8a4c8317cfb04d0d86d18f1f6b0d8f9c | train_001.jsonl | 1387893600 | You are given a matrix consisting of digits zero and one, its size is n × m. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations?Let's assume that the rows of matrix a are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. A matrix cell on the intersection of the i-th row and the j-th column can be represented as (i, j). Formally, a submatrix of matrix a is a group of four integers d, u, l, r (1 ≤ d ≤ u ≤ n; 1 ≤ l ≤ r ≤ m). We will assume that the submatrix contains cells (i, j) (d ≤ i ≤ u; l ≤ j ≤ r). The area of the submatrix is the number of cells it contains. | 512 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import static java.lang.Integer.parseInt;
import static java.lang.Math.max;
import java.util.Arrays;
import java.util.StringTokenizer;
public class MaximumSubmatrix2 {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer(reader.readLine());
int n = parseInt(tok.nextToken()), m = parseInt(tok.nextToken());
int[][] mat = new int[m][n];
StringBuilder s;
for (int i = 0; i < n; i++) {
s = new StringBuilder(reader.readLine());
for (int j = 0; j < m; j++) {
mat[j][i] = s.charAt(j) - '0';
}
}
for (int i = 0; i < n; i++) {
for (int j = 1; j < m; j++) {
mat[j][i] = mat[j][i] == 0 ? 0 : mat[j][i] + mat[j - 1][i];
}
}
for (int i = 0; i < m; i++) {
Arrays.sort(mat[i]);
}
long max = 0;
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
if (mat[j][i] != 0) {
max = max(mat[j][i] * (n - i), max);
}
}
}
System.out.println(max);
}
}
| Java | ["1 1\n1", "2 2\n10\n11", "4 3\n100\n011\n000\n101"] | 2 seconds | ["1", "2", "2"] | null | Java 8 | standard input | [
"dp",
"implementation",
"sortings"
] | 0accc8b26d7d684aa6e60e58545914a8 | The first line contains two integers n and m (1 ≤ n, m ≤ 5000). Next n lines contain m characters each — matrix a. Matrix a only contains characters: "0" and "1". Note that the elements of the matrix follow without any spaces in the lines. | 1,600 | Print a single integer — the area of the maximum obtained submatrix. If we cannot obtain a matrix of numbers one, print 0. | standard output | |
PASSED | e92e792ec13f8e1639cb24af2bf6f406 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes |
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class D515 {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(1, in, out);
out.close();
}
static class Solver {
char[][] field;
int n;
int m;
int[] dx = {-1, 0, 1, 0};
int[] dy = {0, 1, 0, -1};
char[] c = {'<', 'v', '>', '^'};
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
field = new char[n][m];
for (int i = 0; i < n; i++) {
field[i] = in.next().toCharArray();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (field[i][j] == '.') {
dfs(i, j);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (field[i][j] == '.') {
out.println("Not unique");
return;
}
}
}
for (int i = 0; i < n; i++) {
out.println(field[i]);
}
}
public void toNext(int y, int x) {
for (int dir = 0; dir < 4; dir++) {
int ny = y + dy[dir];
int nx = x + dx[dir];
if (nx < 0 || m <= nx || ny < 0 || n <= ny) continue;
if (field[ny][nx] == '.') {
dfs(ny, nx);
}
}
}
public void dfs(int y, int x) {
int count = 0;
int ndir = 0;
int ny = 0;
int nx = 0;
for (int dir = 0; dir < 4; dir++) {
ny = y + dy[dir];
nx = x + dx[dir];
if (nx < 0 || m <= nx || ny < 0 || n <= ny) continue;
if (field[ny][nx] == '.') {
ndir = dir;
count++;
}
}
if (count == 1) {
ny = y + dy[ndir];
nx = x + dx[ndir];
field[ny][nx] = c[ndir];
int opposite = (ndir + 2) % 4;
field[y][x] = c[opposite];
toNext(ny,nx);
// for (int dir = 0; dir < 4; dir++) {
// int nny = ny + dy[dir];
// int nnx = nx + dx[dir];
// if (nnx < 0 || m <= nnx || nny < 0 || n <= nny) continue;
// if (field[nny][nnx] == '.') {
// dfs(nny, nnx);
// }
// }
}
}
// public void swapChar(int y, int x, char a) {
// StringBuilder sb = new StringBuilder(field[y]);
// sb.setCharAt(x, a);
// field[y] = sb.toString();
// }
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 34aa380c76e2bf9bd3a9f3bdf04f4783 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.*;
import java.util.*;
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(in, out);
out.close();
}
}
class Graph {
private Set<Integer> neighbours[];
@SuppressWarnings("unchecked")
public Graph(int n) {
neighbours = new Set[n];
for(int i=0;i<n;i++){
neighbours[i] = new HashSet<>();
}
}
public void addEdge(int from, int to) {
neighbours[from].add(to);
neighbours[to].add(from);
}
public Set<Integer> getNeighbours(int v) {
return neighbours[v];
}
}
class TaskD {
public void solve(InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
char tab[][] = new char[n][m];
for(int i=0;i<n;i++) {
tab[i] = in.next().toCharArray();
}
Queue<Pair> queue = new ArrayDeque<>();
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(tab[i][j] != '*' && hasOnlyOneFreeNeighbour(tab,n,m,i,j) ) {
queue.add(new Pair(i,j));
}
}
}
while(!queue.isEmpty()) {
Pair cell = queue.remove();
if(tab[cell.x][cell.y] != '.') continue;
Pair neighbourCell = findFreeNeighbourCell(tab,n,m,cell);
if(neighbourCell == null) break;
assignValues(tab, cell.x, cell.y, neighbourCell.x, neighbourCell.y);
List<Pair> list = findNext(tab, n,m, neighbourCell.x, neighbourCell.y);
for(Pair pair : list) queue.add(pair);
}
if(valid(tab,n,m)) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
out.print(tab[i][j]);
}
out.printLine();
}
} else {
out.printLine("Not unique");
}
}
private List<Pair> findNext(char[][] tab, int n, int m, int i, int j) {
List<Pair> list = new ArrayList<>();
if(hasOnlyOneFreeNeighbour(tab,n,m,i-1,j)) list.add(new Pair(i-1,j));
if(hasOnlyOneFreeNeighbour(tab,n,m,i+1,j)) list.add(new Pair(i+1,j));
if(hasOnlyOneFreeNeighbour(tab,n,m,i,j-1)) list.add(new Pair(i,j-1));
if(hasOnlyOneFreeNeighbour(tab,n,m,i,j+1)) list.add(new Pair(i,j+1));
return list;
}
private boolean valid(char[][] tab, int n, int m) {
boolean valid = true;
for(int i=0;i<n;i++) {
for (int j = 0; j < m; j++) {
if(tab[i][j] == '.') {
valid = false;
break;
}
}
}
return valid;
}
private void assignValues(char[][] tab, int i, int j, int k, int l) {
if(i == k) {
if(j < l) {
tab[i][j] = '<';
tab[k][l] = '>';
} else {
tab[i][j] = '>';
tab[k][l] = '<';
}
} else {
if(i < k) {
tab[i][j] = '^';
tab[k][l] = 'v';
} else {
tab[i][j] = 'v';
tab[k][l] = '^';
}
}
}
private Pair findFreeNeighbourCell(char tab[][], int n, int m, Pair cell) {
int i = cell.x;
int j = cell.y;
if(i-1 >= 0 && tab[i-1][j] == '.') return new Pair(i-1,j);
if(i+1 < n && tab[i+1][j] == '.') return new Pair(i+1,j);
if(j-1 >= 0 && tab[i][j-1] == '.') return new Pair(i,j-1);
if(j+1 < m && tab[i][j+1] == '.') return new Pair(i,j+1);
return null;
}
private boolean hasOnlyOneFreeNeighbour(char[][] tab,int n, int m, int i, int j) {
if(i < 0 || i >= n || j < 0 || j >= m) return false;
int count = 0;
if(i-1 >= 0 && tab[i-1][j] == '.') count++;
if(i+1 < n && tab[i+1][j] == '.') count++;
if(j-1 >= 0 && tab[i][j-1] == '.') count++;
if(j+1 < m && tab[i][j+1] == '.') count++;
return count == 1;
}
class Pair {
int x,y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
}
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 boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String line = reader.readLine();
if ( line == null ) {
return false;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if ( i != 0 ) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | b586dccc8d54ef73a1cb78b6860bb8fc | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class A {
static final int[] dx = {0, 0, -1, 1};
static final int[] dy = {-1, 1, 0, 0};
static final char[] s1 = {'>','<','v','^'};
static final char[] s2 = {'<','>','^','v'};
static int n, m;
static char[][] grid;
static boolean valid(int x, int y)
{
return x >= 0 && y >= 0 && x < n && y < m && grid[x][y] == '.';
}
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
m = sc.nextInt();
int[] deg = new int[n * m];
grid = new char[n][m];
for(int i = 0; i < n; ++i)
grid[i] = sc.next().toCharArray();
Queue<Integer> q = new LinkedList<>();
boolean[] inQueue = new boolean[n * m];
int cnt = 0;
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j)
if(grid[i][j] == '.')
{
++cnt;
for(int k = 0; k < 4; ++k)
{
int x = i + dx[k], y = j + dy[k];
if(valid(x, y))
++deg[i * m + j];
}
if(deg[i * m + j] == 1)
{
inQueue[i * m + j] = true;
q.add(i * m + j);
}
}
while(!q.isEmpty())
{
--cnt;
int cur = q.remove(), x = cur / m, y = cur % m;
boolean match = grid[x][y] != '.';
for(int k = 0; k < 4; ++k)
{
int i = x + dx[k], j = y + dy[k];
if(valid(i, j))
{
if(--deg[i * m + j] == 1)
{
inQueue[i * m + j] = true;
q.add(i * m + j);
}
if(!match)
{
match = true;
grid[x][y] = s1[k];
grid[i][j] = s2[k];
if(!inQueue[i * m + j])
{
inQueue[i * m + j] = true;
q.add(i * m + j);
}
}
}
}
if(!match)
++cnt;
}
if(cnt != 0)
out.println("Not unique");
else
for(char[] x: grid)
out.println(x);
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader r){ br = new BufferedReader(r);}
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 { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 542ed4dd01d44456067af46e94378f10 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Scanner;
import java.util.Queue;
import java.util.LinkedList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Mouna Cheikhna
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
private static final int[] dx = new int[]{0, 0, -1, 1};
private static final int[] dy = new int[]{-1, 1, 0, 0};
private static final char[] s1 = {'>', '<', 'v', '^'};
private static final char[] s2 = {'<', '>', '^', 'v'};
private int n;
private int m;
private char[][] grid;
private boolean[] inQueue;
private Queue<Integer> queue;
public void solve(int testNumber, Scanner in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
int[] deg = new int[n * m];
grid = new char[n][m];
for (int i = 0; i < n; i++) {
grid[i] = in.next().toCharArray();
}
queue = new LinkedList<>();
inQueue = new boolean[n * m];
int cnt = 0; // count of free cells
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '.') {
cnt++;
// check neighbors
for (int k = 0; k < 4; k++) {
int x = i + dx[k];
int y = j + dy[k];
if (valid(x, y)) {
deg[i * m + j]++;
}
}
if (deg[i * m + j] == 1) { // only one adj free cell
addToQueue(i, j);
}
}
}
}
while (!queue.isEmpty()) {
cnt--;
int current = queue.remove();
int x = current / m;
int y = current % m;
boolean match = grid[x][y] != '.';
for (int k = 0; k < 4; k++) {
int i = x + dx[k];
int j = y + dy[k];
if (valid(i, j)) {
deg[i * m + j]--;
if (deg[i * m + j] == 1) {
addToQueue(i, j);
}
if (!match) {
match = true;
grid[x][y] = s1[k];
grid[i][j] = s2[k];
if (!inQueue[i * m + j]) {
addToQueue(i, j);
}
}
}
}
if (!match) {
cnt++;
}
}
if (cnt != 0) {
out.println("Not unique");
} else {
for (char[] x : grid) {
out.println(x);
}
}
}
private void addToQueue(int i, int j) {
inQueue[i * m + j] = true;
queue.add(i * m + j);
}
private boolean valid(int x, int y) {
return x >= 0 && y >= 0 && x < n && y < m && grid[x][y] == '.';
}
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 16999ecfa69b37fef4b6fe5ea8cec5e5 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import javafx.util.Pair;
import java.util.*;
public class Main {
static int[] dx = {1, -1, 0, 0};
static int[] dy = {0, 0, 1, -1};
static int n, m;
static char[][] map;
static int[][] count;
static Queue<Pair<Integer, Integer>> queue = new LinkedList<>();
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
n = cin.nextInt();
m = cin.nextInt();
map = new char[n][m];
for (int i = 0; i < n; i++) {
map[i] = cin.next().toCharArray();
}
if (!buildCount()) {
System.out.println("Not unique");
cin.close();
return ;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (count[i][j] == 1) {
queue.add(new Pair<>(i, j));
}
}
}
while (!queue.isEmpty()) {
Pair<Integer, Integer> now = queue.poll();
solveOne(now.getKey(), now.getValue());
}
boolean flag = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == '.') {
flag = false;
}
}
}
if (!flag) {
System.out.println("Not unique");
} else {
for (int i = 0; i < n; i++) {
System.out.println(new String(map[i]));
}
}
cin.close();
}
private static boolean solveOne(int x, int y) {
return checkAndPut(x, y, x + 1, y, '^', 'v')
|| checkAndPut(x, y, x - 1, y, 'v', '^')
|| checkAndPut(x, y, x, y + 1, '<', '>')
|| checkAndPut(x, y, x, y - 1, '>', '<');
}
private static boolean checkAndPut(int x, int y, int nx, int ny, char now, char next) {
if (0 <= nx && nx < n && 0 <= ny && ny < m && map[nx][ny] == '.') {
map[x][y] = now;
map[nx][ny] = next;
remove(x, y);
remove(nx, ny);
count[x][y] = -1;
count[nx][ny] = -1;
findOne(x, y);
findOne(nx, ny);
return true;
}
return false;
}
private static void findOne(int x, int y) {
for (int k = 0; k < 4; k++) {
int nx, ny;
nx = x + dx[k];
ny = y + dy[k];
if (nx < 0 || nx >= n) continue;
if (ny < 0 || ny >= m) continue;
if (map[nx][ny] == '.' && count[nx][ny] == 1) {
queue.add(new Pair<>(nx, ny));
}
}
}
private static void remove(int x, int y) {
for (int k = 0; k < 4; k++) {
int nx, ny;
nx = x + dx[k];
ny = y + dy[k];
if (nx < 0 || nx >= n) continue;
if (ny < 0 || ny >= m) continue;
if (map[nx][ny] == '.') count[nx][ny]--;
}
}
private static boolean buildCount() {
count = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == '*') continue;
for (int k = 0; k < 4; k++) {
int nx, ny;
nx = i + dx[k];
ny = j + dy[k];
if (nx < 0 || nx >= n) continue;
if (ny < 0 || ny >= m) continue;
if (map[nx][ny] == '.') count[i][j]++;
}
if (count[i][j] == 0) {
return false;
}
}
}
return true;
}
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 59a8b35263f3a717c6d7873caf986bfe | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes |
// ~/BAU/ACM-ICPC/Teams/A++/BlackBurn95
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
static int [] dx = {-1,1,0,0},dy = {0,0,-1,1};
static char [] d1 = {'v','^','>','<'}, d2 = {'^','v','<','>'};
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// (new FileReader("input.in"));
StringBuilder out = new StringBuilder();
StringTokenizer tk;
tk = new StringTokenizer(in.readLine());
int n = parseInt(tk.nextToken()),m = parseInt(tk.nextToken());
char [][] g = new char[n][m];
for(int i=0; i<n; i++)
g[i] = in.readLine().toCharArray();
int nx,ny,tx,ty;
int [][] deg = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(g[i][j]=='*') continue;
for(int k=0; k<4; k++) {
nx = i+dx[k];
ny = j+dy[k];
if(nx<0 || ny<0 || nx>=n || ny>=m || g[nx][ny]=='*') continue;
deg[i][j]++;
}
}
}
Queue<point> q = new LinkedList<>();
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
if(deg[i][j]==1)
q.add(new point(i,j));
point p;
while(!q.isEmpty()) {
p = q.remove();
for(int i=0; i<4; i++) {
nx = p.x+dx[i];
ny = p.y+dy[i];
if(nx>=0 && nx<n && ny>=0 && ny<m && g[nx][ny]=='.') {
g[p.x][p.y] = d1[i];
g[nx][ny] = d2[i];
for(int j=0; j<4; j++) {
tx = nx+dx[j];
ty = ny+dy[j];
if(tx>=0 && tx<n && ty>=0 && ty<m && g[tx][ty]=='.') {
deg[tx][ty]--;
if(deg[tx][ty]==1) q.add(new point(tx,ty));
}
}
break;
}
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(g[i][j]=='.') {
System.out.println("Not unique");
return;
}
out.append(g[i][j]);
}
out.append("\n");
}
System.out.print(out);
}
}
class point {
int x,y;
public point(int x,int y) {
this.x = x;
this.y = y;
}
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | f20feedbbcd0341bd90ec272baca7cf0 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class DrazilTiles {
int[] dx = new int[]{-1, 0, 0, 1};
int[] dy = new int[]{0, -1, 1, 0};
char[] dir = new char[]{'U', 'L', 'R', 'D'};
void solve() {
int n = in.nextInt(), m = in.nextInt();
char[][] B = new char[n][];
for (int i = 0; i < n; i++) B[i] = in.nextToken().toCharArray();
int cnt = 0;
int[][] deg = new int[n][m];
Queue<int[]> qu = new LinkedList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (B[i][j] == '.') {
cnt++;
for (int k = 0; k < 4; k++) {
int x = i + dx[k], y = j + dy[k];
if (x >= 0 && x < n && y >= 0 && y < m && B[x][y] == '.') deg[i][j]++;
}
if (deg[i][j] == 1) qu.offer(new int[]{i, j});
}
}
}
while (!qu.isEmpty()) {
int[] c = qu.poll();
int x = c[0], y = c[1];
if (B[x][y] != '.') continue;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && B[nx][ny] == '.') {
cnt -= 2;
switch (dir[i]) {
case 'U':
B[x][y] = 'v';
B[nx][ny] = '^';
break;
case 'D':
B[x][y] = '^';
B[nx][ny] = 'v';
break;
case 'L':
B[x][y] = '>';
B[nx][ny] = '<';
break;
case 'R':
B[x][y] = '<';
B[nx][ny] = '>';
}
for (int j = 0; j < 4; j++) {
int mx = nx + dx[j], my = ny + dy[j];
if (mx >= 0 && mx < n && my >= 0 && my < m && B[mx][my] == '.') {
if (--deg[mx][my] == 1) {
qu.offer(new int[]{mx, my});
}
}
}
}
}
}
if (cnt != 0) {
out.println("Not unique");
} else {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print(B[i][j]);
}
out.println();
}
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new DrazilTiles().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | afa0752498df781dc6d010a8b05b106c | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class DrazilTiles {
int[] dx = new int[]{-1, 0, 0, 1};
int[] dy = new int[]{0, -1, 1, 0};
char[] dir = new char[]{'U', 'L', 'R', 'D'};
void solve() {
int n = in.nextInt(), m = in.nextInt();
char[][] B = new char[n][];
for (int i = 0; i < n; i++) B[i] = in.nextToken().toCharArray();
int cnt = 0;
int[][] deg = new int[n][m];
Queue<int[]> qu = new LinkedList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (B[i][j] == '.') {
cnt++;
for (int k = 0; k < 4; k++) {
int x = i + dx[k], y = j + dy[k];
if (x >= 0 && x < n && y >= 0 && y < m && B[x][y] == '.') deg[i][j]++;
}
if (deg[i][j] == 1) qu.offer(new int[]{i, j});
}
}
}
while (!qu.isEmpty()) {
int[] c = qu.poll();
int x = c[0], y = c[1];
if (B[x][y] != '.') continue;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && B[nx][ny] == '.') {
cnt -= 2;
switch (dir[i]) {
case 'U':
B[x][y] = 'v';
B[nx][ny] = '^';
break;
case 'D':
B[x][y] = '^';
B[nx][ny] = 'v';
break;
case 'L':
B[x][y] = '>';
B[nx][ny] = '<';
break;
case 'R':
B[x][y] = '<';
B[nx][ny] = '>';
}
for (int j = 0; j < 4; j++) {
int mx = nx + dx[j], my = ny + dy[j];
if (mx >= 0 && mx < n && my >= 0 && my < m && B[mx][my] == '.') {
if (--deg[mx][my] == 1) {
qu.offer(new int[]{mx, my});
}
}
}
for (int j = 0; j < 4; j++) {
int mx = x + dx[j], my = y + dy[j];
if (mx >= 0 && mx < n && my >= 0 && my < m && B[mx][my] == '.') {
if (--deg[mx][my] == 1) {
qu.offer(new int[]{mx, my});
}
}
}
}
}
}
if (cnt != 0) {
out.println("Not unique");
} else {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print(B[i][j]);
}
out.println();
}
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new DrazilTiles().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 00df45f027c4720a51ddb5ce75bb21b7 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
static int mod = (int)1e9+7;
static int N = (int)2e3+10;
static int ci[] = {1, 0, -1, 0};
static int cj[] = {0, 1, 0, -1};
int n, m;
char[][] a = new char[N][N];
int[][] deg = new int[N][N];
void fill(int i, int j) {
if (deg[i][j] != 1) return;
deg[i][j] = -1;
for (int k = 0; k < 4; k++)
if (deg[i + ci[k]][j + cj[k]] != -1) {
deg[i + ci[k]][j + cj[k]] = -1;
if (k == 0) {
a[i][j] = '^';
a[i+1][j] = 'v';
} else if (k == 1) {
a[i][j] = '<';
a[i][j+1] = '>';
} else if (k == 2) {
a[i-1][j] = '^';
a[i][j] = 'v';
} else {
a[i][j-1] = '<';
a[i][j] = '>';
}
for (int kk = 0; kk < 4; kk++) {
if (deg[i + ci[kk]][j + cj[kk]] != -1)
deg[i + ci[kk]][j + cj[kk]]--;
if (deg[i + ci[k] + ci[kk]][j + cj[k] + cj[kk]] != -1)
deg[i + ci[k] + ci[kk]][j + cj[k] + cj[kk]]--;
}
for (int kk = 0; kk < 4; kk++) {
fill(i + ci[kk], j + cj[kk]);
fill(i + ci[k] + ci[kk], j + cj[k] + cj[kk]);
}
return;
}
}
void work() throws Exception {
//in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//
Scanner cin = new Scanner(System.in);
/////////////////////////////////////////
for(int i = 0; i < N; i ++) {
for(int j = 0; j < N; j ++) {
deg[i][j] = -1;
}
}
n = cin.nextInt();
m = cin.nextInt();
for (int i = 1; i <= n; i++) {
String s = cin.next();
for (int j = 1; j <= m; j++){
a[i][j] = s.charAt(j-1);
if (a[i][j] == '*')
deg[i][j] = -1;
else
deg[i][j] = 0;
}
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (deg[i][j] == 0)
for (int k = 0; k < 4; k++){
if(deg[i + ci[k]][j + cj[k]] != -1)
deg[i][j] += 1;
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
fill(i, j);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (a[i][j] == '.') {
out.println("Not unique");
return ;
}
for (int i = 1; i <= n; i ++){
for(int j = 1; j <= m; j ++) {
out.print(a[i][j]);
}
out.println();
}
}
// BufferedReader in;
// StringTokenizer str = null;
static PrintWriter out;
// private String next() throws Exception{
// while (str == null || !str.hasMoreElements())
// str = new StringTokenizer(in.readLine());
// return str.nextToken();
// }
// private int nextInt() throws Exception{
// return Integer.parseInt(next());
// }
// private long nextLong() throws Exception{
// return Long.parseLong(next());
// }
static int dx[] = {0,1,0,-1};
static int dy[] = {1,0,-1,0};
class pair implements Comparable<pair>{
int first, second;
pair(int x, int y) {
first = x;
second = y;
}
public int compareTo(pair o) {
// TODO auto-generated method stub
if(first != o.first) return ((Integer)first).compareTo(o.first);
else return ((Integer)second).compareTo(o.second);
}
}
DecimalFormat df=new DecimalFormat("0.00");
public static void main(String[] args) throws Exception{
Main wo = new Main();
wo.work();
out.close();
}
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 4ef3aa1c3e36ca0f885f938814b75108 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.*;
import java.util.*;
public class F{
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out);
n=sc.nextInt();
m=sc.nextInt();
V=n*m;
a=new char [n][m];
for(int i=0;i<n;i++)
a[i]=sc.next().toCharArray();
deg=new int [V];
int [] q=new int [V+10];
int front=0,back=0;
int cntDot=0;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++) {
if(a[i][j]=='.') {
cntDot++;
for(int k=0;k<4;k+=2) {
int nr=i+dx[k];
int nc=j+dy[k];
if(valid(nr, nc) && a[nr][nc]=='.') {
deg[i*m+j]++;
deg[nr*m+nc]++;
}
}
if(deg[i*m+j]==1)
q[back++]=i*m+j;
}
}
boolean ok=true;
while(front!=back) {
int p=q[front++];
int r=p/m;
int c=p%m;
if(a[r][c]!='.')
continue;
cntDot-=2;
boolean done=false;
for(int k=0;k<4;k++) {
int nr=r+dx[k];
int nc=c+dy[k];
if(valid(nr, nc) && a[nr][nc]=='.') {
done=true;
a[r][c]=s1[k];
a[nr][nc]=s2[k];
for(int k2=0;k2<4;k2++) {
int nnr=nr+dx[k2];
int nnc=nc+dy[k2];
if(valid(nnr, nnc) && --deg[nnr*m+nnc]==1)
q[back++]=nnr*m+nnc;
}
break;
}
}
ok &=done;
}
if(!ok || cntDot>0)
pw.println("Not unique");
else
for(int i=0;i<n;i++)
pw.println(new String(a[i]));
pw.flush();
pw.close();
}
static int [] deg;
static int n,m,V;
static char [][] a;
static int [] dx={1,-1,0,0};
static int [] dy={0,0,1,-1};
static char [] s1={'^','v','<','>'};
static char [] s2={'v','^','>','<'};
static boolean valid(int r,int c){
return r>=0 && c>=0 && r<n && c<m;
}
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;}
}
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 985cd072bd50f9dc79bda996dfd14883 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main implements Runnable {
private boolean is_good(int x, int y){
if(x >= 0 && x < r && y >= 0 && y < c && map[x][y] == '.')
return true;
else
return false;
}
private void set(int x, int y, int xx, int yy){
if(x+y > xx + yy){
int t = x;
x = xx;
xx = t;
t = y;
y = yy;
yy = t;
}
if(x == xx){
map[x][y] = '<';
map[xx][yy] = '>';
}
else{
map[x][y] = '^';
map[xx][yy] = 'v';
}
}
private void update(int x, int y){
degree[x][y] = 0;
for(int k = 0; k < 4; k++){
int nx = x + dx[k];
int ny = y + dy[k];
if(is_good(nx, ny)){
degree[nx][ny]--;
if(degree[nx][ny] == 1){
q.add(nx); q.add(ny);
}
}
}
}
int r, c;
char[][] map;
int[] dx = {1, -1, 0, 0};
int[] dy = {0, 0, 1, -1};
int[][] degree;
Queue<Integer> q;
public void solve() throws IOException {
r = nextInt();
c = nextInt();
map = new char[r][c];
for(int i = 0; i < r; i++) map[i] = nextToken().toCharArray();
degree = new int[r][c];
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
if(is_good(i, j))
for(int k = 0; k < 4; k++){
int nx = i + dx[k];
int ny = j + dy[k];
if(is_good(nx, ny))
degree[i][j]++;
}
q = new LinkedList<>();
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
if(degree[i][j] == 1){
q.add(i);
q.add(j);
}
}
}
//out.println(q.size());
while(!q.isEmpty()){
int x = q.poll();
int y = q.poll();
for(int k = 0; k < 4; k++){
int nx = x + dx[k];
int ny = y + dy[k];
if(is_good(nx, ny)){
set(x, y, nx,ny);
update(x, y);
update(nx, ny);
break;
}
}
}
boolean done = true;
for(int i = 0; i < r; i++){
//out.println(new String(map[i]));
for(int j = 0; j < c; j++){
if(map[i][j] == '.')
done = false;
}
}
if(!done)
out.println("Not unique");
else{
for(int i = 0; i < r; i++){
out.println(new String(map[i]));
}
}
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void debug(Object... arr){
System.out.println(Arrays.deepToString(arr));
}
public void print1Int(int[] a){
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public void print2Int(int[][] a){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[0].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = null;
solve();
in.close();
out.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.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());
}
PrintWriter out;
BufferedReader in;
StringTokenizer tok;
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | f4f307b5cd819617f3c88dd3e993f257 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.StringTokenizer;
public class _515D {
static int n, m;
static char[][] a;
static int[] dx = { 0, 0, 1, -1 };
static int[] dy = { 1, -1, 0, 0 };
static void fill(int i, int j, int ii, int jj) {
if (i == ii) {
a[i][Math.min(j, jj)] = '<';
a[i][Math.max(j, jj)] = '>';
} else {
a[Math.min(i, ii)][j] = '^';
a[Math.max(i, ii)][j] = 'v';
}
// for (int kk = 0; kk < n; kk++)
// System.out.println(String.valueOf(a[kk]));
// System.out.println();
}
static boolean isDot(int i, int j) {
return i >= 0 && i < n && j >= 0 && j < m && a[i][j] == '.';
}
public static void main(String[] args) throws Exception {
Reader.init(System.in);
BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));
n = Reader.nextInt();
m = Reader.nextInt();
a = new char[n][];
for (int i = 0; i < n; i++)
a[i] = Reader.next().toCharArray();
int[] degree = new int[n * m];
Queue<Integer> queue = new ArrayDeque<Integer>(n * m);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (a[i][j] != '.')
continue;
int vertex = i * m + j;
for (int k = 0; k < 4; k++) {
int x = i + dx[k];
int y = j + dy[k];
if (isDot(x, y))
degree[vertex]++;
}
if (degree[vertex] == 1)
queue.add(vertex);
}
while (!queue.isEmpty()) {
int u = queue.poll();
if (degree[u] == 0)
continue; // very important
int x = u / m, y = u % m;
int xx = -1, yy = -1;
int v = -1;
for (int k = 0; k < 4; k++) {
xx = x + dx[k];
yy = y + dy[k];
if (isDot(xx, yy)) {
v = xx * m + yy;
break;
}
}
// remove vertex u and v
fill(x, y, xx, yy);
degree[u] = degree[v] = 0;
for (int k = 0; k < 4; k++) {
int xxx = xx + dx[k];
int yyy = yy + dy[k];
if (isDot(xxx, yyy)) {
int w = xxx * m + yyy;
degree[xxx * m + yyy]--;
if (degree[xxx * m + yyy] == 1)
queue.add(w);
}
}
}
boolean ok = true;
loop: {
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (a[i][j] == '.') {
ok = false;
break loop;
}
}
if (ok) {
for (int i = 0; i < n; i++) {
cout.write(a[i]);
cout.write("\n");
}
} else {
cout.write("Not unique\n");
}
cout.close();
}
static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
final U _1;
final V _2;
private Pair(U key, V val) {
this._1 = key;
this._2 = val;
}
public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) {
return new Pair<U, V>(_1, _2);
}
@Override
public String toString() {
return _1 + " " + _2;
}
@Override
public int hashCode() {
int res = 17;
res = res * 31 + _1.hashCode();
res = res * 31 + _2.hashCode();
return res;
}
@Override
public int compareTo(Pair<U, V> that) {
int res = this._1.compareTo(that._1);
if (res < 0 || res > 0)
return res;
else
return this._2.compareTo(that._2);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Pair))
return false;
Pair<?, ?> that = (Pair<?, ?>) obj;
return _1.equals(that._1) && _2.equals(that._2);
}
}
/** Class for buffered reading int and double values */
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
static class ArrayUtil {
static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(long[] a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(double[] a, int i, int j) {
double tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(char[] a, int i, int j) {
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(boolean[] a, int i, int j) {
boolean tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void reverse(int[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(long[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(double[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(char[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(boolean[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static long sum(int[] a) {
int sum = 0;
for (int i : a)
sum += i;
return sum;
}
static long sum(long[] a) {
long sum = 0;
for (long i : a)
sum += i;
return sum;
}
static double sum(double[] a) {
double sum = 0;
for (double i : a)
sum += i;
return sum;
}
static int max(int[] a) {
int max = Integer.MIN_VALUE;
for (int i : a)
if (i > max)
max = i;
return max;
}
static int min(int[] a) {
int min = Integer.MAX_VALUE;
for (int i : a)
if (i < min)
min = i;
return min;
}
static long max(long[] a) {
long max = Long.MIN_VALUE;
for (long i : a)
if (i > max)
max = i;
return max;
}
static long min(long[] a) {
long min = Long.MAX_VALUE;
for (long i : a)
if (i < min)
min = i;
return min;
}
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | b50b2ca186fc7c800866e1026fc67cfc | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.InputStream;
import java.io.FilterInputStream;
import java.util.NoSuchElementException;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.io.IOException;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Zyflair Griffane
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputUtil in = new InputUtil(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public final int[] dr = { -1, 0, 1, 0 };
public final int[] dc = { 0, -1, 0, 1 };
public char[][] board;
public void solve(int testNumber, InputUtil in, PrintWriter out) {
int rows = in.nextInt();
int cols = in.nextInt();
board = in.nextCharRows(rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == '.') {
force(i, j);
}
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == '.') {
out.println("Not unique");
return;
}
}
}
for (int i = 0; i < rows; i++) {
out.println(new String(board[i]));
}
}
public void force(int row, int col) {
int mask = 0;
for (int i = 0; i < 4; i++) {
if (empty(row + dr[i], col + dc[i])) {
mask |= (1 << i);
}
}
if (Integer.bitCount(mask) != 1) {
return;
}
if (mask == 1) {
board[row][col] = 'v';
row--;
board[row][col] = '^';
}
if (mask == 2) {
board[row][col] = '>';
col--;
board[row][col] = '<';
}
if (mask == 4) {
board[row][col] = '^';
row++;
board[row][col] = 'v';
}
if (mask == 8) {
board[row][col] = '<';
col++;
board[row][col] = '>';
}
for (int i = 0; i < 4; i++) {
if (empty(row + dr[i], col + dc[i])) {
force(row + dr[i], col + dc[i]);
}
}
}
public boolean empty(int row, int col) {
return row > -1 && row < board.length && col > -1 && col < board[0].length && board[row][col] == '.';
}
}
class InputUtil {
JoltyScanner in;
public InputUtil(InputStream istream) {
in = new JoltyScanner(istream);
}
public String next() {
return in.nextOrNull();
}
public int nextInt() {
String s = next();
if (s == null) {
throw new NoSuchElementException("Attempted to read integer that is not there.");
}
return Integer.parseInt(s);
}
public char[][] nextCharRows(int rows) {
char[][] arr = new char[rows][];
for (int i = 0; i < rows; i++) {
arr[i] = in.next().toCharArray();
}
return arr;
}
}
class JoltyScanner {
public static final int BUFFER_SIZE = 1 << 16;
public static final char NULL_CHAR = (char) -1;
BufferedInputStream in;
StringBuilder str = new StringBuilder();
byte[] buffer = new byte[BUFFER_SIZE];
boolean EOF_FLAG = false;
char c = NULL_CHAR;
int bufferIdx = 0;
int size = 0;
public JoltyScanner(InputStream in) {
this.in = new BufferedInputStream(in, BUFFER_SIZE);
}
public String next() {
checkEOF();
for (c = c == NULL_CHAR ? nextChar() : c; Character.isWhitespace(c); checkEOF()) {
c = nextChar();
}
str.setLength(0);
for (; !EOF_FLAG && !Character.isWhitespace(c); c = nextChar()) {
str.append(c);
}
return str.toString();
}
public String nextOrNull() {
try {
return next();
} catch (EndOfFileException e) {
return null;
}
}
public char nextChar() {
if (EOF_FLAG) {
return NULL_CHAR;
}
while (bufferIdx == size) {
try {
size = in.read(buffer);
if (size == -1) {
throw new Exception();
}
} catch (Exception e) {
EOF_FLAG = true;
return NULL_CHAR;
}
if (size == -1) {
size = BUFFER_SIZE;
}
bufferIdx = 0;
}
return (char) buffer[bufferIdx++];
}
public void checkEOF() {
if (EOF_FLAG) {
throw new EndOfFileException();
}
}
public class EndOfFileException extends RuntimeException {
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 914565a9d743f3cacdf89b90d8586324 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.*;
import java.util.*;
public class SolveContest {
private BufferedReader in;
private PrintWriter out;
public SolveContest() {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"),true);
solve();
} catch (Exception e) {
e.printStackTrace();
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
} finally {
try {
in.close();
} catch (IOException e) {
}
out.close();
}
}
StringTokenizer st;
String nextToken() {
while (st == null || !st.hasMoreTokens())
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.valueOf(nextToken());
}
long nextLong() {
return Long.valueOf(nextToken());
}
char[][] a;
int[] dx = {1,-1,0,0};
int[] dy = {0,0,1,-1};
char[] bg = {'^','v','<','>'};
char[] end = {'v','^','>','<'};
int n;
int m;
boolean isCorrect(int newX, int newY) {
return (0 <= newX && newX < n) && (0 <= newY && newY < m);
}
int getPower(int i, int j) {
if (a[i][j] != '.') return 0;
int power = 0;
for (int k = 0; k < 4; k++) {
int newX = i + dx[k];
int newY = j + dy[k];
if (isCorrect(newX, newY) && a[newX][newY] == '.') {
power++;
}
}
return power;
}
public void solve() {
n = nextInt();
m = nextInt();
a = new char[n][m];
for (int i = 0; i < n; i++) {
String s = nextToken();
for (int j = 0; j < m; j++) {
a[i][j] = s.charAt(j);
}
}
Queue<Pair> q = new LinkedList<Pair>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (getPower(i,j) == 1)
q.add(new Pair(i,j));
}
}
while (!q.isEmpty()) {
Pair p = q.poll();
if (a[p.i][p.j] != '.') continue;
int pow = 0;
int dir = 0;
for (int i = 0; i < 4; i++) {
int newX = p.i + dx[i];
int newY = p.j + dy[i];
if (isCorrect(newX, newY) && a[newX][newY] == '.') {
pow++;
dir = i;
}
}
if (pow != 1) {
out.print("Not unique");
return;
}
int newX = p.i + dx[dir];
int newY = p.j + dy[dir];
a[newX][newY] = end[dir];
a[p.i][p.j] = bg[dir];
for (int i = 0; i < 4; i++) {
int newNewX = newX + dx[i];
int newNewY = newY + dy[i];
if (isCorrect(newNewX, newNewY) && getPower(newNewX, newNewY) == 1) {
q.add(new Pair(newNewX, newNewY));
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i][j] == '.') {
out.print("Not unique");
return;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print(a[i][j]);
}
out.println();
}
}
public static void main(String[] args) {
new SolveContest();
}
}
class Pair {
int i;
int j;
public Pair(int i, int j) {
this.i = i;
this.j = j;
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 245648a370a2de22d594d1cae49445fe | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.math.*;
import java.io.*;
import java.util.*;
public class C515D{
static char[][] ar;
static int i, j;
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
String[] s=br.readLine().split(" ");
i=Integer.parseInt(s[0]);
j=Integer.parseInt(s[1]);
ar=new char[i][j];
for(int x=0;x<i;x++)
ar[x]=br.readLine().toCharArray();
find(ar,i,j);
boolean bool=true;
for(int x=0;x<i;x++)
for(int y=0;y<j;y++)
if(ar[x][y]=='.') bool=false;
if(bool)
for(int x=0;x<i;x++){
for(int y=0;y<j;y++)
out.print(ar[x][y]);
out.println();
}
else out.println("Not unique");
out.close();
}
public static void find(char[][] ar,int i,int j){
for(int x=0;x<i;x++)
for(int y=0;y<j;y++)
if(count(x,y).size()==1) index(x,y);
}
public static void index(int xi,int yi){
LinkedList<Pair> q = new LinkedList<Pair>();
if(ar[xi][yi]=='.') q.add(new Pair(xi,yi));
while(q.size()>0) {
Pair cur = q.poll();
int x=cur.a;
int y=cur.b;
ArrayList<Pair> adjacent=count(x,y);
if(adjacent.size()==1){
Pair r=adjacent.get(0);
parenthesis(x,y,r.a,r.b);
for(Pair p:count(r.a, r.b))
q.add(p);
}
}
}
public static void parenthesis(int x,int y,int z,int w){
if((x-z)==0){
ar[x][Math.max(y,w)]='>'; //>
ar[x][Math.min(y,w)]='<'; //<
}
else{
ar[Math.max(x,z)][y]='v'; //v
ar[Math.min(x,z)][w]='^'; //^
}
}
public static ArrayList<Pair> count(int x,int y){
ArrayList<Pair> ret=new ArrayList<Pair>();
if(x>0)
if(ar[x-1][y]=='.') ret.add(new Pair(x-1,y));
if(y>0)
if(ar[x][y-1]=='.') ret.add(new Pair(x,y-1));
if(x<i-1)
if(ar[x+1][y]=='.') ret.add(new Pair(x+1,y));
if(y<j-1)
if(ar[x][y+1]=='.') ret.add(new Pair(x,y+1));
return ret;
}
}
class Pair implements Comparable<Pair> {
Integer a;
Integer b;
public Pair(int ma, int mb) {
a = ma;
b = mb;
}
public int compareTo(Pair o) {
if(a == o.a)
return a.compareTo(o.b);
return a < o.a ? -1 : 1;
}
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 10d6bdb19f16a17d0f4d4278a39d95eb | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.util.*;
/**
* Created by liqiu on 2/4/15.
*/
public class D {
static int n, m;
static char[][] maze;
static int[][] deg;
static char[][] tile = { {'v','^'}, {'^','v'}, {'>', '<'}, {'<','>'}};
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
n = cin.nextInt(); m = cin.nextInt();
deg = new int[n][m];
maze = new char[n][];
for(int[] row: deg) Arrays.fill(row, 0);
for(int i = 0; i < n; ++i){
String row = cin.next();
maze[i] = row.toCharArray();
}
Queue<Integer> que = new LinkedList<Integer>();
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j)if( maze[i][j] == '.' ){
for(int k = 0; k < 4; ++k){
int xx = i + dx[k]; int yy = j + dy[k];
if( !emptyCell(xx, yy) ){
deg[i][j]++;
}
}
if( deg[i][j] == 3 ) {
que.add(i);
que.add(j);
}
}
}
while( !que.isEmpty() ){
int x = que.poll(); int y = que.poll();
for(int k = 0; k < 4; ++k){
int xx = x + dx[k]; int yy = y + dy[k];
if( emptyCell(xx, yy) ) {
maze[x][y] = tile[k][0]; maze[xx][yy] = tile[k][1];
for(int p = 0; p < 4; ++p ){
int nx = xx + dx[p];
int ny = yy + dy[p];
if (emptyCell(nx, ny)) {
deg[nx][ny]++;
if (deg[nx][ny] == 3) {
que.add(nx);
que.add(ny);
}
}
}
}
}
}
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j)if( maze[i][j] == '.' ){
System.out.println("Not unique"); return;
}
}
for(char[] row: maze ){
System.out.println(row);
}
}
private static boolean emptyCell(int x, int y) {
if( x >=0 && x < n && y >= 0 && y < m && maze[x][y] == '.' ) return true;
return false;
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 4f7387ea21e25291736ec0b6e6fc7ff7 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
public class C515D {
private StringTokenizer st;
private BufferedReader bf;
private int n;
private int m;
private char[][] a;
private int cnt;
private HashMap<String, Integer> hm;
private HashSet<String> hs;
private class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int X() {
return x;
}
public int Y() {
return y;
}
}
public C515D(){
try {
bf = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(bf.readLine());
hm = new HashMap<String, Integer>();
hs = new HashSet<String>();
// Queue<Point> q = new LinkedList<Point>();
Queue<Point> q = new ArrayDeque<Point>(n * m);
cnt = 0;
n = nextInt();
m = nextInt();
a = new char[n][m];
int emptycount = 0;
int index = 0;
for (int i = 0; i < n; i++) {
String s = next();
a[i] = s.toCharArray();
for (int j = 0; j < m; j++) {
if (a[i][j] == '.')
emptycount++;
}
}
// if (isFill()) {
if (emptycount == 0) {
for (int i = 0; i < n; i++)
System.out.println(a[i]);
return;
}
if (emptycount % 2 != 0) {
System.out.println("Not unique");
return;
}
if (!isaroundone(q)) {
System.out.println("Not unique");
return;
}
// for (int i = 0; i < 2; i++)
mustset(q);
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// System.out.print(a[i][j]);
// }
// System.out.println("");
// }
boolean isfill = isFill();
if (!isfill && !isaroundone(q)) {
System.out.println("Not unique");
return;
}
if (isfill) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
sb.append(a[i][j]);
// System.out.print(a[i][j]);
}
// System.out.println("\n");
sb.append("\n");
}
System.out.println(sb.toString());
return;
}
if (dfs(0, 0, 0, 0)) {
System.out.println("Not unique");
} else {
for (String s: hm.keySet()) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(s.charAt(i*m+j));
}
System.out.println("");
}
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean isFill() {
for (int y = 0; y < n; y++) {
for (int x = 0; x < m; x++) {
if (a[y][x] == '.') {
return false;
}
}
}
return true;
}
private String oneline() {
StringBuilder sb = new StringBuilder();
for (int r = 0; r < n; r++)
sb.append(a[r]);
return sb.toString();
}
private boolean hasspace() {
boolean result;
for (int y = 0; y < n; y++) {
for (int x = 0; x < m; x++) {
result = false;
if (a[y][x] == '.') {
if (x+1 < m && a[y][x+1] == '.')
result |= true;
if (x-1 >= 0 && a[y][x-1] == '.')
result |= true;
if (y+1 < n && a[y+1][x] == '.')
result |= true;
if (y-1 >= 0 && a[y-1][x] == '.')
result |= true;
if (!result)
return result;
}
}
}
return true;
}
private boolean dfs(int x0, int y0, int x1, int y1) {
if (isFill()) {
String key = oneline();
if (!hm.containsKey(key)) {
hm.put(key, 1);
}
// return true;
if (hm.size() >= 2)
return true;
return false;
}
if (hs.contains(oneline())) {
return false;
}
if (!hasspace())
return false;
int tmpx = x0;
for (int y = y0; y < n; y++) {
for (int x = tmpx; x < m - 1; x++) {
if (a[y][x] == '.'&& a[y][x + 1] == '.') {
a[y][x] = '<';
a[y][x + 1] = '>';
if (dfs(x+2, y, x1, y1))
return true;
hs.add(oneline());
a[y][x] = '.';
a[y][x + 1] = '.';
}
}
tmpx=0;
}
int tmpy = y1;
for (int x = x1; x < m; x++) {
for (int y = tmpy; y < n - 1; y++) {
if (a[y][x] == '.'&& a[y + 1][x] == '.') {
a[y][x] = '^';
a[y + 1][x] = 'v';
if (dfs(x0, y0, x, y+2))
return true;
hs.add(oneline());
a[y][x] = '.';
a[y + 1][x] = '.';
}
}
tmpy=0;
}
hs.add(oneline());
return false;
}
private boolean isValidRange(int x, int y) {
if (x >= 0 && x < m && y >= 0 && y < n)
return true;
else
return false;
}
private boolean fewpoint(int x, int y) {
boolean result = false;
int cnt = 0;
if (isValidRange(x,y) && a[y][x] == '.') {
if (isValidRange(x+1,y) && x+1 < m && a[y][x+1] == '.')
cnt++;
if (isValidRange(x-1,y) && x-1 >= 0 && a[y][x-1] == '.')
cnt++;
if (isValidRange(x,y+1) && y+1 < n && a[y+1][x] == '.')
cnt++;
if (isValidRange(x,y-1) && y-1 >= 0 && a[y-1][x] == '.')
cnt++;
if (cnt == 1)
return true;
}
return result;
}
private boolean isaroundone(Queue<Point> q) {
boolean result = false;
for (int y = 0; y < n; y++) {
for (int x = 0; x < m; x++) {
if (fewpoint(x, y)) {
q.add(new Point(x, y));
result = true;
}
}
}
return result;
}
private void tocell(Queue<Point> q, int dx, int dy) {
if (fewpoint(dx + 1, dy))
q.add(new Point(dx + 1, dy));
if (fewpoint(dx - 1, dy))
q.add(new Point(dx - 1, dy));
if (fewpoint(dx, dy + 1))
q.add(new Point(dx, dy + 1));
if (fewpoint(dx, dy - 1))
q.add(new Point(dx, dy - 1));
}
private void mustset(Queue<Point> q) {
while (!q.isEmpty()) {
Point p = q.remove();
int x = p.X();
int y = p.Y();
if (a[y][x] != '.')
continue;
//right
if ((x+1 < m && a[y][x+1] == '.')) {
a[y][x] = '<';
a[y][x + 1] = '>';
tocell(q, x + 1 , y);
}
//left
if (x-1 >= 0 && a[y][x-1] == '.') {
a[y][x - 1] = '<';
a[y][x] = '>';
tocell(q, x - 1 , y);
}
//down
if (y+1 < n && a[y+1][x] == '.') {
a[y][x] = '^';
a[y + 1][x] = 'v';
tocell(q, x , y + 1);
}
//up
if (y-1 >= 0 && a[y-1][x] == '.') {
a[y - 1][x] = '^';
a[y][x] = 'v';
tocell(q, x , y - 1);
}
}
// for (int y = 0; y < n; y++) {
// for (int x = 0; x < m; x++) {
// if (a[y][x] == '.' && fewpoint(x, y)) {
// //right
// if ((x+1 < m && a[y][x+1] == '.')) {
// a[y][x] = '<';
// a[y][x + 1] = '>';
// }
// //left
// if (x-1 >= 0 && a[y][x-1] == '.') {
// a[y][x - 1] = '<';
// a[y][x] = '>';
// }
//
// //down
// if (y+1 < n && a[y+1][x] == '.') {
// a[y][x] = '^';
// a[y + 1][x] = 'v';
// }
//
// //up
// if (y-1 >= 0 && a[y-1][x] == '.') {
// a[y - 1][x] = '^';
// a[y][x] = 'v';
// }
// }
// }
// }
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private String next() throws IOException {
if (st == null || !st.hasMoreTokens())
st = new StringTokenizer(bf.readLine());
return st.nextToken();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
C515D c = new C515D();
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | d0dff1bc17ec32f67858f97df7db0dc3 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
public class C515D {
private StringTokenizer st;
private BufferedReader bf;
private int n;
private int m;
private char[][] a;
private int cnt;
private HashMap<String, Integer> hm;
private HashSet<String> hs;
private class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int X() {
return x;
}
public int Y() {
return y;
}
}
public C515D(){
try {
bf = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(bf.readLine());
hm = new HashMap<String, Integer>();
hs = new HashSet<String>();
// Queue<Point> q = new LinkedList<Point>();
Queue<Point> q = new ArrayDeque<Point>(n * m);
cnt = 0;
n = nextInt();
m = nextInt();
a = new char[n][m];
int emptycount = 0;
int index = 0;
for (int i = 0; i < n; i++) {
String s = next();
a[i] = s.toCharArray();
for (int j = 0; j < m; j++) {
if (a[i][j] == '.')
emptycount++;
}
}
// if (isFill()) {
if (emptycount == 0) {
for (int i = 0; i < n; i++)
System.out.println(a[i]);
return;
}
if (emptycount % 2 != 0) {
System.out.println("Not unique");
return;
}
if (!isaroundone(q)) {
System.out.println("Not unique");
return;
}
// for (int i = 0; i < 2; i++)
mustset(q);
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// System.out.print(a[i][j]);
// }
// System.out.println("");
// }
boolean isfill = isFill();
if (!isfill && !isaroundone(q)) {
System.out.println("Not unique");
return;
}
if (isfill) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
sb.append(a[i][j]);
// System.out.print(a[i][j]);
}
// System.out.println("\n");
sb.append("\n");
}
System.out.println(sb.toString());
return;
}
// if (dfs(0, 0, 0, 0)) {
// System.out.println("Not unique");
// } else {
// for (String s: hm.keySet()) {
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// System.out.print(s.charAt(i*m+j));
// }
// System.out.println("");
// }
// break;
// }
// }
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean isFill() {
for (int y = 0; y < n; y++) {
for (int x = 0; x < m; x++) {
if (a[y][x] == '.') {
return false;
}
}
}
return true;
}
private String oneline() {
StringBuilder sb = new StringBuilder();
for (int r = 0; r < n; r++)
sb.append(a[r]);
return sb.toString();
}
private boolean hasspace() {
boolean result;
for (int y = 0; y < n; y++) {
for (int x = 0; x < m; x++) {
result = false;
if (a[y][x] == '.') {
if (x+1 < m && a[y][x+1] == '.')
result |= true;
if (x-1 >= 0 && a[y][x-1] == '.')
result |= true;
if (y+1 < n && a[y+1][x] == '.')
result |= true;
if (y-1 >= 0 && a[y-1][x] == '.')
result |= true;
if (!result)
return result;
}
}
}
return true;
}
private boolean dfs(int x0, int y0, int x1, int y1) {
if (isFill()) {
String key = oneline();
if (!hm.containsKey(key)) {
hm.put(key, 1);
}
// return true;
if (hm.size() >= 2)
return true;
return false;
}
if (hs.contains(oneline())) {
return false;
}
if (!hasspace())
return false;
int tmpx = x0;
for (int y = y0; y < n; y++) {
for (int x = tmpx; x < m - 1; x++) {
if (a[y][x] == '.'&& a[y][x + 1] == '.') {
a[y][x] = '<';
a[y][x + 1] = '>';
if (dfs(x+2, y, x1, y1))
return true;
hs.add(oneline());
a[y][x] = '.';
a[y][x + 1] = '.';
}
}
tmpx=0;
}
int tmpy = y1;
for (int x = x1; x < m; x++) {
for (int y = tmpy; y < n - 1; y++) {
if (a[y][x] == '.'&& a[y + 1][x] == '.') {
a[y][x] = '^';
a[y + 1][x] = 'v';
if (dfs(x0, y0, x, y+2))
return true;
hs.add(oneline());
a[y][x] = '.';
a[y + 1][x] = '.';
}
}
tmpy=0;
}
hs.add(oneline());
return false;
}
private boolean isValidRange(int x, int y) {
if (x >= 0 && x < m && y >= 0 && y < n)
return true;
else
return false;
}
private boolean fewpoint(int x, int y) {
boolean result = false;
int cnt = 0;
if (isValidRange(x,y) && a[y][x] == '.') {
if (isValidRange(x+1,y) && x+1 < m && a[y][x+1] == '.')
cnt++;
if (isValidRange(x-1,y) && x-1 >= 0 && a[y][x-1] == '.')
cnt++;
if (isValidRange(x,y+1) && y+1 < n && a[y+1][x] == '.')
cnt++;
if (isValidRange(x,y-1) && y-1 >= 0 && a[y-1][x] == '.')
cnt++;
if (cnt == 1)
return true;
}
return result;
}
private boolean isaroundone(Queue<Point> q) {
boolean result = false;
for (int y = 0; y < n; y++) {
for (int x = 0; x < m; x++) {
if (fewpoint(x, y)) {
q.add(new Point(x, y));
result = true;
}
}
}
return result;
}
private void tocell(Queue<Point> q, int dx, int dy) {
if (fewpoint(dx + 1, dy))
q.add(new Point(dx + 1, dy));
if (fewpoint(dx - 1, dy))
q.add(new Point(dx - 1, dy));
if (fewpoint(dx, dy + 1))
q.add(new Point(dx, dy + 1));
if (fewpoint(dx, dy - 1))
q.add(new Point(dx, dy - 1));
}
private void mustset(Queue<Point> q) {
while (!q.isEmpty()) {
Point p = q.remove();
int x = p.X();
int y = p.Y();
if (a[y][x] != '.')
continue;
//right
if ((x+1 < m && a[y][x+1] == '.')) {
a[y][x] = '<';
a[y][x + 1] = '>';
tocell(q, x + 1 , y);
}
//left
if (x-1 >= 0 && a[y][x-1] == '.') {
a[y][x - 1] = '<';
a[y][x] = '>';
tocell(q, x - 1 , y);
}
//down
if (y+1 < n && a[y+1][x] == '.') {
a[y][x] = '^';
a[y + 1][x] = 'v';
tocell(q, x , y + 1);
}
//up
if (y-1 >= 0 && a[y-1][x] == '.') {
a[y - 1][x] = '^';
a[y][x] = 'v';
tocell(q, x , y - 1);
}
}
// for (int y = 0; y < n; y++) {
// for (int x = 0; x < m; x++) {
// if (a[y][x] == '.' && fewpoint(x, y)) {
// //right
// if ((x+1 < m && a[y][x+1] == '.')) {
// a[y][x] = '<';
// a[y][x + 1] = '>';
// }
// //left
// if (x-1 >= 0 && a[y][x-1] == '.') {
// a[y][x - 1] = '<';
// a[y][x] = '>';
// }
//
// //down
// if (y+1 < n && a[y+1][x] == '.') {
// a[y][x] = '^';
// a[y + 1][x] = 'v';
// }
//
// //up
// if (y-1 >= 0 && a[y-1][x] == '.') {
// a[y - 1][x] = '^';
// a[y][x] = 'v';
// }
// }
// }
// }
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private String next() throws IOException {
if (st == null || !st.hasMoreTokens())
st = new StringTokenizer(bf.readLine());
return st.nextToken();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
C515D c = new C515D();
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 8fe0efde3daeb2e7890acf3a5669db9a | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | 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.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
public class D
{
public static int cover(int i,int j)
{
int n=a.length;
int m=a[0].length;
int []di= {1,-1,0,0};
int []dj= {0,0,1,-1};
for(int k=0;k<4;k++)
{
int ii=i+di[k];
int jj=j+dj[k];
if(ii>=0 && ii<n && jj>=0 && jj<m && a[ii][jj]=='.')
{
if(ii==i)
{
a[i][Math.min(j, jj)]='<';
a[i][Math.max(j, jj)]='>';
}
else
{
a[Math.min(i, ii)][j]='^';
a[Math.max(i, ii)][j]='v';
}
return ii*m+jj;
}
}
return 0;
}
public static void connect(int i,int j)
{
int n=a.length;
int m=a[0].length;
int []di= {1,-1,0,0};
int []dj= {0,0,1,-1};
for(int k=0;k<4;k++)
{
int ii=i+di[k];
int jj=j+dj[k];
if(ii>=0 && ii<n && jj>=0 && jj<m && a[ii][jj]=='.')
{
int u=m*i+j;
int v=m*ii+jj;
adj[u][size[u]++]=v;
}
}
}
static char [][]a;
static int [][]adj;
static int []size;
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt(),m=sc.nextInt();
a=new char[n][];
for(int i=0;i<n;i++)
a[i]=sc.nextLine().toCharArray();
adj=new int[n*m][4];
size=new int [n*m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(a[i][j]=='.')
connect(i,j);
int []deg=new int [n*m];
Queue q=new Queue(n,m);
for(int i=0;i<n*m;i++)
{
if(size[i]==1)
q.add(i);
deg[i]=size[i];
}
while(!q.isEmpty())
{
int y=q.poll();
int i=y/m;
int j=y-i*m;
if(a[i][j]!='.')
continue;
int v=cover(i,j);
deg[v]--;
for(int k=0;k<size[v];k++)
{
int x=adj[v][k];
if(--deg[x]==1)
q.add(x);
}
}
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(a[i][j]=='.')
{
System.out.println("Not unique");
return;
}
for(char []x:a)
pw.println(x);
pw.close();
}
static class Queue
{
int back,front;
int []a;
int size=0;
public Queue(int n,int m)
{
a=new int [n*m];
}
public int poll()
{
size--;
return a[back++];
}
public void add(int x)
{
size++;
a[front++]=x;
}
public boolean isEmpty()
{
return size==0;
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner( String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(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 boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 3f62a91728124c3974eafc4f591ca621 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | 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.io.PrintWriter;
import java.util.StringTokenizer;
public class D
{
public static int cover(int i,int j)
{
int n=a.length;
int m=a[0].length;
for(int k=0;k<4;k++)
{
int ii=i+di[k];
int jj=j+dj[k];
if(ii>=0 && ii<n && jj>=0 && jj<m && a[ii][jj]=='.')
{
a[i][j]=s1[k];
a[ii][jj]=s2[k];
return ii*m+jj;
}
}
return 0;
}
public static void connect(int i,int j)
{
int n=a.length;
int m=a[0].length;
for(int k=0;k<4;k++)
{
int ii=i+di[k];
int jj=j+dj[k];
int u=m*i+j;
if(ii>=0 && ii<n && jj>=0 && jj<m && a[ii][jj]=='.')
deg[u]++;
}
}
static char [][]a;
static int [][]adj;
static int []deg;
static char [] s1={'^','v','<','>'};
static char [] s2={'v','^','>','<'};
static int []di= {1,-1,0,0};
static int []dj= {0,0,1,-1};
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt(),m=sc.nextInt();
a=new char[n][];
for(int i=0;i<n;i++)
a[i]=sc.nextLine().toCharArray();
deg=new int [n*m];
Queue q=new Queue(n,m);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(a[i][j]=='.')
{
int v=m*i+j;
connect(i,j);
if(deg[v]==1)
q.add(v);
}
while(!q.isEmpty())
{
int y=q.poll();
int i=y/m;
int j=y-i*m;
if(a[i][j]!='.')
continue;
int v=cover(i,j);
i=v/m;
j=v-i*m;
for(int k=0;k<4;k++)
{
int ii=i+di[k];
int jj=j+dj[k];
int tmp=m*ii+jj;
if(ii>=0 && ii<n && jj>=0 && jj<m && a[ii][jj]=='.' && --deg[tmp]==1)
{
q.add(tmp);
}
}
}
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(a[i][j]=='.')
{
System.out.println("Not unique");
return;
}
for(char []x:a)
pw.println(x);
pw.close();
}
static class Queue
{
int back,front;
int []a;
int size=0;
public Queue(int n,int m)
{
a=new int [n*m];
}
public int poll()
{
size--;
return a[back++];
}
public void add(int x)
{
size++;
a[front++]=x;
}
public boolean isEmpty()
{
return size==0;
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner( String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(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 boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | a38d5537bf29e6b96620cbfa39977c98 | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | 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.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
public class D
{
public static int cover(int i,int j)
{
int n=a.length;
int m=a[0].length;
int []di= {1,-1,0,0};
int []dj= {0,0,1,-1};
for(int k=0;k<4;k++)
{
int ii=i+di[k];
int jj=j+dj[k];
if(ii>=0 && ii<n && jj>=0 && jj<m && a[ii][jj]=='.')
{
if(ii==i)
{
a[i][Math.min(j, jj)]='<';
a[i][Math.max(j, jj)]='>';
}
else
{
a[Math.min(i, ii)][j]='^';
a[Math.max(i, ii)][j]='v';
}
return ii*m+jj;
}
}
return 0;
}
public static void connect(int i,int j)
{
int n=a.length;
int m=a[0].length;
int []di= {1,-1,0,0};
int []dj= {0,0,1,-1};
for(int k=0;k<4;k++)
{
int ii=i+di[k];
int jj=j+dj[k];
if(ii>=0 && ii<n && jj>=0 && jj<m && a[ii][jj]=='.')
{
int u=m*i+j;
int v=m*ii+jj;
adj[u][size[u]++]=v;
}
}
}
static char [][]a;
static int [][]adj;
static int []size;
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt(),m=sc.nextInt();
a=new char[n][];
for(int i=0;i<n;i++)
a[i]=sc.nextLine().toCharArray();
adj=new int[n*m][4];
size=new int [n*m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(a[i][j]=='.')
connect(i,j);
int []deg=new int [n*m];
Queue q=new Queue(n,m);
for(int i=0;i<n*m;i++)
{
if(size[i]==1)
q.add(i);
deg[i]=size[i];
}
while(!q.isEmpty())
{
int y=q.poll();
int i=y/m;
int j=y-i*m;
if(a[i][j]!='.')
continue;
int v=cover(i,j);
deg[v]--;
for(int k=0;k<size[v];k++)
{
int x=adj[v][k];
if(--deg[x]==1)
q.add(x);
}
}
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(a[i][j]=='.')
{
System.out.println("Not unique");
return;
}
for(char []x:a)
pw.println(new String(x));
pw.close();
}
static class Queue
{
int back,front;
int []a;
int size=0;
public Queue(int n,int m)
{
a=new int [n*m];
}
public int poll()
{
size--;
return a[back++];
}
public void add(int x)
{
size++;
a[front++]=x;
}
public boolean isEmpty()
{
return size==0;
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner( String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(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 boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 0f3397e24cb6d002dc35a4a935cc31ce | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.util.*;
import java.io.*;
public class D {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
int m = sc.nextInt();
char[][] map = new char[n][m];
for(int i = 0; i < n; i++) {
map[i] = sc.next().toCharArray();
}
int[][] dir = {{0,1},{0,-1},{1,0},{-1,0}};
char[] bla = "<>^v".toCharArray();
char[] ble = "><v^".toCharArray();
LinkedList<Pair> q = new LinkedList<>();
int[][] deg = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(map[i][j] == '.') {
for(int[] d: dir) {
int x = i+d[0], y = j+d[1];
if(x >= 0 && x < n && y >= 0 && y < m && map[x][y] == '.') {
deg[i][j]++;
}
}
if(deg[i][j] == 1) {
q.add(new Pair(i,j));
}
}
}
}
while(!q.isEmpty()) {
Pair p = q.removeFirst();
for(int k = 0; k < 4; k++) {
int x = p.x+dir[k][0], y = p.y+dir[k][1];
if(x >= 0 && x < n && y >= 0 && y < m && map[x][y] == '.') {
map[p.x][p.y] = bla[k];
map[x][y] = ble[k];
deg[p.x][p.y]--; deg[x][y]--;
for(int[] d: dir) {
int x2 = x + d[0], y2 = y + d[1];
if(x2 >= 0 && x2 < n && y2 >= 0 && y2 < m && map[x2][y2] == '.') {
deg[x2][y2]--;
if(deg[x2][y2] == 1) {
q.add(new Pair(x2, y2));
}
}
}
}
}
}
boolean valid = true;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(map[i][j] == '.') valid = false;
}
}
if(!valid) {
System.out.println("Not unique");
}
else {
for(int i = 0; i < n; i++) {
System.out.println(new String(map[i]));
}
}
}
static class Pair{
int x, y;
public Pair(int x, int y) {
this.x = x; this.y = y;
}
public String toString() {
return x+" "+y;
}
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | ba42921f3c07f6d89d8955c35bb7778c | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes |
import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class DrazilAndTiles {
static int n;
static int m;
static int[] r = { 1, -1, 0, 0 };
static int[] c = { 0, 0, 1, -1 };
static char[][] grid;
static boolean valid(int i, int j) {
return i >= 0 && i < n && j >= 0 && j < m;
}
public static void put(int i, int j, int k) {
int row = i + r[k];
int col = j + c[k];
if (k == 0) {
grid[i][j] = '^';
grid[row][col] = 'v';
} else if (k == 1) {
grid[i][j] = 'v';
grid[row][col] = '^';
} else if (k == 2) {
grid[i][j] = '<';
grid[row][col] = '>';
} else {
grid[i][j] = '>';
grid[row][col] = '<';
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
grid = new char[n][m];
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++)
grid[i][j] = s.charAt(j);
}
Queue<Point> q = new LinkedList<>();
int[][] deg = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (grid[i][j] == '*')
continue;
for (int k = 0; k < 4; k++) {
int row = i + r[k];
int col = j + c[k];
if (valid(row, col) && grid[row][col] == '.')
deg[i][j]++;
}
if (deg[i][j] == 1)
q.add(new Point(i, j));
}
while (!q.isEmpty()) {
Point a = q.poll();
for (int i = 0; i < 4; i++) {
int row = a.x + r[i];
int col = a.y + c[i];
if (valid(row, col) && grid[row][col] == '.') {
put(a.x, a.y, i);
for (int j = 0; j < 4; j++) {
int r1 = row + r[j];
int c1 = col + c[j];
if (valid(r1, c1) && grid[r1][c1] == '.') {
deg[r1][c1]--;
if (deg[r1][c1] == 1)
q.add(new Point(r1, c1));
}
}
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
if (grid[i][j] == '.') {
System.out.println("Not unique");
return;
}
sb.append(new String(grid[i]));
sb.append("\n");
}
System.out.println(sb.toString());
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public 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();
}
public boolean nextEmpty() throws IOException {
String s = nextLine();
st = new StringTokenizer(s);
return s.isEmpty();
}
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 8746b17ad1c9976194490783565d4b7c | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.*;
import java.util.*;
public class a {
public static void main(String[] args) throws IOException {
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt(), m = input.nextInt();
int[][] degs = new int[n][m];
int[] di = new int[]{0, 1, 0, -1};
int[] dj = new int[]{1, 0, -1, 0};
Queue<Integer> qi = new LinkedList<Integer>(), qj = new LinkedList<Integer>();
char[][] res = new char[n][m];
char[][] grid = new char[n][m];
for(int i = 0; i<n; i++)
{
String s = input.next();
for(int j = 0; j<m; j++)
res[i][j] = grid[i][j] = s.charAt(j);
}
for(int i = 0; i<n; i++)
for(int j = 0; j<m; j++)
{
if((i+j)%2 == 0 || grid[i][j] == '*') continue;
int d =0;
for(int k =0 ; k<4; k++)
{
int ni = i+di[k], nj = j+dj[k];
if(ni<0 || nj < 0 || ni >= n || nj >= m) continue;
if(grid[ni][nj] == '.') d++;
}
degs[i][j] = d;
//out.println(i+" "+j+" "+d);
if(degs[i][j] == 1)
{
qi.add(i);
qj.add(j);
}
}
while(!qi.isEmpty())
{
int ati = qi.poll();
int atj = qj.poll();
//out.println(ati+" "+atj);
int d = -1;
for(int k = 0; k<4; k++)
{
int ni = ati+di[k], nj = atj+dj[k];
if(ni<0 || nj < 0 || ni >= n || nj >= m) continue;
if(res[ni][nj] == '.') d = k;
}
if(d == -1) break;
int i = ati+di[d], j = atj+dj[d];
if(d == 0)
{
res[ati][atj] = '<';
res[i][j] = '>';
}
else if(d == 1)
{
res[ati][atj] = '^';
res[i][j] = 'v';
}
else if(d == 2)
{
res[ati][atj] = '>';
res[i][j] = '<';
}
else if(d == 3)
{
res[ati][atj] = 'v';
res[i][j] = '^';
}
for(int k = 0; k<4; k++)
{
int ni = i+di[k], nj = j+dj[k];
if(ni<0 || nj < 0 || ni >= n || nj >= m) continue;
if(grid[ni][nj] == '.')
{
degs[ni][nj]--;
if(degs[ni][nj] == 1)
{
qi.add(ni);
qj.add(nj);
// out.println("ADD: "+ni+" "+nj);
}
}
}
}
boolean good = true;
for(int i = 0; i<n; i++)
for(int j = 0; j<m; j++)
good &= res[i][j] != '.';
if(good)
{
for(char[] A: res) out.println(new String(A));
}
else
{
out.println("Not unique");
}
out.close();
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 2d2b43d0a9578e3c4483754d74c8566c | train_001.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.util.LinkedList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Collection;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Queue;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
char grid[][];
int degree[][];
int dx[] = new int[]{0, 1, 0, -1};
int dy[] = new int[]{1, 0, -1, 0};
int n;
int m;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
grid = new char[n + 2][m + 2];
degree = new int[n + 2][m + 2];
for (int i = 1; i <= n; i++) {
char row[] = in.next().toCharArray();
for (int j = 1; j <= m; j++) {
grid[i][j] = row[j - 1];
}
}
Queue<Pair> q = new LinkedList<>();
int cells = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (grid[i][j] == '.') {
cells++;
for (int k = 0; k < 4; k++) {
int nx = i + dx[k];
int ny = j + dy[k];
if (grid[nx][ny] == '.') degree[i][j]++;
}
if (degree[i][j] == 1) q.add(new Pair(i, j));
}
}
}
while (!q.isEmpty()) {
Pair p1 = q.remove();
if (grid[p1.x][p1.y] != '.') continue;
Pair p2 = adj(p1);
if (p2 == null) {
out.println("Not unique");
return;
}
cover(p1.x, p1.y, p2.x, p2.y);
degree[p1.x][p1.y] = 0;
degree[p2.x][p2.y] = 0;
for (int k = 0; k < 4; k++) {
int nx = p2.x + dx[k];
int ny = p2.y + dy[k];
degree[nx][ny]--;
if (degree[nx][ny] == 1) q.add(new Pair(nx, ny));
}
cells -= 2;
}
if (cells > 0) {
out.println("Not unique");
} else {
for (int i = 1; i <= n; i++) {
out.println(new String(grid[i], 1, m));
}
}
}
private Pair adj(Pair p) {
for (int k = 0; k < 4; k++) {
int nx = p.x + dx[k];
int ny = p.y + dy[k];
if (grid[nx][ny] == '.') return new Pair(nx, ny);
}
return null;
}
private void cover(int x1, int y1, int x2, int y2) {
if (x1 == x2) {
grid[x1][Math.min(y1, y2)] = '<';
grid[x2][Math.max(y1, y2)] = '>';
} else {
grid[Math.min(x1, x2)][y1] = '^';
grid[Math.max(x1, x2)][y2] = 'v';
}
}
private class Pair {
private final int x;
private final int y;
public Pair(int i, int j) {
this.x = i;
this.y = j;
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.