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
sequencelengths 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 | 3fe6eacb2d354e0f93d356244f23c3b8 | train_000.jsonl | 1396798800 | Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries. | 512 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static PrintWriter out;
static Reader in;
public static void main(String[] args) throws IOException {
//out = new PrintWriter(new File("out.txt"));
//PrintWriter out = new PrintWriter(System.out);
//in = new Reader(new FileInputStream("in.txt"));
//Reader in = new Reader();
input_output();
Main solver = new Main();
solver.solve();
out.flush();
out.close();
}
static int INF = (int)2e9+5;
static int maxn = (int)2e6+5;
static int mod=(int)1e9+7 ;
static int n, m, t, q, k;
// read the editorial of the last problem (K).
static long[] res;
void solve() throws IOException{
n = in.nextInt();
int size = 1;
for (int i = 0; i < n; i++) size = size*2;
int[] cop = new int[size];
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = in.nextInt();
cop[i] = arr[i];
}
long[] pow = new long[n+1];
pow[0] = 1;
for (int i = 1; i <= n; i++) pow[i] = pow[i-1]*2;
long tmp, x;
// calculate res: res[i] = the number of inversions if we consider each 2^i part alone.
res = new long[n+1];
invCount(cop, n);
long[] rem = new long[n+1];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < size; j+=pow[i]) {
Map<Integer, Integer> tmpmap = new HashMap<>();
tmp = 0;
for (int z = j; z < j+pow[i]; z++) {
tmpmap.put(arr[z], tmpmap.getOrDefault(arr[z], 0)+1);
x = tmpmap.get(arr[z]);
if (x == 2) tmp += 1L;
else if (x > 2) tmp += ((x-1L)*x)/2L-((x-2L)*(x-1L))/2L;
}
rem[i] += tmp;
}
}
StringBuilder myres = new StringBuilder("");
int mm = in.nextInt();
long ans = res[n];
for (int i = 0; i < mm ;i++) {
q = in.nextInt();
if (q == 0) {
myres.append(ans+"\n");
continue;
}
tmp = ((pow[q]-1)*pow[q])/2L;
tmp = tmp*pow[n-q];
ans += tmp-2L*res[q]-rem[q];
for (int j = q+1; j <= n; j++) res[j] += tmp-2L*res[q]-rem[q];
for (int j = 1; j <= q; j++) {
tmp = ((pow[j]-1)*pow[j])/2L;
tmp = tmp*pow[n-j];
res[j] = tmp-res[j]-rem[j];
}
myres.append(ans+"\n");
}
out.println(myres);
}
//<>
static long merge(int[] arr, int[] left, int[] right) {
int i = 0, j = 0;
long count = 0;
while (i < left.length || j < right.length) {
if (i == left.length) {
arr[i+j] = right[j];
j++;
} else if (j == right.length) {
arr[i+j] = left[i];
i++;
} else if (left[i] <= right[j]) {
arr[i+j] = left[i];
i++;
} else {
arr[i+j] = right[j];
count += left.length-i;
j++;
}
}
return count;
}
static long invCount(int[] arr, int power) {
if (arr.length < 2)
return 0;
int m = (arr.length + 1) / 2;
int left[] = Arrays.copyOfRange(arr, 0, m);
int right[] = Arrays.copyOfRange(arr, m, arr.length);
long cnt = invCount(left, power-1) + invCount(right, power-1) + merge(arr, left, right);
res[power] += cnt;
return cnt;
}
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;
}
}
static void input_output() throws IOException {
File f = new File("in.txt");
if(f.exists() && !f.isDirectory()) {
in = new Reader(new FileInputStream("in.txt"));
} else in = new Reader();
f = new File("out.txt");
if(f.exists() && !f.isDirectory()) {
out = new PrintWriter(new File("out.txt"));
} else out = new PrintWriter(System.out);
}
} | Java | ["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"] | 4 seconds | ["0\n6\n6\n0", "0\n1\n0"] | NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i < j and x[i] > x[j]. | Java 8 | standard input | [
"combinatorics",
"divide and conquer"
] | ea7f8bd397f80ba7d3add6f9609dcc4a | The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. | 2,100 | Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query. | standard output | |
PASSED | 50b35eb06d6c850adf71dbb7086f22a3 | train_000.jsonl | 1396798800 | Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries. | 512 megabytes | import java.io.*;
import java.util.*;
public class C {
MyScanner in;
PrintWriter out;
public static void main(String[] args) throws Exception {
new C().run();
}
public void run() throws Exception {
in = new MyScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
long[] inv, str;
void countStr(int[] a, int l, int r, int level) {
int[] b = new int[r - l];
if (level > 0) {
int m = (l + r) / 2;
countStr(a, l, m, level - 1);
countStr(a, m, r, level - 1);
int i1 = l;
int i2 = m;
int j = 0;
while (i1 < m && i2 < r) {
if (a[i1] < a[i2]) {
str[level] += (r - i2);
b[j++] = a[i1++];
} else if (a[i1] >= a[i2]) {
b[j++] = a[i2++];
}
}
while (i1 < m) {
b[j++] = a[i1++];
}
while (i2 < r) {
b[j++] = a[i2++];
}
System.arraycopy(b, 0, a, l, r - l);
}
}
void countInv(int[] a, int l, int r, int level) {
int[] b = new int[r - l];
if (level > 0) {
int m = (l + r) / 2;
countInv(a, l, m, level - 1);
countInv(a, m, r, level - 1);
int i1 = l;
int i2 = m;
int j = 0;
while (i1 < m && i2 < r) {
if (a[i1] <= a[i2]) {
b[j++] = a[i1++];
} else if (a[i1] > a[i2]) {
inv[level] += (m - i1);
b[j++] = a[i2++];
}
}
while (i1 < m) {
b[j++] = a[i1++];
}
while (i2 < r) {
b[j++] = a[i2++];
}
System.arraycopy(b, 0, a, l, r - l);
}
}
public void solve() throws Exception {
int n = in.nextInt();
int[] a = new int[1 << n];
for (int i = 0; i < (1 << n); i++) {
a[i] = in.nextInt();
}
str = new long[n + 1];
inv = new long[n + 1];
countStr(Arrays.copyOf(a, a.length), 0, a.length, n);
countInv(Arrays.copyOf(a, a.length), 0, a.length, n);
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int q = in.nextInt();
for (int level = 0; level <= q; level++) {
long tmp = str[level];
str[level] = inv[level];
inv[level] = tmp;
}
long ans = 0;
for (int level = 0; level <= n; level++) {
ans += inv[level];
}
out.println(ans);
}
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws Exception {
while ((st == null) || (!st.hasMoreTokens())) {
String t = br.readLine();
if (t == null) {
return null;
}
st = new StringTokenizer(t);
}
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
double nextDouble() throws Exception {
return Double.parseDouble(next());
}
boolean nextBoolean() throws Exception {
return Boolean.parseBoolean(next());
}
long nextLong() throws Exception {
return Long.parseLong(next());
}
}
}
| Java | ["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"] | 4 seconds | ["0\n6\n6\n0", "0\n1\n0"] | NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i < j and x[i] > x[j]. | Java 8 | standard input | [
"combinatorics",
"divide and conquer"
] | ea7f8bd397f80ba7d3add6f9609dcc4a | The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. | 2,100 | Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query. | standard output | |
PASSED | b90bb7e388fe37f85f79d60b2e7f75a5 | train_000.jsonl | 1396798800 | Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries. | 512 megabytes | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
/* spar5h */
public class cf1 implements Runnable{
static void addMap(HashMap<Integer, Integer> hm, int x) {
if(hm.get(x) == null)
hm.put(x, 1);
else
hm.put(x, hm.get(x) + 1);
}
static int[] a, pow2;
static long[] invCount, sameCount;
static long recur(int[] a, int k) {
if(k == 0)
return 0;
int n = pow2[k];
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for(int i = 0; i < n; i++)
addMap(hm, a[i]);
for(Map.Entry<Integer, Integer> e : hm.entrySet())
sameCount[k] += (long)e.getValue() * (e.getValue() - 1) / 2;
int[] left = new int[n / 2];
for(int i = 0; i < n / 2; i++)
left[i] = a[i];
int[] right = new int[n / 2];
for(int i = 0; i < n / 2; i++)
right[i] = a[i + n / 2];
long inv = 0;
inv += recur(left, k - 1);
inv += recur(right, k - 1);
int i = 0, j = 0;
while(i < n / 2 && j < n / 2) {
if(left[i] <= right[j]) {
a[i + j] = left[i]; i++;
}
else {
inv += n / 2 - i; a[i + j] = right[j]; j++;
}
}
while(i < n / 2) {
a[i + j] = left[i]; i++;
}
while(j < n / 2) {
a[i + j] = right[j]; j++;
}
invCount[k] += inv;
return inv;
}
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = s.nextInt();
pow2 = new int[n + 1]; pow2[0] = 1;
for(int i = 1; i <= n; i++)
pow2[i] = pow2[i - 1] * 2;
invCount = new long[n + 1];
sameCount = new long[n + 1];
int[] a = new int[1 << n];
for(int i = 0; i < (1 << n); i++)
a[i] = s.nextInt();
recur(a.clone(), n);
int m = s.nextInt();
while(m-- > 0) {
int k = s.nextInt();
for(int i = 0; i <= k; i++)
invCount[i] = (long)pow2[n - i] * pow2[i] * (pow2[i] - 1) / 2 - sameCount[i] - invCount[i];
for(int i = k + 1; i <= n; i++)
invCount[i] += invCount[k] - ((long)pow2[n - k] * pow2[k] * (pow2[k] - 1) / 2 - sameCount[k] - invCount[k]);
w.println(invCount[n]);
}
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 cf1(),"cf1",1<<26).start();
}
} | Java | ["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"] | 4 seconds | ["0\n6\n6\n0", "0\n1\n0"] | NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i < j and x[i] > x[j]. | Java 8 | standard input | [
"combinatorics",
"divide and conquer"
] | ea7f8bd397f80ba7d3add6f9609dcc4a | The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. | 2,100 | Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query. | standard output | |
PASSED | b1131c5278d7059089c17232b2669742 | train_000.jsonl | 1396798800 | Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries. | 512 megabytes | import java.io.*;
import java.util.*;
public class C implements Runnable{
public static void main (String[] args) {new Thread(null, new C(), "_cf", 1 << 28).start();}
long[] sums, sumr;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("Go!");
int n = fs.nextInt();
int m = (1 << (n+1))+10;
int[] a = fs.nextIntArray(1<<n);
long[] invCount = new long[m], rinvCount = new long[m];
sums = new long[n+2]; sumr = new long[n+2];
go(1, 0, (1<<n)-1, a, invCount, rinvCount);
int[] state = new int[n+1];
int q = fs.nextInt();
while(q-->0) {
int qi = fs.nextInt();
for(int i = n-qi; i <= n; i++) state[i] ^= 1;
long res = 0;
for(int i = 0; i < n; i++) {
if(state[i] == 1) res += sumr[i];
else res += sums[i];
}
out.println(res);
}
out.close();
}
int[] go(int node, int left, int right, int[] a, long[] invCount, long[] rinvCount) {
if(left == right) {
invCount[node] = rinvCount[node] = 0;
return new int[] {a[left]};
}
int[] lf = go(2*node, left, (left+right)/2, a, invCount, rinvCount);
int[] rg = go(2*node+1, (left+right)/2+1, right, a, invCount, rinvCount);
for(int i = 0, j = 0; i < lf.length; i++) {
while(j < rg.length && lf[i] > rg[j]) j++;
invCount[node] += j;
}
for(int i = 0, j = 0; i < rg.length; i++) {
while(j < lf.length && rg[i] > lf[j]) j++;
rinvCount[node] += j;
}
sums[Integer.numberOfTrailingZeros(Integer.highestOneBit(node))] += invCount[node];
sumr[Integer.numberOfTrailingZeros(Integer.highestOneBit(node))] += rinvCount[node];
int[] res = new int[lf.length+rg.length];
int p1 = 0, p2 = 0;
while(p1 < lf.length || p2 < rg.length) {
if(p1 == lf.length) res[p1+p2] = rg[p2++];
else if(p2 == rg.length) res[p1+p2] = lf[p1++];
else if(lf[p1] <= rg[p2]) res[p1+p2] = lf[p1++];
else res[p1+p2] = rg[p2++];
}
return res;
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | Java | ["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"] | 4 seconds | ["0\n6\n6\n0", "0\n1\n0"] | NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i < j and x[i] > x[j]. | Java 8 | standard input | [
"combinatorics",
"divide and conquer"
] | ea7f8bd397f80ba7d3add6f9609dcc4a | The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. | 2,100 | Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query. | standard output | |
PASSED | 96cd195fab49580ae28d5d9dd7af866b | train_000.jsonl | 1396798800 | Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries. | 512 megabytes | import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public class Round240C {
public static class Node {
int[] sorted;
int level;
public Node(int level, int val) {
sorted = new int[1];
sorted[0] = val;
this.level = level;
}
public Node(Node left, Node right, int level) {
sorted = new int[left.sorted.length * 2];
this.level = level;
Merge(left, right);
ADD_ANSWER(left, right);
}
public void Merge(Node left, Node right) {
int[] l_tree = left.sorted;
int[] r_tree = right.sorted;
int l = l_tree.length;
int i = 0, j = 0;
int ptr = 0;
while(i < l && j < l) {
if(l_tree[i] > r_tree[j]) {
sorted[ptr] = r_tree[j];
j++;
}else if(l_tree[i] < r_tree[j]) {
sorted[ptr] = l_tree[i];
i++;
}else {
sorted[ptr++] = l_tree[i];
sorted[ptr] = r_tree[j];
i++;
j++;
}
ptr++;
}
while(i < l) {
sorted[ptr++] = l_tree[i++];
}
while(j < l) {
sorted[ptr++] = r_tree[j++];
}
}
public void ADD_ANSWER(Node left, Node right) {
int[] l_tree = left.sorted;
int[] r_tree = right.sorted;
int l = l_tree.length;
long[] ans = new long[2];
int ptr = 0;
for(int i = 0; i < l; i++) {
while(ptr < l && l_tree[i] > r_tree[ptr]) {
ptr++;
}
ans[0] += ptr;
}
ptr = l - 1;
for(int i = l - 1; i >= 0; i--) {
while(ptr >= 0 && l_tree[i] < r_tree[ptr]) {
ptr--;
}
ans[1] += l - 1 - ptr;
}
level_ans[level][0] += ans[0];
level_ans[level][1] += ans[1];
}
}
public static Node[] tree;
public static void Build(int start, int end, int index, int[] arr, int level) {
if(start == end) {
tree[index] = new Node(level, arr[start]);
return;
}
int mid = (start + end)>>1;
Build(start, mid, index<<1, arr, level + 1);
Build(mid + 1, end, index<<1|1, arr, level + 1);
tree[index] = new Node(tree[index<<1], tree[index<<1|1], level);
}
public static void solve() {
int n = s.nextInt();
int[] arr = s.nextIntArray(1<<n);
tree = new Node[4 * (1<<n) + 1];
level_ans = new long[n + 1][2];
Build(0, (1<<n) - 1, 1, arr, 0);
int[] current_state = new int[n + 1];
int q = s.nextInt();
while(q-- > 0) {
int change = s.nextInt();
int level = n - Integer.toBinaryString(1<<change).length() ;
long ans = 0;
for(int i = 0; i < n; i++) {
if(level < i) {
current_state[i] ^= 1;
}
ans += level_ans[i][current_state[i]];
}
out.println(ans);
}
}
public static long[][] level_ans;
public static void main(String[] args) {
new Thread(null, null, "Thread", 1 << 27) {
public void run() {
try {
out = new PrintWriter(new BufferedOutputStream(System.out));
s = new FastReader(System.in);
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
public static PrintWriter out;
public static FastReader s;
public static class FastReader {
private InputStream stream;
private byte[] buf = new byte[4096];
private int curChar, snumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
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 = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int number = 0;
do {
number *= 10;
number += c - '0';
c = read();
} while (!isSpaceChar(c));
return number * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
long sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long number = 0;
do {
number *= 10L;
number += (long) (c - '0');
c = read();
} while (!isSpaceChar(c));
return number * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextLong();
}
return arr;
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public 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 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 | ["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"] | 4 seconds | ["0\n6\n6\n0", "0\n1\n0"] | NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i < j and x[i] > x[j]. | Java 8 | standard input | [
"combinatorics",
"divide and conquer"
] | ea7f8bd397f80ba7d3add6f9609dcc4a | The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. | 2,100 | Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query. | standard output | |
PASSED | 1b32445700641d6fa14d38941b810ada | train_000.jsonl | 1396798800 | Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries. | 512 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.StringTokenizer;
public class Abood3A {
static final int INF = Integer.MAX_VALUE;
static long[] inv, invR;
static void mergeSort(int[] a, int b, int e, int i)
{
if(b < e)
{
int q = (b + e) / 2;
mergeSort(a, b, q, i + 1);
mergeSort(a, q + 1, e, i + 1);
merge(a, b, q, e, i);
}
}
static void merge(int[] a, int b, int mid, int e, int idx)
{
int n1 = mid - b + 1;
int n2 = e - mid;
int[] L = new int[n1+1], R = new int[n2+1];
for(int i = 0; i < n1; i++) L[i] = a[b + i];
for(int i = 0; i < n2; i++) R[i] = a[mid + 1 + i];
L[n1] = R[n2] = INF;
for(int k = b, i = 0, j = 0; k <= e; k++)
if(L[i] <= R[j]) {
a[k] = L[i++];
} else{
a[k] = R[j++];
inv[idx] += (n1 - i);
}
for(int k = b, i = 0, j = 0; k <= e; k++)
if(R[j] <= L[i]) {
j++;
} else{
i++;
invR[idx] += (n2 - j);
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
inv = new long[n + 1];
invR = new long[n + 1];
boolean[] Rev = new boolean[n + 1];
int[] a = new int[1 << n];
for (int i = 0; i < a.length; i++)
a[i] = sc.nextInt();
mergeSort(a, 0, a.length - 1, 0);
int m = sc.nextInt();
for (int i = 0; i < m; i++) {
int q = sc.nextInt();
long ans = 0;
for (int j = 0; j < inv.length; j++) {
if(j < n - q)
ans += Rev[j] ? invR[j] : inv[j];
else {
ans += Rev[j] ? inv[j] : invR[j];
Rev[j] = !Rev[j];
}
}
out.println(ans);
}
out.flush();
}
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();}
}
} | Java | ["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"] | 4 seconds | ["0\n6\n6\n0", "0\n1\n0"] | NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i < j and x[i] > x[j]. | Java 8 | standard input | [
"combinatorics",
"divide and conquer"
] | ea7f8bd397f80ba7d3add6f9609dcc4a | The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. | 2,100 | Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query. | standard output | |
PASSED | ea6dae42b767f2ff6db020747abef187 | train_000.jsonl | 1396798800 | Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries. | 512 megabytes | import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int n=ni();
a=new int[(1<<n)+1];
for(int i=1;i<=(1<<n);i++) a[i]=ni();
sum2=new long[n+1][2];
tree=new int[4*(1<<n)+1][];
build(1,1,1<<n,0);
// pw.println(sum2[0][0]+" "+sum2[0][1]+" "+sum2[1][0]+" "+sum2[1][1]);
// pw.println("");
int q=ni();
int parity[]=new int[n+1];
long sum[]=new long[n+1];
while(q-->0){
int h=n-ni();
for(int i=h;i<=n;i++) parity[i]^=1;
for(int i=n-1;i>=0;i--){
sum[i]=sum[i+1]+sum2[i][parity[i]];
}
pw.println(sum[0]);
}
}
int tree[][];
int a[];
long sum2[][];
void build(int id,int l,int r,int h){
if(l==r){
tree[id]=new int[1];
tree[id][0]=a[l];
}else {
int mid=(l+r)>>1;
build(2*id,l,mid,h+1);
build(2*id+1,mid+1,r,h+1);
merge(id,h);
}
}
void merge(int id,int h){
int sz1=tree[2*id].length,sz2=tree[2*id+1].length;
tree[id]=new int[sz1+sz2];
int idx=0,id1=0,id2=0;
while(id1<sz1 && id2<sz2){
if(tree[2*id][id1]<tree[2*id+1][id2]){
tree[id][idx++]=tree[2*id][id1++];
}else{
tree[id][idx++]=tree[2*id+1][id2++];
}
}
while(id1<sz1){
tree[id][idx++]=tree[2*id][id1++];
}
while(id2<sz2){
tree[id][idx++]=tree[2*id+1][id2++];
}
sum2[h][0]+=cal(2*id,2*id+1);
sum2[h][1]+=cal(2*id+1,2*id);
}
long cal(int id1,int id2){
int sz1=tree[id1].length,sz2=tree[id2].length;
int i2=0;
long ans=0;
for(int i1=0;i1<sz1;i1++){
while(i2<sz2 && tree[id2][i2]<tree[id1][i1]){
i2++;
}
ans+=i2;
}
return ans;
}
long M = (long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
Thread t = new Thread(null, null, "~", Runtime.getRuntime().maxMemory()){
@Override
public void run() {
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
};
t.start();
t.join();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private 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 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 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 = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
} | Java | ["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"] | 4 seconds | ["0\n6\n6\n0", "0\n1\n0"] | NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i < j and x[i] > x[j]. | Java 8 | standard input | [
"combinatorics",
"divide and conquer"
] | ea7f8bd397f80ba7d3add6f9609dcc4a | The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. | 2,100 | Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query. | standard output | |
PASSED | 81344bd909d204ecc8f5acfc2b2fd62e | train_000.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;
/* Name of the class has to be "Main" only if the class is public*/
public class CF602C
{
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;
}
}
static class Node {
long pp;
long a, b;
Node(long x, long y) {
a = x;
b = y;
pp = a * b;
}
}
static class Comp implements Comparator<Node> {
public int compare(Node o1, Node o2) {
if (o1.pp > o2.pp) {
return 1;
} else {
return -1;
}
}
}
public static void main(String[] args) {
FastReader sc=new FastReader();
PrintWriter out=new PrintWriter(System.out);
//your code starts here
int n=sc.nextInt();
boolean adj[][]=new boolean[n][n];
int m=sc.nextInt();
for(int i=0;i<m;i++)
{
int a=sc.nextInt()-1;
int b=sc.nextInt()-1;
// adding edges of undirected graph
adj[a][b]=true; adj[b][a]=true;
}
if(m==0 || m==(n*(n-1)/2)) {
out.println(-1); out.close(); return;
}
int[] dist=new int[n]; Arrays.fill(dist, Integer.MAX_VALUE);
dist[0]=0;
Queue<Integer> q=new LinkedList();
q.add(0);
while(!q.isEmpty())
{
int s=q.poll();
for(int i=0;i<n;i++)
{
if(!adj[0][n-1] && adj[s][i])
{
if(dist[i]==Integer.MAX_VALUE) {
dist[i]=dist[s]+1;
q.add(i);
}
}
else if(!adj[s][i] && adj[0][n-1])
{
if(dist[i]==Integer.MAX_VALUE)
{
dist[i]=dist[s]+1;
q.add(i);
}
}
}
}
//for(int i:dist) out.print(i+" ");
if(dist[n-1]==Integer.MAX_VALUE) out.println(-1);
else out.println(Math.max(1,dist[n-1]));
out.close();
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 11 | standard input | [
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | ffe70122fe98ce0b60a0c92ccd325739 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.*;
import java.lang.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out, true);
try {
Task task = new Task();
task.solve(reader, writer);
} finally {
reader.close();
writer.close();
}
}
}
class Rest {
public int value;
public int y;
Rest(int value, int y) {
this.value = value;
this.y = y;
}
}
class Task {
private int diff(int prev, int current, int p, int u, int d) {
int signum = (int) Math.signum(prev - current);
switch (signum) {
case 1: return d;
case 0: return p;
case -1: return u;
}
return 0;
}
public void solve(InputReader reader, PrintWriter writer) throws IOException {
int n = reader.nextInt();
int m = reader.nextInt();
int t = reader.nextInt();
int tp = reader.nextInt();
int tu = reader.nextInt();
int td = reader.nextInt();
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = reader.nextInt();
}
}
int[][] horizontalDirect = new int[n][m];
int[][] horizontalRevert = new int[n][m];
int[][] verticalDirect = new int[n][m];
int[][] verticalRevert = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
horizontalDirect[i][j] = (0 == i) ? 0 : horizontalDirect[i - 1][j] + diff(map[i-1][j], map[i][j], tp, tu, td);
horizontalRevert[i][j] = (0 == i) ? 0 : horizontalRevert[i - 1][j] + diff(map[i-1][j], map[i][j], tp, td, tu);
verticalDirect[i][j] = (0 == j) ? 0 : verticalDirect[i][j - 1] + diff(map[i][j - 1], map[i][j], tp, tu, td);
verticalRevert[i][j] = (0 == j) ? 0 : verticalRevert[i][j - 1] + diff(map[i][j - 1], map[i][j], tp, td, tu);
}
}
TreeSet<Rest> tree = new TreeSet<Rest>(new Comparator<Rest>() {
public int compare(Rest a, Rest b) {
return Integer.compare(a.value, b.value);
}
});
int minValue = Integer.MAX_VALUE;
String ret = "";
for (int startX=0; startX < n && 0 != minValue; startX++) {
for (int endX=startX + 2; endX < n && 0 != minValue; endX++) {
tree.clear();
for (int startY=0, endY=2; endY < m && 0 != minValue; startY++, endY++) {
int value = 0;
value += (horizontalRevert[endX][startY] - horizontalRevert[startX][startY]);
value += - verticalRevert[endX][startY];
value += - verticalDirect[startX][startY];
tree.add(new Rest(value, startY));
value = 0;
value += verticalRevert[endX][endY];
value += verticalDirect[startX][endY];
value += (horizontalDirect[endX][endY] - horizontalDirect[startX][endY]);
Rest r = tree.ceiling(new Rest(t - value, 0));
if (null != r && Math.abs(value + r.value - t) < minValue) {
minValue = Math.abs(value + r.value - t);
ret = String.format("%d %d %d %d", startX + 1, r.y + 1, endX + 1, endY + 1);
}
r = tree.floor(new Rest(t - value, 0));
if (null != r && Math.abs(value + r.value - t) < minValue) {
minValue = Math.abs(value + r.value - t);
ret = String.format("%d %d %d %d", startX + 1, r.y + 1, endX + 1, endY + 1);
}
}
}
}
writer.println(ret);
}
}
class InputReader {
private StringTokenizer tokenizer;
private BufferedReader reader;
InputReader(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() throws IOException {
while (null == tokenizer || !tokenizer.hasMoreTokens()) {
this.tokenizer = new StringTokenizer(reader.readLine());
}
return this.tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public void close() throws IOException{
this.reader.close();
}
}
| Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | 7915411208091cc4937e712adae1e159 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CF242_D solver = new CF242_D();
solver.solve(1, in, out);
out.close();
}
}
class CF242_D {
static class Pair implements Comparable<Pair> {
int value;
int index;
Pair(int value, int index) {
this.value = value;
this.index = index;
}
public int compareTo(Pair o) {
if (value == o.value) {
return index - o.index;
}
return value - o.value;
}
}
int n, m, tNeed;
int tPlain, tUp, tDown;
int[][] h;
int[][] prefRowsLeft;
int[][] prefRowsRight;
int[][] prefColsDown;
int[][] prefColsUp;
TreeSet<Pair> set = new TreeSet<Pair>();
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
m = in.readInt();
tNeed = in.readInt();
tPlain = in.readInt();
tUp = in.readInt();
tDown = in.readInt();
h = IOUtils.readIntTable(in, n, m);
prefRowsLeft = new int[n][m];
prefRowsRight = new int[n][m];
prefColsDown = new int[m][n];
prefColsUp = new int[m][n];
precalcPrefixSums();
int bestR1 = -1, bestR2 = -1;
int bestC1 = -1, bestC2 = -1;
int bestDiff = (int) 1e9;
for (int r1 = 0; r1 < n; r1++) {
for (int r2 = r1 + 2; r2 < n; r2++) {
set.clear();
for (int c1 = 0, c2 = 2; c2 < m; c1++, c2++) {
set.add(new Pair(getSum1(r1, r2, c1), c1));
Pair toFind = new Pair(tNeed - getSum2(r1, r2, c2), -1);
Pair ceiling = set.ceiling(toFind);
if (ceiling != null) {
int diff = Math.abs(toFind.value - ceiling.value);
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = ceiling.index; bestC2 = c2;
}
}
Pair floor = set.floor(toFind);
if (floor != null) {
int diff = Math.abs(toFind.value - floor.value);
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = floor.index; bestC2 = c2;
}
}
}
}
}
out.printLine(bestR1 + 1, bestC1 + 1, bestR2 + 1, bestC2 + 1);
}
private int getSum1(int r1, int r2, int c1) {
return getSumLeft(r2, c1, m-1)
+ getSumUp(c1, r1, r2)
+ getSumRight(r1, c1, m-1);
}
private int getSum2(int r1, int r2, int c2) {
return - getSumLeft(r2, c2, m-1)
+ getSumDown(c2, r1, r2)
- getSumRight(r1, c2, m-1);
}
private int getSumLeft(int r, int c1, int c2) {
return prefRowsLeft[r][c1] - prefRowsLeft[r][c2];
}
private int getSumRight(int r, int c1, int c2) {
return prefRowsRight[r][c2] - prefRowsRight[r][c1];
}
private int getSumDown(int c, int r1, int r2) {
return prefColsDown[c][r2] - prefColsDown[c][r1];
}
private int getSumUp(int c, int r1, int r2) {
return prefColsUp[c][r1] - prefColsUp[c][r2];
}
private void precalcPrefixSums() {
for (int r = 0; r < n; r++) {
for (int c = 1; c < m; c++) {
int val = prefRowsRight[r][c-1];
if (h[r][c-1] < h[r][c]) {
val += tUp;
} else if (h[r][c-1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsRight[r][c] = val;
}
}
for (int r = 0; r < n; r++) {
for (int c = m-2; c >= 0; c--) {
int val = prefRowsLeft[r][c+1];
if (h[r][c+1] < h[r][c]) {
val += tUp;
} else if (h[r][c+1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsLeft[r][c] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = 1; r < n; r++) {
int val = prefColsDown[c][r-1];
if (h[r-1][c] < h[r][c]) {
val += tUp;
} else if (h[r-1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsDown[c][r] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = n-2; r >= 0; r--) {
int val = prefColsUp[c][r+1];
if (h[r+1][c] < h[r][c]) {
val += tUp;
} else if (h[r+1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsUp[c][r] = val;
}
}
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
} | Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | 3fa881a55999f8c0423d8053aa1c57d1 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.Reader;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.util.Comparator;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
static int tp;
static int tu;
static int td;
static int f(int from, int to) {
if (from == to) return tp;
if (from > to) return td;
else return tu;
}
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int m = in.nextInt();
int needT = in.nextInt();
tp = in.nextInt();
tu = in.nextInt();
td = in.nextInt();
int[][] a = in.readInt2DArray(n, m);
int[][][] go = new int[4][n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i > 0) {
go[0][i][j] = go[0][i - 1][j] + f(a[i][j], a[i - 1][j]);
}
if (j > 0) {
go[1][i][j] = go[1][i][j - 1] + f(a[i][j], a[i][j - 1]);
}
}
}
for (int i = n - 1; i >= 0; i--) {
for (int j = m - 1; j >= 0; j--) {
if (i + 1 < n) {
go[2][i][j] = go[2][i + 1][j] + f(a[i][j], a[i + 1][j]);
}
if (j + 1 < m) {
go[3][i][j] = go[3][i][j + 1] + f(a[i][j], a[i][j + 1]);
}
}
}
int ansDif = Integer.MAX_VALUE;
int ansUp = -1;
int ansDown = -1;
int ansLeft = -1;
int ansRight = -1;
Element[] f = new Element[n - 1];
Comparator<Element> comp = new Comparator<Element>() {
public int compare(Element o1, Element o2) {
int c = Integer.compare(o1.sum, o2.sum);
if (c != 0) return c;
return Integer.compare(o1.id, o2.id);
}
};
int[] p1 = new int[n + 1];
int[] p2 = new int[n + 1];
int[] where = new int[n - 1];
for (int left = 0; left < m; left++) {
for (int right = left + 2; right < m; right++) {
Element cur = new Element(0, 0);
for (int i = 0; i < n - 1; i++) {
f[i] = new Element(go[3][i][left] - go[3][i][right] - go[0][i][left] + go[2][i][right], i);
}
Arrays.sort(f, comp);
for (int i = 0; i < n - 1; i++) where[f[i].id] = i;
for (int i = 0; i <= n; i++) p1[i] = p2[i] = i;
for (int i = n - 1; i > 0; i--) {
int zID = where[i - 1];
p1[get(p1, zID)] = get(p1, (zID == 0 ? n - 1 : zID - 1));
p2[get(p2, zID)] = get(p2, zID + 1);
int cost = go[1][i][right] - go[1][i][left] + go[0][i][left] - go[2][i][right];
cur.sum = needT - cost;
cur.id = -1;
int id = ~Arrays.binarySearch(f, cur, comp);
int prevID = id == 0 ? n - 1 : get(p1, id - 1);
int nextID = get(p2, id);
Element prev = prevID == n - 1 ? null : f[prevID];
Element next = nextID == n - 1 ? null : f[nextID];
if (prev != null) {
int all = prev.sum + cost;
if (Math.abs(all - needT) < ansDif) {
ansDif = Math.abs(all - needT);
ansUp = prev.id;
ansDown = i;
ansLeft = left;
ansRight = right;
}
}
if (next != null) {
int all = next.sum + cost;
if (Math.abs(all - needT) < ansDif) {
ansDif = Math.abs(all - needT);
ansUp = next.id;
ansDown = i;
ansLeft = left;
ansRight = right;
}
}
}
}
}
out.println((ansUp + 1) + " " + (ansLeft + 1) + " " + (ansDown + 1) + " " + (ansRight + 1));
}
static class Element {
int sum;
int id;
public Element(int sum, int id) {
this.sum = sum;
this.id = id;
}
}
static int get(int[] p, int x) {
return x == p[x] ? x : (p[x] = get(p, p[x]));
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
public int[][] readInt2DArray(int n, int m) {
int[][] ret = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = nextInt();
}
}
return ret;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
}
| Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | 5a46a515a4d412dd64d46d0d18fdfa95 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF424D extends PrintWriter {
CF424D() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF424D o = new CF424D(); o.main(); o.flush();
}
static Random rand = new Random();
static class V {
V l, r;
int key, val, x;
V(int key, int val) {
this.key = key; this.val = val; x = rand.nextInt();
}
}
V v_, l_, r_;
void split(V v, int key) {
if (v == null) {
v_ = l_ = r_ = null;
} else if (v.key < key) {
split(v.r, key);
v.r = l_; l_ = v;
} else if (v.key > key) {
split(v.l, key);
v.l = r_; r_ = v;
} else {
v_ = v; l_ = v.l; r_ = v.r;
v.l = v.r = null;
}
}
V merge(V l, V r) {
if (l == null)
return r;
if (r == null)
return l;
if (l.x <= r.x) {
l.r = merge(l.r, r);
return l;
} else {
r.l = merge(l, r.l);
return r;
}
}
void add(int key, int val) {
split(v_, key);
if (v_ == null)
v_ = new V(key, val);
v_ = merge(merge(l_, v_), r_);
}
V first(V v) {
if (v != null)
while (v.l != null)
v = v.l;
return v;
}
V last(V v) {
if (v != null)
while (v.r != null)
v = v.r;
return v;
}
int query(int key) {
split(v_, key);
int val;
if (v_ != null) {
val = v_.val;
} else {
V u = last(l_);
V w = first(r_);
if (u == null)
val = w.val;
else if (w == null)
val = u.val;
else
val = key - u.key <= w.key - key ? u.val : w.val;
}
v_ = merge(merge(l_, v_), r_);
return val;
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int t = sc.nextInt();
int tp = sc.nextInt();
int tu = sc.nextInt();
int td = sc.nextInt();
int[][] aa = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
aa[i][j] = sc.nextInt();
int[][] rr = new int[n][m];
int[][] ll = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 1; j < m; j++) {
int a_ = aa[i][j - 1], a = aa[i][j];
rr[i][j] = rr[i][j - 1] + (a_ == a ? tp : a_ < a ? tu : td);
ll[i][j] = ll[i][j - 1] + (a_ == a ? tp : a_ > a ? tu : td);
}
int[][] uu = new int[n][m];
int[][] dd = new int[n][m];
for (int j = 0; j < m; j++)
for (int i = 1; i < n; i++) {
int a_ = aa[i - 1][j], a = aa[i][j];
dd[i][j] = dd[i - 1][j] + (a_ == a ? tp : a_ < a ? tu : td);
uu[i][j] = uu[i - 1][j] + (a_ == a ? tp : a_ > a ? tu : td);
}
int d_ = 1000000001, i1_ = -1, i2_ = -1, j1_ = -1, j2_ = -1;
for (int i1 = 0; i1 < n; i1++)
for (int i2 = i1 + 2; i2 < n; i2++) {
for (int j2 = 2; j2 < m; j2++) {
int j1 = j2 - 2;
int a = rr[i1][j2] + ll[i2][j2] + (dd[i2][j2] - dd[i1][j2]);
int b = rr[i1][j1] + ll[i2][j1] - (uu[i2][j1] - uu[i1][j1]);
add(b, j1);
j1 = query(a - t);
b = rr[i1][j1] + ll[i2][j1] - (uu[i2][j1] - uu[i1][j1]);
int d = Math.abs(a - b - t);
if (d_ > d) {
d_ = d; i1_ = i1; i2_ = i2; j1_ = j1; j2_ = j2;
}
}
v_ = l_ = r_ = null;
}
println((i1_ + 1) + " " + (j1_ + 1) + " " + (i2_ + 1) + " " + (j2_ + 1));
}
}
| Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | 9ca57681633f2123f91525b78f20f7f4 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.Reader;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.util.Comparator;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
static int tp;
static int tu;
static int td;
static int f(int from, int to) {
if (from == to) return tp;
if (from > to) return td;
else return tu;
}
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int m = in.nextInt();
int needT = in.nextInt();
tp = in.nextInt();
tu = in.nextInt();
td = in.nextInt();
int[][] a = in.readInt2DArray(n, m);
int[][][] go = new int[4][n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i > 0) {
go[0][i][j] = go[0][i - 1][j] + f(a[i][j], a[i - 1][j]);
}
if (j > 0) {
go[1][i][j] = go[1][i][j - 1] + f(a[i][j], a[i][j - 1]);
}
}
}
for (int i = n - 1; i >= 0; i--) {
for (int j = m - 1; j >= 0; j--) {
if (i + 1 < n) {
go[2][i][j] = go[2][i + 1][j] + f(a[i][j], a[i + 1][j]);
}
if (j + 1 < m) {
go[3][i][j] = go[3][i][j + 1] + f(a[i][j], a[i][j + 1]);
}
}
}
int ansDif = Integer.MAX_VALUE;
int ansUp = -1;
int ansDown = -1;
int ansLeft = -1;
int ansRight = -1;
Element[] f = new Element[n - 1];
Comparator<Element> comp = new Comparator<Element>() {
public int compare(Element o1, Element o2) {
int c = Integer.compare(o1.sum, o2.sum);
if (c != 0) return c;
return Integer.compare(o1.id, o2.id);
}
};
int[] p1 = new int[n + 1];
int[] p2 = new int[n + 1];
int[] where = new int[n - 1];
for (int left = 0; left < m; left++) {
for (int right = left + 2; right < m; right++) {
Element cur = new Element(0, 0);
for (int i = 0; i < n - 1; i++) {
f[i] = new Element(go[3][i][left] - go[3][i][right] - go[0][i][left] + go[2][i][right], i);
}
Arrays.sort(f, comp);
for (int i = 0; i < n - 1; i++) where[f[i].id] = i;
for (int i = 0; i <= n; i++) p1[i] = p2[i] = i;
for (int i = n - 1; i > 0; i--) {
int zID = where[i - 1];
p1[get(p1, zID)] = get(p1, (zID == 0 ? n - 1 : zID - 1));
p2[get(p2, zID)] = get(p2, zID + 1);
int cost = go[1][i][right] - go[1][i][left] + go[0][i][left] - go[2][i][right];
cur.sum = needT - cost;
cur.id = -1;
int id = ~Arrays.binarySearch(f, cur, comp);
int prevID = id == 0 ? n - 1 : get(p1, id - 1);
int nextID = get(p2, id);
Element prev = prevID == n - 1 ? null : f[prevID];
Element next = nextID == n - 1 ? null : f[nextID];
if (prev != null) {
int all = prev.sum + cost;
if (Math.abs(all - needT) < ansDif) {
ansDif = Math.abs(all - needT);
ansUp = prev.id;
ansDown = i;
ansLeft = left;
ansRight = right;
}
}
if (next != null) {
int all = next.sum + cost;
if (Math.abs(all - needT) < ansDif) {
ansDif = Math.abs(all - needT);
ansUp = next.id;
ansDown = i;
ansLeft = left;
ansRight = right;
}
}
}
}
}
out.println((ansUp + 1) + " " + (ansLeft + 1) + " " + (ansDown + 1) + " " + (ansRight + 1));
}
static class Element {
int sum;
int id;
public Element(int sum, int id) {
this.sum = sum;
this.id = id;
}
}
static int get(int[] p, int x) {
return x == p[x] ? x : (p[x] = get(p, p[x]));
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
public int[][] readInt2DArray(int n, int m) {
int[][] ret = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = nextInt();
}
}
return ret;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
}
| Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | 8c8ba8c83cc3a3d2ed9f53868924a466 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.NavigableSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
static class Block implements Comparable<Block> {
int tot;
int col;
public Block(int tot, int col) {
this.tot = tot;
this.col = col;
}
public Block(Block rhs) {
this.tot = rhs.tot;
this.col = rhs.col;
}
public int compareTo(Block rhs) {
return this.tot - rhs.tot;
}
}
public static void solve() throws IOException {
int n = nextInt(), m = nextInt(), t = nextInt();
int tp = nextInt(), tu = nextInt(), td = nextInt();
int[][] grid = new int[n][m];
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
grid[i][j] = nextInt();
int[][] rowRightPref = new int[n][m];
int[][] colDownPref = new int[n][m];
int[][] rowLeftPref = new int[n][m];
int[][] colUpPref = new int[n][m];
for(int i = 0; i < n; i++) {
rowRightPref[i][0] = 0;
for(int j = 1; j < m; j++) {
if(grid[i][j] > grid[i][j - 1])
rowRightPref[i][j] = tu + rowRightPref[i][j - 1];
if(grid[i][j] < grid[i][j - 1])
rowRightPref[i][j] = td + rowRightPref[i][j - 1];
if(grid[i][j] == grid[i][j - 1])
rowRightPref[i][j] = tp + rowRightPref[i][j - 1];
}
}
for(int j = 0; j < m; j++) {
colDownPref[0][j] = 0;
for(int i = 1; i < n; i++) {
colDownPref[i][j] = grid[i][j] > grid[i - 1][j] ? tu + colDownPref[i - 1][j] : colDownPref[i][j];
colDownPref[i][j] = grid[i][j] < grid[i - 1][j] ? td + colDownPref[i - 1][j] : colDownPref[i][j];
colDownPref[i][j] = grid[i][j] == grid[i - 1][j] ? tp + colDownPref[i - 1][j] : colDownPref[i][j];
}
}
for(int i = 0; i < n; i++) {
rowLeftPref[i][m - 1] = 0;
for(int j = m - 2; j >= 0; j--) {
rowLeftPref[i][j] = grid[i][j] > grid[i][j + 1] ? tu + rowLeftPref[i][j + 1] : rowLeftPref[i][j];
rowLeftPref[i][j] = grid[i][j] < grid[i][j + 1] ? td + rowLeftPref[i][j + 1] : rowLeftPref[i][j];
rowLeftPref[i][j] = grid[i][j] == grid[i][j + 1] ? tp + rowLeftPref[i][j + 1] : rowLeftPref[i][j];
}
}
for(int j = 0; j < m; j++) {
colUpPref[n - 1][j] = 0;
for(int i = n - 2; i >= 0; i--) {
colUpPref[i][j] = grid[i][j] > grid[i + 1][j] ? tu + colUpPref[i + 1][j] : colUpPref[i][j];
colUpPref[i][j] = grid[i][j] < grid[i + 1][j] ? td + colUpPref[i + 1][j] : colUpPref[i][j];
colUpPref[i][j] = grid[i][j] == grid[i + 1][j] ? tp + colUpPref[i + 1][j] : colUpPref[i][j];
}
}
myDiff = Integer.MAX_VALUE;
ui = -1; uj = -1; di = -1; dj = -1;
for(int i1 = 0; i1 < n - 1; i1++) {
for(int i2 = i1 + 2; i2 < n; i2++) {
NavigableSet<Block> my = new TreeSet<Block>();
Block myLast = null, mySecondLast = null;
for(int j = 0; j < m; j++) {
//boolean debug = i1 == 4 && i2 == 5 && j == 6;
int nowSum = rowRightPref[i1][j] + colDownPref[i2][j] - colDownPref[i1][j] + rowLeftPref[i2][0] - rowLeftPref[i2][j]
+ colUpPref[i1][0] - colUpPref[i2][0];
int findSum = nowSum - t;
Block largestSmaller = my.lower(new Block(findSum + 1, 1));
if(largestSmaller != null) {
int nowDiff = (nowSum - largestSmaller.tot) - t;
updateIt(nowDiff, i1 + 1, largestSmaller.col + 1, i2 + 1, j + 1);
}
Block smallestLarger = my.higher(new Block(findSum, 1));
if(smallestLarger != null) {
int nowDiff = (nowSum - smallestLarger.tot) - t;
updateIt(nowDiff, i1 + 1, smallestLarger.col + 1, i2 + 1, j + 1);
}
//if(debug) out.println(nowSum + " " + findSum);
mySecondLast = myLast;
myLast = new Block(nowSum - (colDownPref[i2][j] - colDownPref[i1][j]) - (colUpPref[i1][j] - colUpPref[i2][j]), j);
if(j > 0)
my.add(new Block(mySecondLast));
}
}
}
//out.println(myDiff);
out.println(ui + " " + uj + " " + di + " " + dj);
}
static int ui, uj, di, dj, myDiff;
public static void updateIt(int nowDiff, int nui, int nuj, int dui, int duj) {
if(Math.abs(nowDiff) < Math.abs(myDiff)) {
ui = nui;
uj = nuj;
di = dui;
dj = duj;
myDiff = nowDiff;
}
}
static BufferedReader br;
static StringTokenizer st;
static PrintWriter out;
public static void main(String[] args) throws IOException {
InputStream input = System.in;
OutputStream output = System.out;
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(output);
solve();
out.close();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if(line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
} | Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | 065c39da49913b12d3b5df20a99b322d | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
static class Block implements Comparable<Block> {
int tot;
int col;
public Block(int tot, int col) {
this.tot = tot;
this.col = col;
}
public Block(Block rhs) {
this.tot = rhs.tot;
this.col = rhs.col;
}
public int compareTo(Block rhs) {
return this.tot - rhs.tot;
}
}
static TreeSet<Block> my = new TreeSet<Block>();
static int[][] grid, rowRightPref, rowLeftPref, colDownPref, colUpPref;
public static void solve() throws IOException {
int n = nextInt(), m = nextInt(), t = nextInt();
int tp = nextInt(), tu = nextInt(), td = nextInt();
grid = new int[n][m];
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
grid[i][j] = nextInt();
rowRightPref = new int[n][m];
colDownPref = new int[n][m];
rowLeftPref = new int[n][m];
colUpPref = new int[n][m];
for(int i = 0; i < n; i++) {
rowRightPref[i][0] = 0;
for(int j = 1; j < m; j++) {
if(grid[i][j] > grid[i][j - 1])
rowRightPref[i][j] = tu + rowRightPref[i][j - 1];
if(grid[i][j] < grid[i][j - 1])
rowRightPref[i][j] = td + rowRightPref[i][j - 1];
if(grid[i][j] == grid[i][j - 1])
rowRightPref[i][j] = tp + rowRightPref[i][j - 1];
}
}
for(int j = 0; j < m; j++) {
colDownPref[0][j] = 0;
for(int i = 1; i < n; i++) {
colDownPref[i][j] = grid[i][j] > grid[i - 1][j] ? tu + colDownPref[i - 1][j] : colDownPref[i][j];
colDownPref[i][j] = grid[i][j] < grid[i - 1][j] ? td + colDownPref[i - 1][j] : colDownPref[i][j];
colDownPref[i][j] = grid[i][j] == grid[i - 1][j] ? tp + colDownPref[i - 1][j] : colDownPref[i][j];
}
}
for(int i = 0; i < n; i++) {
rowLeftPref[i][m - 1] = 0;
for(int j = m - 2; j >= 0; j--) {
rowLeftPref[i][j] = grid[i][j] > grid[i][j + 1] ? tu + rowLeftPref[i][j + 1] : rowLeftPref[i][j];
rowLeftPref[i][j] = grid[i][j] < grid[i][j + 1] ? td + rowLeftPref[i][j + 1] : rowLeftPref[i][j];
rowLeftPref[i][j] = grid[i][j] == grid[i][j + 1] ? tp + rowLeftPref[i][j + 1] : rowLeftPref[i][j];
}
}
for(int j = 0; j < m; j++) {
colUpPref[n - 1][j] = 0;
for(int i = n - 2; i >= 0; i--) {
colUpPref[i][j] = grid[i][j] > grid[i + 1][j] ? tu + colUpPref[i + 1][j] : colUpPref[i][j];
colUpPref[i][j] = grid[i][j] < grid[i + 1][j] ? td + colUpPref[i + 1][j] : colUpPref[i][j];
colUpPref[i][j] = grid[i][j] == grid[i + 1][j] ? tp + colUpPref[i + 1][j] : colUpPref[i][j];
}
}
myDiff = Integer.MAX_VALUE;
Block largestSmaller, smallestLarger;
ui = -1; uj = -1; di = -1; dj = -1;
for(int i1 = 0; i1 < n - 1; i1++) {
for(int i2 = i1 + 2; i2 < n; i2++) {
my.clear();
for(int j = 2; j < m; j++) {
int lastSum = rowRightPref[i1][j - 2] + colDownPref[i2][j - 2] - colDownPref[i1][j - 2] + rowLeftPref[i2][0] - rowLeftPref[i2][j - 2]
+ colUpPref[i1][0] - colUpPref[i2][0];
my.add(new Block(lastSum - (colDownPref[i2][j - 2] - colDownPref[i1][j - 2]) - (colUpPref[i1][j - 2] - colUpPref[i2][j - 2]), j - 2));
int nowSum = rowRightPref[i1][j] + colDownPref[i2][j] - colDownPref[i1][j] + rowLeftPref[i2][0] - rowLeftPref[i2][j]
+ colUpPref[i1][0] - colUpPref[i2][0];
int findSum = nowSum - t;
Block toFind = new Block(findSum, 1);
largestSmaller = my.floor(toFind);
if(largestSmaller != null) {
int nowDiff = (nowSum - largestSmaller.tot) - t;
if(Math.abs(nowDiff) < Math.abs(myDiff)) {
ui = i1 + 1;
uj = largestSmaller.col + 1;
di = i2 + 1;
dj = j + 1;
myDiff = nowDiff;
}
//updateIt(nowDiff, i1 + 1, largestSmaller.col + 1, i2 + 1, j + 1);
}
smallestLarger = my.ceiling(toFind);
if(smallestLarger != null) {
int nowDiff = (nowSum - smallestLarger.tot) - t;
if(Math.abs(nowDiff) < Math.abs(myDiff)) {
ui = i1 + 1;
uj = smallestLarger.col + 1;
di = i2 + 1;
dj = j + 1;
myDiff = nowDiff;
}
//updateIt(nowDiff, i1 + 1, smallestLarger.col + 1, i2 + 1, j + 1);
}
}
}
}
out.println(ui + " " + uj + " " + di + " " + dj);
}
static int ui, uj, di, dj, myDiff;
/*
public static void updateIt(int nowDiff, int nui, int nuj, int dui, int duj) {
if(Math.abs(nowDiff) < Math.abs(myDiff)) {
ui = nui;
uj = nuj;
di = dui;
dj = duj;
myDiff = nowDiff;
}
}
*/
static BufferedReader br;
static StringTokenizer st;
static PrintWriter out;
public static void main(String[] args) throws IOException {
InputStream input = System.in;
OutputStream output = System.out;
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(output);
solve();
out.close();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if(line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
} | Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | bbfa79ecfb1ed451bbec891d6d404609 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CF242_D solver = new CF242_D();
solver.solve(1, in, out);
out.close();
}
}
class CF242_D {
/*static class Pair implements Comparable<Pair> {
int value;
int index;
Pair(int value, int index) {
this.value = value;
this.index = index;
}
public int compareTo(Pair o) {
if (value == o.value) {
return index - o.index;
}
return value - o.value;
}
}*/
int n, m, tNeed;
int tPlain, tUp, tDown;
int[][] h;
int[][] prefRowsLeft;
int[][] prefRowsRight;
int[][] prefColsDown;
int[][] prefColsUp;
TreeSet<Long> set = new TreeSet<Long>();
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
m = in.readInt();
tNeed = in.readInt();
tPlain = in.readInt();
tUp = in.readInt();
tDown = in.readInt();
h = IOUtils.readIntTable(in, n, m);
prefRowsLeft = new int[n][m];
prefRowsRight = new int[n][m];
prefColsDown = new int[m][n];
prefColsUp = new int[m][n];
precalcPrefixSums();
int bestR1 = -1, bestR2 = -1;
int bestC1 = -1, bestC2 = -1;
int bestDiff = (int) 1e9;
for (int r1 = 0; r1 < n; r1++) {
for (int r2 = r1 + 2; r2 < n; r2++) {
set.clear();
for (int c1 = 0, c2 = 2; c2 < m; c1++, c2++) {
set.add(zip(getSum1(r1, r2, c1), c1));
long toFind = zip(tNeed - getSum2(r1, r2, c2), -1);
Long ceiling = set.ceiling(toFind);
if (ceiling != null) {
int diff = Math.abs(value(toFind) - value(ceiling));
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = index(ceiling); bestC2 = c2;
}
}
Long floor = set.floor(toFind);
if (floor != null) {
int diff = Math.abs(value(toFind) - value(floor));
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = index(floor); bestC2 = c2;
}
}
}
}
}
out.printLine(bestR1 + 1, bestC1 + 1, bestR2 + 1, bestC2 + 1);
}
private long zip(int a, int b) {
return ((long)a << 32) | (b & 0x00000000FFFFFFFFL);
}
private int value(long z) {
return (int) (z >>> 32);
}
private int index(long z) {
return (int) z;
}
private int getSum1(int r1, int r2, int c1) {
return getSumLeft(r2, c1, m-1)
+ getSumUp(c1, r1, r2)
+ getSumRight(r1, c1, m-1);
}
private int getSum2(int r1, int r2, int c2) {
return - getSumLeft(r2, c2, m-1)
+ getSumDown(c2, r1, r2)
- getSumRight(r1, c2, m-1);
}
private int getSumLeft(int r, int c1, int c2) {
return prefRowsLeft[r][c1] - prefRowsLeft[r][c2];
}
private int getSumRight(int r, int c1, int c2) {
return prefRowsRight[r][c2] - prefRowsRight[r][c1];
}
private int getSumDown(int c, int r1, int r2) {
return prefColsDown[c][r2] - prefColsDown[c][r1];
}
private int getSumUp(int c, int r1, int r2) {
return prefColsUp[c][r1] - prefColsUp[c][r2];
}
private void precalcPrefixSums() {
for (int r = 0; r < n; r++) {
for (int c = 1; c < m; c++) {
int val = prefRowsRight[r][c-1];
if (h[r][c-1] < h[r][c]) {
val += tUp;
} else if (h[r][c-1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsRight[r][c] = val;
}
}
for (int r = 0; r < n; r++) {
for (int c = m-2; c >= 0; c--) {
int val = prefRowsLeft[r][c+1];
if (h[r][c+1] < h[r][c]) {
val += tUp;
} else if (h[r][c+1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsLeft[r][c] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = 1; r < n; r++) {
int val = prefColsDown[c][r-1];
if (h[r-1][c] < h[r][c]) {
val += tUp;
} else if (h[r-1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsDown[c][r] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = n-2; r >= 0; r--) {
int val = prefColsUp[c][r+1];
if (h[r+1][c] < h[r][c]) {
val += tUp;
} else if (h[r+1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsUp[c][r] = val;
}
}
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
} | Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | 00d0c85f14c88c0cbb59a885e7aa2115 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.*;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CF242_D solver = new CF242_D();
solver.solve(1, in, out);
out.close();
}
}
class CF242_D {
// static class Pair implements Comparable<Pair> {
// int value;
// int index;
//
// Pair(int value, int index) {
// this.value = value;
// this.index = index;
// }
//
// public int compareTo(Pair o) {
// if (value == o.value) {
// return index - o.index;
// }
// return value - o.value;
// }
// }
int n, m, tNeed;
int tPlain, tUp, tDown;
int[][] h;
int[][] prefRowsLeft;
int[][] prefRowsRight;
int[][] prefColsDown;
int[][] prefColsUp;
//TreeSet<Pair> set = new TreeSet<Pair>();
EzLongTreeSet set = new EzLongTreeSet();
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
m = in.readInt();
tNeed = in.readInt();
tPlain = in.readInt();
tUp = in.readInt();
tDown = in.readInt();
h = IOUtils.readIntTable(in, n, m);
prefRowsLeft = new int[n][m];
prefRowsRight = new int[n][m];
prefColsDown = new int[m][n];
prefColsUp = new int[m][n];
precalcPrefixSums();
int bestR1 = -1, bestR2 = -1;
int bestC1 = -1, bestC2 = -1;
int bestDiff = (int) 1e9;
for (int r1 = 0; r1 < n; r1++) {
for (int r2 = r1 + 2; r2 < n; r2++) {
set.clear();
for (int c1 = 0, c2 = 2; c2 < m; c1++, c2++) {
set.add(zip(getSum1(r1, r2, c1), c1));
long toFind = zip(tNeed - getSum2(r1, r2, c2), -1);
long ceiling = set.ceiling(toFind);
if (set.wasCorrectValueReturned()) {
int diff = Math.abs(value(toFind) - value(ceiling));
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = index(ceiling); bestC2 = c2;
}
}
long floor = set.floor(toFind);
if (set.wasCorrectValueReturned()) {
int diff = Math.abs(value(toFind) - value(floor));
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = index(floor); bestC2 = c2;
}
}
}
}
}
out.printLine(bestR1 + 1, bestC1 + 1, bestR2 + 1, bestC2 + 1);
}
private long zip(int a, int b) {
return ((long)a << 32) | (b & 0x00000000FFFFFFFFL);
}
private int value(long z) {
return (int) (z >>> 32);
}
private int index(long z) {
return (int) z;
}
private int getSum1(int r1, int r2, int c1) {
return getSumLeft(r2, c1, m-1)
+ getSumUp(c1, r1, r2)
+ getSumRight(r1, c1, m-1);
}
private int getSum2(int r1, int r2, int c2) {
return - getSumLeft(r2, c2, m-1)
+ getSumDown(c2, r1, r2)
- getSumRight(r1, c2, m-1);
}
private int getSumLeft(int r, int c1, int c2) {
return prefRowsLeft[r][c1] - prefRowsLeft[r][c2];
}
private int getSumRight(int r, int c1, int c2) {
return prefRowsRight[r][c2] - prefRowsRight[r][c1];
}
private int getSumDown(int c, int r1, int r2) {
return prefColsDown[c][r2] - prefColsDown[c][r1];
}
private int getSumUp(int c, int r1, int r2) {
return prefColsUp[c][r1] - prefColsUp[c][r2];
}
private void precalcPrefixSums() {
for (int r = 0; r < n; r++) {
for (int c = 1; c < m; c++) {
int val = prefRowsRight[r][c-1];
if (h[r][c-1] < h[r][c]) {
val += tUp;
} else if (h[r][c-1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsRight[r][c] = val;
}
}
for (int r = 0; r < n; r++) {
for (int c = m-2; c >= 0; c--) {
int val = prefRowsLeft[r][c+1];
if (h[r][c+1] < h[r][c]) {
val += tUp;
} else if (h[r][c+1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsLeft[r][c] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = 1; r < n; r++) {
int val = prefColsDown[c][r-1];
if (h[r-1][c] < h[r][c]) {
val += tUp;
} else if (h[r-1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsDown[c][r] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = n-2; r >= 0; r--) {
int val = prefColsUp[c][r+1];
if (h[r+1][c] < h[r][c]) {
val += tUp;
} else if (h[r+1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsUp[c][r] = val;
}
}
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
}
class EzLongTreeSet {
private static final int DEFAULT_CAPACITY = 10;
private static final double ENLARGE_SCALE = 2.0;
private static final boolean BLACK = false;
private static final boolean RED = true;
private static class Node {
private long key;
private Node left;
private Node right;
private Node p;
private boolean color;
private Node(long key, Node left, Node right, Node p, boolean color) {
this.key = key;
this.left = left;
this.right = right;
this.p = p;
this.color = color;
}
}
// Arrays are 1-indexed. Index 0 is a null node.
private Node[] nodes;
private final Node NULL;
// TODO add size field, add swapping with last element while removing
private int totalNodes;
private int removedNodes;
private Node root;
private boolean wasCorrectValueReturned;
public EzLongTreeSet() {
this(DEFAULT_CAPACITY);
}
public EzLongTreeSet(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity must be non-negative");
}
capacity++;
nodes = new Node[capacity];
totalNodes = 0;
removedNodes = 0;
NULL = new Node((long) 0, null, null, null, BLACK);
NULL.left = NULL.right = NULL.p = NULL;
nodes[0] = NULL;
root = NULL;
wasCorrectValueReturned = false;
}
public int size() {
return totalNodes - removedNodes;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean contains(long element) {
Node x = root;
while (x != NULL) {
if (element < x.key) {
x = x.left;
} else if (element > x.key) {
x = x.right;
} else {
return true;
}
}
return false;
}
public long[] toArray() {
long[] result = new long[size()];
Node x = firstNode();
for (int i = 0; x != NULL; x = successorNode(x), i++) {
result[i] = x.key;
}
return result;
}
public boolean add(long element) {
Node y = NULL;
Node x = root;
while (x != NULL) {
//noinspection SuspiciousNameCombination
y = x;
if (element < x.key) {
x = x.left;
} else if (element > x.key) {
x = x.right;
} else {
return false;
}
}
if (totalNodes == nodes.length - 1) {
enlarge();
}
Node z = new Node(element, NULL, NULL, y, RED);
nodes[++totalNodes] = z;
if (y == NULL) {
root = z;
} else {
if (element < y.key) {
y.left = z;
} else {
y.right = z;
}
}
fixAfterAdd(z);
return true;
}
public boolean remove(long element) {
Node z = root;
while (z != NULL) {
if (element < z.key) {
z = z.left;
} else if (element > z.key) {
z = z.right;
} else {
removeNode(z);
return true;
}
}
return false;
}
private void removeNode(Node z) {
Node y = (z.left == NULL || z.right == NULL) ? z : successorNode(z);
Node x = (y.left!= NULL) ? y.left : y.right;
x.p = y.p;
if (y.p == NULL) {
root = x;
} else {
if (y == y.p.left) {
y.p.left = x;
} else {
y.p.right = x;
}
}
if (y != z) {
z.key = y.key;
}
//noinspection PointlessBooleanExpression
if (y.color == BLACK) {
fixAfterRemove(x);
}
removedNodes++;
}
private Node successorNode(Node x) {
if (x.right != NULL) {
x = x.right;
while (x.left != NULL) {
x = x.left;
}
return x;
} else {
Node y = x.p;
while (y != NULL && x == y.right) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
return y;
}
}
@SuppressWarnings("PointlessBooleanExpression")
private void fixAfterAdd(Node z) {
while (z.p.color == RED) {
if (z.p == z.p.p.left) {
Node y = z.p.p.right;
if (y.color == RED) {
z.p.color = BLACK;
y.color = BLACK;
z.p.p.color = RED;
z = z.p.p;
} else {
if (z == z.p.right) {
z = z.p;
rotateLeft(z);
}
z.p.color = BLACK;
z.p.p.color = RED;
rotateRight(z.p.p);
}
} else {
Node y = z.p.p.left;
if (y.color == RED) {
z.p.color = BLACK;
y.color = BLACK;
z.p.p.color = RED;
z = z.p.p;
} else {
if (z == z.p.left) {
z = z.p;
rotateRight(z);
}
z.p.color = BLACK;
z.p.p.color = RED;
rotateLeft(z.p.p);
}
}
}
root.color = BLACK;
}
@SuppressWarnings("PointlessBooleanExpression")
private void fixAfterRemove(Node x) {
while (x != root && x.color == BLACK) {
if (x == x.p.left) {
Node w = x.p.right;
if (w.color == RED) {
w.color = BLACK;
x.p.color = RED;
rotateLeft(x.p);
w = x.p.right;
}
if (w.left.color == BLACK && w.right.color == BLACK) {
w.color = RED;
x = x.p;
} else {
if (w.right.color == BLACK) {
w.left.color = BLACK;
w.color = RED;
rotateRight(w);
w = x.p.right;
}
w.color = x.p.color;
x.p.color = BLACK;
w.right.color = BLACK;
rotateLeft(x.p);
x = root;
}
} else {
Node w = x.p.left;
if (w.color == RED) {
w.color = BLACK;
x.p.color = RED;
rotateRight(x.p);
w = x.p.left;
}
if (w.left.color == BLACK && w.right.color == BLACK) {
w.color = RED;
x = x.p;
} else {
if (w.left.color == BLACK) {
w.right.color = BLACK;
w.color = RED;
rotateLeft(w);
w = x.p.left;
}
w.color = x.p.color;
x.p.color = BLACK;
w.left.color = BLACK;
rotateRight(x.p);
x = root;
}
}
}
x.color = BLACK;
}
private void rotateLeft(Node x) {
Node y = x.right;
x.right = y.left;
if (y.left != NULL) {
y.left.p = x;
}
y.p = x.p;
if (x.p == NULL) {
root = y;
} else {
if (x == x.p.left) {
x.p.left = y;
} else {
x.p.right = y;
}
}
y.left = x;
x.p = y;
}
private void rotateRight(Node x) {
Node y = x.left;
x.left = y.right;
if (y.right != NULL) {
y.right.p = x;
}
y.p = x.p;
if (x.p == NULL) {
root = y;
} else {
if (x == x.p.right) {
x.p.right = y;
} else {
x.p.left = y;
}
}
y.right = x;
x.p = y;
}
public void clear() {
NULL.color = BLACK;
NULL.left = NULL.right = NULL.p = NULL;
totalNodes = 0;
removedNodes = 0;
root = NULL;
wasCorrectValueReturned = false;
}
private void enlarge() {
int newLength = Math.max(nodes.length + 1, (int) (nodes.length * ENLARGE_SCALE));
nodes = Arrays.copyOf(nodes, newLength);
}
private Node firstNode() {
Node x = root;
while (x.left != NULL) {
x = x.left;
}
return x;
}
private Node lastNode() {
Node x = root;
while (x.right != NULL) {
x = x.right;
}
return x;
}
public long getFirst() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = firstNode();
wasCorrectValueReturned = true;
return x.key;
}
public long getLast() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = lastNode();
wasCorrectValueReturned = true;
return x.key;
}
public long removeFirst() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = firstNode();
wasCorrectValueReturned = true;
final long removedElement = x.key;
removeNode(x);
return removedElement;
}
public long removeLast() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = lastNode();
wasCorrectValueReturned = true;
final long removedElement = x.key;
removeNode(x);
return removedElement;
}
public long floor(long element) {
Node x = root;
while (x != NULL) {
if (element > x.key) {
if (x.right != NULL) {
x = x.right;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else if (element < x.key) {
if (x.left != NULL) {
x = x.left;
} else {
Node y = x.p;
while (y != NULL && x == y.left) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
} else {
wasCorrectValueReturned = true;
return x.key;
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public long ceiling(long element) {
Node x = root;
while (x != NULL) {
if (element < x.key) {
if (x.left != NULL) {
x = x.left;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else if (element > x.key) {
if (x.right != NULL) {
x = x.right;
} else {
Node y = x.p;
while (y != NULL && x == y.right) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
} else {
wasCorrectValueReturned = true;
return x.key;
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public long lower(long element) {
Node x = root;
while (x != NULL) {
if (element > x.key) {
if (x.right != NULL) {
x = x.right;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else {
if (x.left != NULL) {
x = x.left;
} else {
Node y = x.p;
while (y != NULL && x == y.left) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public long higher(long element) {
Node x = root;
while (x != NULL) {
if (element < x.key) {
if (x.left != NULL) {
x = x.left;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else {
if (x.right != NULL) {
x = x.right;
} else {
Node y = x.p;
while (y != NULL && x == y.right) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public boolean wasCorrectValueReturned() {
return wasCorrectValueReturned;
}
}
| Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | bcc3c6138d40b1f35e6c2948a9700000 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.*;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CF242_D solver = new CF242_D();
solver.solve(1, in, out);
out.close();
}
}
class CF242_D {
// static class Pair implements Comparable<Pair> {
// int value;
// int index;
//
// Pair(int value, int index) {
// this.value = value;
// this.index = index;
// }
//
// public int compareTo(Pair o) {
// if (value == o.value) {
// return index - o.index;
// }
// return value - o.value;
// }
// }
int n, m, tNeed;
int tPlain, tUp, tDown;
int[][] h;
int[][] prefRowsLeft;
int[][] prefRowsRight;
int[][] prefColsDown;
int[][] prefColsUp;
//TreeSet<Pair> set = new TreeSet<Pair>();
EzLongTreeSet set = new EzLongTreeSet();
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
m = in.readInt();
tNeed = in.readInt();
tPlain = in.readInt();
tUp = in.readInt();
tDown = in.readInt();
h = IOUtils.readIntTable(in, n, m);
prefRowsLeft = new int[n][m];
prefRowsRight = new int[n][m];
prefColsDown = new int[m][n];
prefColsUp = new int[m][n];
precalcPrefixSums();
int bestR1 = -1, bestR2 = -1;
int bestC1 = -1, bestC2 = -1;
int bestDiff = (int) 1e9;
for (int r1 = 0; r1 < n; r1++) {
for (int r2 = r1 + 2; r2 < n; r2++) {
set.clear();
for (int c1 = 0, c2 = 2; c2 < m; c1++, c2++) {
set.add(zip(getSum1(r1, r2, c1), c1));
long toFind = zip(tNeed - getSum2(r1, r2, c2), -1);
long ceiling = set.ceiling(toFind);
if (set.wasCorrectValueReturned()) {
int diff = Math.abs(value(toFind) - value(ceiling));
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = index(ceiling); bestC2 = c2;
}
}
long floor = set.floor(toFind);
if (set.wasCorrectValueReturned()) {
int diff = Math.abs(value(toFind) - value(floor));
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = index(floor); bestC2 = c2;
}
}
}
}
}
out.printLine(bestR1 + 1, bestC1 + 1, bestR2 + 1, bestC2 + 1);
}
private long zip(int a, int b) {
return ((long)a << 32) | (b & 0x00000000FFFFFFFFL);
}
private int value(long z) {
return (int) (z >>> 32);
}
private int index(long z) {
return (int) z;
}
private int getSum1(int r1, int r2, int c1) {
return getSumLeft(r2, c1, m-1)
+ getSumUp(c1, r1, r2)
+ getSumRight(r1, c1, m-1);
}
private int getSum2(int r1, int r2, int c2) {
return - getSumLeft(r2, c2, m-1)
+ getSumDown(c2, r1, r2)
- getSumRight(r1, c2, m-1);
}
private int getSumLeft(int r, int c1, int c2) {
return prefRowsLeft[r][c1] - prefRowsLeft[r][c2];
}
private int getSumRight(int r, int c1, int c2) {
return prefRowsRight[r][c2] - prefRowsRight[r][c1];
}
private int getSumDown(int c, int r1, int r2) {
return prefColsDown[c][r2] - prefColsDown[c][r1];
}
private int getSumUp(int c, int r1, int r2) {
return prefColsUp[c][r1] - prefColsUp[c][r2];
}
private void precalcPrefixSums() {
for (int r = 0; r < n; r++) {
for (int c = 1; c < m; c++) {
int val = prefRowsRight[r][c-1];
if (h[r][c-1] < h[r][c]) {
val += tUp;
} else if (h[r][c-1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsRight[r][c] = val;
}
}
for (int r = 0; r < n; r++) {
for (int c = m-2; c >= 0; c--) {
int val = prefRowsLeft[r][c+1];
if (h[r][c+1] < h[r][c]) {
val += tUp;
} else if (h[r][c+1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsLeft[r][c] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = 1; r < n; r++) {
int val = prefColsDown[c][r-1];
if (h[r-1][c] < h[r][c]) {
val += tUp;
} else if (h[r-1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsDown[c][r] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = n-2; r >= 0; r--) {
int val = prefColsUp[c][r+1];
if (h[r+1][c] < h[r][c]) {
val += tUp;
} else if (h[r+1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsUp[c][r] = val;
}
}
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
}
class EzLongTreeSet {
private static final int DEFAULT_CAPACITY = 10;
private static final double ENLARGE_SCALE = 2.0;
private static final boolean BLACK = false;
private static final boolean RED = true;
private static final int NULL = 0;
// Arrays are 1-indexed. Index 0 is a null node.
private long[] key;
private int[] left;
private int[] right;
private int[] p;
private boolean[] color;
private int totalNodes;
private int removedNodes;
private int root;
private boolean wasCorrectValueReturned;
public EzLongTreeSet() {
this(DEFAULT_CAPACITY);
}
public EzLongTreeSet(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity must be non-negative");
}
capacity++;
key = new long[capacity];
left = new int[capacity];
right = new int[capacity];
p = new int[capacity];
color = new boolean[capacity];
color[NULL] = BLACK;
totalNodes = 0;
removedNodes = 0;
root = NULL;
wasCorrectValueReturned = false;
}
public int size() {
return totalNodes - removedNodes;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean contains(long element) {
int x = root;
while (x != NULL) {
if (element < key[x]) {
x = left[x];
} else if (element > key[x]) {
x = right[x];
} else {
return true;
}
}
return false;
}
public long[] toArray() {
long[] result = new long[size()];
for (int i = 0, x = firstNode(); x != NULL; x = successorNode(x), i++) {
result[i] = key[x];
}
return result;
}
public boolean add(long element) {
int y = NULL;
int x = root;
while (x != NULL) {
//noinspection SuspiciousNameCombination
y = x;
if (element < key[x]) {
x = left[x];
} else if (element > key[x]) {
x = right[x];
} else {
return false;
}
}
if (totalNodes == color.length - 1) {
enlarge();
}
int z = ++totalNodes;
key[z] = element;
p[z] = y;
if (y == NULL) {
root = z;
} else {
if (element < key[y]) {
left[y] = z;
} else {
right[y] = z;
}
}
left[z] = NULL;
right[z] = NULL;
color[z] = RED;
fixAfterAdd(z);
return true;
}
public boolean remove(long element) {
int z = root;
while (z != NULL) {
if (element < key[z]) {
z = left[z];
} else if (element > key[z]) {
z = right[z];
} else {
removeNode(z);
return true;
}
}
return false;
}
private void removeNode(int z) {
int y = (left[z] == NULL || right[z] == NULL) ? z : successorNode(z);
int x = (left[y] != NULL) ? left[y] : right[y];
p[x] = p[y];
if (p[y] == NULL) {
root = x;
} else {
if (y == left[p[y]]) {
left[p[y]] = x;
} else {
right[p[y]] = x;
}
}
if (y != z) {
key[z] = key[y];
}
//noinspection PointlessBooleanExpression
if (color[y] == BLACK) {
fixAfterRemove(x);
}
removedNodes++;
}
private int successorNode(int x) {
if (right[x] != NULL) {
x = right[x];
while (left[x] != NULL) {
x = left[x];
}
return x;
} else {
int y = p[x];
while (y != NULL && x == right[y]) {
//noinspection SuspiciousNameCombination
x = y;
y = p[y];
}
return y;
}
}
@SuppressWarnings("PointlessBooleanExpression")
private void fixAfterAdd(int z) {
while (color[p[z]] == RED) {
if (p[z] == left[p[p[z]]]) {
int y = right[p[p[z]]];
if (color[y] == RED) {
color[p[z]] = BLACK;
color[y] = BLACK;
color[p[p[z]]] = RED;
z = p[p[z]];
} else {
if (z == right[p[z]]) {
z = p[z];
rotateLeft(z);
}
color[p[z]] = BLACK;
color[p[p[z]]] = RED;
rotateRight(p[p[z]]);
}
} else {
int y = left[p[p[z]]];
if (color[y] == RED) {
color[p[z]] = BLACK;
color[y] = BLACK;
color[p[p[z]]] = RED;
z = p[p[z]];
} else {
if (z == left[p[z]]) {
z = p[z];
rotateRight(z);
}
color[p[z]] = BLACK;
color[p[p[z]]] = RED;
rotateLeft(p[p[z]]);
}
}
}
color[root] = BLACK;
}
@SuppressWarnings("PointlessBooleanExpression")
private void fixAfterRemove(int x) {
while (x != root && color[x] == BLACK) {
if (x == left[p[x]]) {
int w = right[p[x]];
if (color[w] == RED) {
color[w] = BLACK;
color[p[x]] = RED;
rotateLeft(p[x]);
w = right[p[x]];
}
if (color[left[w]] == BLACK && color[right[w]] == BLACK) {
color[w] = RED;
x = p[x];
} else {
if (color[right[w]] == BLACK) {
color[left[w]] = BLACK;
color[w] = RED;
rotateRight(w);
w = right[p[x]];
}
color[w] = color[p[x]];
color[p[x]] = BLACK;
color[right[w]] = BLACK;
rotateLeft(p[x]);
x = root;
}
} else {
int w = left[p[x]];
if (color[w] == RED) {
color[w] = BLACK;
color[p[x]] = RED;
rotateRight(p[x]);
w = left[p[x]];
}
if (color[left[w]] == BLACK && color[right[w]] == BLACK) {
color[w] = RED;
x = p[x];
} else {
if (color[left[w]] == BLACK) {
color[right[w]] = BLACK;
color[w] = RED;
rotateLeft(w);
w = left[p[x]];
}
color[w] = color[p[x]];
color[p[x]] = BLACK;
color[left[w]] = BLACK;
rotateRight(p[x]);
x = root;
}
}
}
color[x] = BLACK;
}
private void rotateLeft(int x) {
int y = right[x];
right[x] = left[y];
if (left[y] != NULL) {
p[left[y]] = x;
}
p[y] = p[x];
if (p[x] == NULL) {
root = y;
} else {
if (x == left[p[x]]) {
left[p[x]] = y;
} else {
right[p[x]] = y;
}
}
left[y] = x;
p[x] = y;
}
private void rotateRight(int x) {
int y = left[x];
left[x] = right[y];
if (right[y] != NULL) {
p[right[y]] = x;
}
p[y] = p[x];
if (p[x] == NULL) {
root = y;
} else {
if (x == right[p[x]]) {
right[p[x]] = y;
} else {
left[p[x]] = y;
}
}
right[y] = x;
p[x] = y;
}
public void clear() {
color[NULL] = BLACK;
totalNodes = 0;
removedNodes = 0;
root = NULL;
wasCorrectValueReturned = false;
}
private void enlarge() {
int newLength = Math.max(color.length + 1, (int) (color.length * ENLARGE_SCALE));
key = Arrays.copyOf(key, newLength);
left = Arrays.copyOf(left, newLength);
right = Arrays.copyOf(right, newLength);
p = Arrays.copyOf(p, newLength);
color = Arrays.copyOf(color, newLength);
}
private int firstNode() {
int x = root;
while (left[x] != NULL) {
x = left[x];
}
return x;
}
private int lastNode() {
int x = root;
while (right[x] != NULL) {
x = right[x];
}
return x;
}
public long getFirst() {
if (root == NULL) {
wasCorrectValueReturned = false;
return key[NULL];
}
final int x = firstNode();
wasCorrectValueReturned = true;
return key[x];
}
public long getLast() {
if (root == NULL) {
wasCorrectValueReturned = false;
return key[NULL];
}
final int x = lastNode();
wasCorrectValueReturned = true;
return key[x];
}
public long removeFirst() {
if (root == NULL) {
wasCorrectValueReturned = false;
return key[NULL];
}
final int x = firstNode();
wasCorrectValueReturned = true;
final long removedElement = key[x];
removeNode(x);
return removedElement;
}
public long removeLast() {
if (root == NULL) {
wasCorrectValueReturned = false;
return key[NULL];
}
final int x = lastNode();
wasCorrectValueReturned = true;
final long removedElement = key[x];
removeNode(x);
return removedElement;
}
public long floor(long element) {
int x = root;
while (x != NULL) {
if (element > key[x]) {
if (right[x] != NULL) {
x = right[x];
} else {
wasCorrectValueReturned = true;
return key[x];
}
} else if (element < key[x]) {
if (left[x] != NULL) {
x = left[x];
} else {
int y = p[x];
while (y != NULL && x == left[y]) {
//noinspection SuspiciousNameCombination
x = y;
y = p[y];
}
wasCorrectValueReturned = (y != NULL);
return key[y];
}
} else {
wasCorrectValueReturned = true;
return key[x];
}
}
wasCorrectValueReturned = false;
return key[NULL];
}
public long ceiling(long element) {
int x = root;
while (x != NULL) {
if (element < key[x]) {
if (left[x] != NULL) {
x = left[x];
} else {
wasCorrectValueReturned = true;
return key[x];
}
} else if (element > key[x]) {
if (right[x] != NULL) {
x = right[x];
} else {
int y = p[x];
while (y != NULL && x == right[y]) {
//noinspection SuspiciousNameCombination
x = y;
y = p[y];
}
wasCorrectValueReturned = (y != NULL);
return key[y];
}
} else {
wasCorrectValueReturned = true;
return key[x];
}
}
wasCorrectValueReturned = false;
return key[NULL];
}
public long lower(long element) {
int x = root;
while (x != NULL) {
if (element > key[x]) {
if (right[x] != NULL) {
x = right[x];
} else {
wasCorrectValueReturned = true;
return key[x];
}
} else {
if (left[x] != NULL) {
x = left[x];
} else {
int y = p[x];
while (y != NULL && x == left[y]) {
//noinspection SuspiciousNameCombination
x = y;
y = p[y];
}
wasCorrectValueReturned = (y != NULL);
return key[y];
}
}
}
wasCorrectValueReturned = false;
return key[NULL];
}
public long higher(long element) {
int x = root;
while (x != NULL) {
if (element < key[x]) {
if (left[x] != NULL) {
x = left[x];
} else {
wasCorrectValueReturned = true;
return key[x];
}
} else {
if (right[x] != NULL) {
x = right[x];
} else {
int y = p[x];
while (y != NULL && x == right[y]) {
//noinspection SuspiciousNameCombination
x = y;
y = p[y];
}
wasCorrectValueReturned = (y != NULL);
return key[y];
}
}
}
wasCorrectValueReturned = false;
return key[NULL];
}
public boolean wasCorrectValueReturned() {
return wasCorrectValueReturned;
}
} | Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | eac210f14d2bf7ad6cc155cd39fd9a10 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CF242_D solver = new CF242_D();
solver.solve(1, in, out);
out.close();
}
}
class CF242_D {
static class Pair implements Comparable<Pair> {
int value;
int index;
Pair(int value, int index) {
this.value = value;
this.index = index;
}
public int compareTo(Pair o) {
if (value == o.value) {
return index - o.index;
}
return value - o.value;
}
}
int n, m, tNeed;
int tPlain, tUp, tDown;
int[][] h;
int[][] prefRowsLeft;
int[][] prefRowsRight;
int[][] prefColsDown;
int[][] prefColsUp;
TreeSet<Pair> set = new TreeSet<Pair>();
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
m = in.readInt();
tNeed = in.readInt();
tPlain = in.readInt();
tUp = in.readInt();
tDown = in.readInt();
h = IOUtils.readIntTable(in, n, m);
prefRowsLeft = new int[n][m];
prefRowsRight = new int[n][m];
prefColsDown = new int[m][n];
prefColsUp = new int[m][n];
precalcPrefixSums();
int bestR1 = -1, bestR2 = -1;
int bestC1 = -1, bestC2 = -1;
int bestDiff = (int) 1e9;
for (int r1 = 0; r1 < n; r1++) {
for (int r2 = r1 + 2; r2 < n; r2++) {
set.clear();
for (int c1 = 0, c2 = 2; c2 < m; c1++, c2++) {
set.add(new Pair(getSum1(r1, r2, c1), c1));
Pair toFind = new Pair(tNeed - getSum2(r1, r2, c2), -1);
Pair ceiling = set.ceiling(toFind);
if (ceiling != null) {
int diff = Math.abs(toFind.value - ceiling.value);
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = ceiling.index; bestC2 = c2;
}
}
Pair floor = set.floor(toFind);
if (floor != null) {
int diff = Math.abs(toFind.value - floor.value);
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = floor.index; bestC2 = c2;
}
}
}
}
}
out.printLine(bestR1 + 1, bestC1 + 1, bestR2 + 1, bestC2 + 1);
}
private int getSum1(int r1, int r2, int c1) {
return getSumLeft(r2, c1, m-1)
+ getSumUp(c1, r1, r2)
+ getSumRight(r1, c1, m-1);
}
private int getSum2(int r1, int r2, int c2) {
return - getSumLeft(r2, c2, m-1)
+ getSumDown(c2, r1, r2)
- getSumRight(r1, c2, m-1);
}
private int getSumLeft(int r, int c1, int c2) {
return prefRowsLeft[r][c1] - prefRowsLeft[r][c2];
}
private int getSumRight(int r, int c1, int c2) {
return prefRowsRight[r][c2] - prefRowsRight[r][c1];
}
private int getSumDown(int c, int r1, int r2) {
return prefColsDown[c][r2] - prefColsDown[c][r1];
}
private int getSumUp(int c, int r1, int r2) {
return prefColsUp[c][r1] - prefColsUp[c][r2];
}
private void precalcPrefixSums() {
for (int r = 0; r < n; r++) {
for (int c = 1; c < m; c++) {
int val = prefRowsRight[r][c-1];
if (h[r][c-1] < h[r][c]) {
val += tUp;
} else if (h[r][c-1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsRight[r][c] = val;
}
}
for (int r = 0; r < n; r++) {
for (int c = m-2; c >= 0; c--) {
int val = prefRowsLeft[r][c+1];
if (h[r][c+1] < h[r][c]) {
val += tUp;
} else if (h[r][c+1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsLeft[r][c] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = 1; r < n; r++) {
int val = prefColsDown[c][r-1];
if (h[r-1][c] < h[r][c]) {
val += tUp;
} else if (h[r-1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsDown[c][r] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = n-2; r >= 0; r--) {
int val = prefColsUp[c][r+1];
if (h[r+1][c] < h[r][c]) {
val += tUp;
} else if (h[r+1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsUp[c][r] = val;
}
}
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
} | Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | ba90b363776117c2b0c5d015fec00430 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CF242_D solver = new CF242_D();
solver.solve(1, in, out);
out.close();
}
}
class CF242_D {
static class Pair implements Comparable<Pair> {
int value;
int index;
Pair(int value, int index) {
this.value = value;
this.index = index;
}
public int compareTo(Pair o) {
if (value == o.value) {
return index - o.index;
}
return value - o.value;
}
}
int n, m, tNeed;
int tPlain, tUp, tDown;
int[][] h;
int[][] prefRowsLeft;
int[][] prefRowsRight;
int[][] prefColsDown;
int[][] prefColsUp;
TreeSet<Pair> set = new TreeSet<Pair>();
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
m = in.readInt();
tNeed = in.readInt();
tPlain = in.readInt();
tUp = in.readInt();
tDown = in.readInt();
h = IOUtils.readIntTable(in, n, m);
prefRowsLeft = new int[n][m];
prefRowsRight = new int[n][m];
prefColsDown = new int[m][n];
prefColsUp = new int[m][n];
precalcPrefixSums();
int bestR1 = -1, bestR2 = -1;
int bestC1 = -1, bestC2 = -1;
int bestDiff = (int) 1e9;
for (int r1 = 0; r1 < n; r1++) {
for (int r2 = r1 + 2; r2 < n; r2++) {
set.clear();
for (int c1 = 0, c2 = 2; c2 < m; c1++, c2++) {
set.add(new Pair(getSum1(r1, r2, c1), c1));
Pair toFind = new Pair(tNeed - getSum2(r1, r2, c2), -1);
Pair ceiling = set.ceiling(toFind);
if (ceiling != null) {
int diff = Math.abs(toFind.value - ceiling.value);
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = ceiling.index; bestC2 = c2;
}
}
Pair floor = set.floor(toFind);
if (floor != null) {
int diff = Math.abs(toFind.value - floor.value);
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = floor.index; bestC2 = c2;
}
}
}
}
}
out.printLine(bestR1 + 1, bestC1 + 1, bestR2 + 1, bestC2 + 1);
}
private int getSum1(int r1, int r2, int c1) {
return getSumLeft(r2, c1, m-1)
+ getSumUp(c1, r1, r2)
+ getSumRight(r1, c1, m-1);
}
private int getSum2(int r1, int r2, int c2) {
return - getSumLeft(r2, c2, m-1)
+ getSumDown(c2, r1, r2)
- getSumRight(r1, c2, m-1);
}
private int getSumLeft(int r, int c1, int c2) {
return prefRowsLeft[r][c1] - prefRowsLeft[r][c2];
}
private int getSumRight(int r, int c1, int c2) {
return prefRowsRight[r][c2] - prefRowsRight[r][c1];
}
private int getSumDown(int c, int r1, int r2) {
return prefColsDown[c][r2] - prefColsDown[c][r1];
}
private int getSumUp(int c, int r1, int r2) {
return prefColsUp[c][r1] - prefColsUp[c][r2];
}
private void precalcPrefixSums() {
for (int r = 0; r < n; r++) {
for (int c = 1; c < m; c++) {
int val = prefRowsRight[r][c-1];
if (h[r][c-1] < h[r][c]) {
val += tUp;
} else if (h[r][c-1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsRight[r][c] = val;
}
}
for (int r = 0; r < n; r++) {
for (int c = m-2; c >= 0; c--) {
int val = prefRowsLeft[r][c+1];
if (h[r][c+1] < h[r][c]) {
val += tUp;
} else if (h[r][c+1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsLeft[r][c] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = 1; r < n; r++) {
int val = prefColsDown[c][r-1];
if (h[r-1][c] < h[r][c]) {
val += tUp;
} else if (h[r-1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsDown[c][r] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = n-2; r >= 0; r--) {
int val = prefColsUp[c][r+1];
if (h[r+1][c] < h[r][c]) {
val += tUp;
} else if (h[r+1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsUp[c][r] = val;
}
}
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
}
| Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | 3a347857801a17c4c093aaaec7c8ec34 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.*;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CF242_D solver = new CF242_D();
solver.solve(1, in, out);
out.close();
}
}
class CF242_D {
// static class Pair implements Comparable<Pair> {
// int value;
// int index;
//
// Pair(int value, int index) {
// this.value = value;
// this.index = index;
// }
//
// public int compareTo(Pair o) {
// if (value == o.value) {
// return index - o.index;
// }
// return value - o.value;
// }
// }
int n, m, tNeed;
int tPlain, tUp, tDown;
int[][] h;
int[][] prefRowsLeft;
int[][] prefRowsRight;
int[][] prefColsDown;
int[][] prefColsUp;
//TreeSet<Pair> set = new TreeSet<Pair>();
EzLongTreeSet set = new EzLongTreeSet();
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
m = in.readInt();
tNeed = in.readInt();
tPlain = in.readInt();
tUp = in.readInt();
tDown = in.readInt();
h = IOUtils.readIntTable(in, n, m);
prefRowsLeft = new int[n][m];
prefRowsRight = new int[n][m];
prefColsDown = new int[m][n];
prefColsUp = new int[m][n];
precalcPrefixSums();
int bestR1 = -1, bestR2 = -1;
int bestC1 = -1, bestC2 = -1;
int bestDiff = (int) 1e9;
for (int r1 = 0; r1 < n; r1++) {
for (int r2 = r1 + 2; r2 < n; r2++) {
set.clear();
for (int c1 = 0, c2 = 2; c2 < m; c1++, c2++) {
set.add(zip(getSum1(r1, r2, c1), c1));
long toFind = zip(tNeed - getSum2(r1, r2, c2), -1);
long ceiling = set.ceiling(toFind);
if (set.wasCorrectValueReturned()) {
int diff = Math.abs(value(toFind) - value(ceiling));
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = index(ceiling); bestC2 = c2;
}
}
long floor = set.floor(toFind);
if (set.wasCorrectValueReturned()) {
int diff = Math.abs(value(toFind) - value(floor));
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = index(floor); bestC2 = c2;
}
}
}
}
}
out.printLine(bestR1 + 1, bestC1 + 1, bestR2 + 1, bestC2 + 1);
}
private long zip(int a, int b) {
return ((long)a << 32) | (b & 0x00000000FFFFFFFFL);
}
private int value(long z) {
return (int) (z >>> 32);
}
private int index(long z) {
return (int) z;
}
private int getSum1(int r1, int r2, int c1) {
return getSumLeft(r2, c1, m-1)
+ getSumUp(c1, r1, r2)
+ getSumRight(r1, c1, m-1);
}
private int getSum2(int r1, int r2, int c2) {
return - getSumLeft(r2, c2, m-1)
+ getSumDown(c2, r1, r2)
- getSumRight(r1, c2, m-1);
}
private int getSumLeft(int r, int c1, int c2) {
return prefRowsLeft[r][c1] - prefRowsLeft[r][c2];
}
private int getSumRight(int r, int c1, int c2) {
return prefRowsRight[r][c2] - prefRowsRight[r][c1];
}
private int getSumDown(int c, int r1, int r2) {
return prefColsDown[c][r2] - prefColsDown[c][r1];
}
private int getSumUp(int c, int r1, int r2) {
return prefColsUp[c][r1] - prefColsUp[c][r2];
}
private void precalcPrefixSums() {
for (int r = 0; r < n; r++) {
for (int c = 1; c < m; c++) {
int val = prefRowsRight[r][c-1];
if (h[r][c-1] < h[r][c]) {
val += tUp;
} else if (h[r][c-1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsRight[r][c] = val;
}
}
for (int r = 0; r < n; r++) {
for (int c = m-2; c >= 0; c--) {
int val = prefRowsLeft[r][c+1];
if (h[r][c+1] < h[r][c]) {
val += tUp;
} else if (h[r][c+1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsLeft[r][c] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = 1; r < n; r++) {
int val = prefColsDown[c][r-1];
if (h[r-1][c] < h[r][c]) {
val += tUp;
} else if (h[r-1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsDown[c][r] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = n-2; r >= 0; r--) {
int val = prefColsUp[c][r+1];
if (h[r+1][c] < h[r][c]) {
val += tUp;
} else if (h[r+1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsUp[c][r] = val;
}
}
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
}
class EzLongTreeSet {
private static final int DEFAULT_CAPACITY = 10;
private static final double ENLARGE_SCALE = 2.0;
private static final boolean BLACK = false;
private static final boolean RED = true;
private static final class Node {
private long key;
private Node left;
private Node right;
private Node p;
private boolean color;
private Node(long key, Node left, Node right, Node p, boolean color) {
this.key = key;
this.left = left;
this.right = right;
this.p = p;
this.color = color;
}
}
// Arrays are 1-indexed. Index 0 is a null node.
private Node[] nodes;
private final Node NULL;
// TODO add size field, add swapping with last element while removing
private int totalNodes;
private int removedNodes;
private Node root;
private boolean wasCorrectValueReturned;
public EzLongTreeSet() {
this(DEFAULT_CAPACITY);
}
public EzLongTreeSet(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity must be non-negative");
}
capacity++;
nodes = new Node[capacity];
totalNodes = 0;
removedNodes = 0;
NULL = new Node((long) 0, null, null, null, BLACK);
NULL.left = NULL.right = NULL.p = NULL;
nodes[0] = NULL;
root = NULL;
wasCorrectValueReturned = false;
}
public int size() {
return totalNodes - removedNodes;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean contains(long element) {
Node x = root;
while (x != NULL) {
if (element < x.key) {
x = x.left;
} else if (element > x.key) {
x = x.right;
} else {
return true;
}
}
return false;
}
public long[] toArray() {
long[] result = new long[size()];
Node x = firstNode();
for (int i = 0; x != NULL; x = successorNode(x), i++) {
result[i] = x.key;
}
return result;
}
public boolean add(long element) {
Node y = NULL;
Node x = root;
while (x != NULL) {
//noinspection SuspiciousNameCombination
y = x;
if (element < x.key) {
x = x.left;
} else if (element > x.key) {
x = x.right;
} else {
return false;
}
}
if (totalNodes == nodes.length - 1) {
enlarge();
}
Node z = new Node(element, NULL, NULL, y, RED);
nodes[++totalNodes] = z;
if (y == NULL) {
root = z;
} else {
if (element < y.key) {
y.left = z;
} else {
y.right = z;
}
}
fixAfterAdd(z);
return true;
}
public boolean remove(long element) {
Node z = root;
while (z != NULL) {
if (element < z.key) {
z = z.left;
} else if (element > z.key) {
z = z.right;
} else {
removeNode(z);
return true;
}
}
return false;
}
private void removeNode(Node z) {
Node y = (z.left == NULL || z.right == NULL) ? z : successorNode(z);
Node x = (y.left!= NULL) ? y.left : y.right;
x.p = y.p;
if (y.p == NULL) {
root = x;
} else {
if (y == y.p.left) {
y.p.left = x;
} else {
y.p.right = x;
}
}
if (y != z) {
z.key = y.key;
}
//noinspection PointlessBooleanExpression
if (y.color == BLACK) {
fixAfterRemove(x);
}
removedNodes++;
}
private Node successorNode(Node x) {
if (x.right != NULL) {
x = x.right;
while (x.left != NULL) {
x = x.left;
}
return x;
} else {
Node y = x.p;
while (y != NULL && x == y.right) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
return y;
}
}
@SuppressWarnings("PointlessBooleanExpression")
private void fixAfterAdd(Node z) {
while (z.p.color == RED) {
if (z.p == z.p.p.left) {
Node y = z.p.p.right;
if (y.color == RED) {
z.p.color = BLACK;
y.color = BLACK;
z.p.p.color = RED;
z = z.p.p;
} else {
if (z == z.p.right) {
z = z.p;
rotateLeft(z);
}
z.p.color = BLACK;
z.p.p.color = RED;
rotateRight(z.p.p);
}
} else {
Node y = z.p.p.left;
if (y.color == RED) {
z.p.color = BLACK;
y.color = BLACK;
z.p.p.color = RED;
z = z.p.p;
} else {
if (z == z.p.left) {
z = z.p;
rotateRight(z);
}
z.p.color = BLACK;
z.p.p.color = RED;
rotateLeft(z.p.p);
}
}
}
root.color = BLACK;
}
@SuppressWarnings("PointlessBooleanExpression")
private void fixAfterRemove(Node x) {
while (x != root && x.color == BLACK) {
if (x == x.p.left) {
Node w = x.p.right;
if (w.color == RED) {
w.color = BLACK;
x.p.color = RED;
rotateLeft(x.p);
w = x.p.right;
}
if (w.left.color == BLACK && w.right.color == BLACK) {
w.color = RED;
x = x.p;
} else {
if (w.right.color == BLACK) {
w.left.color = BLACK;
w.color = RED;
rotateRight(w);
w = x.p.right;
}
w.color = x.p.color;
x.p.color = BLACK;
w.right.color = BLACK;
rotateLeft(x.p);
x = root;
}
} else {
Node w = x.p.left;
if (w.color == RED) {
w.color = BLACK;
x.p.color = RED;
rotateRight(x.p);
w = x.p.left;
}
if (w.left.color == BLACK && w.right.color == BLACK) {
w.color = RED;
x = x.p;
} else {
if (w.left.color == BLACK) {
w.right.color = BLACK;
w.color = RED;
rotateLeft(w);
w = x.p.left;
}
w.color = x.p.color;
x.p.color = BLACK;
w.left.color = BLACK;
rotateRight(x.p);
x = root;
}
}
}
x.color = BLACK;
}
private void rotateLeft(Node x) {
Node y = x.right;
x.right = y.left;
if (y.left != NULL) {
y.left.p = x;
}
y.p = x.p;
if (x.p == NULL) {
root = y;
} else {
if (x == x.p.left) {
x.p.left = y;
} else {
x.p.right = y;
}
}
y.left = x;
x.p = y;
}
private void rotateRight(Node x) {
Node y = x.left;
x.left = y.right;
if (y.right != NULL) {
y.right.p = x;
}
y.p = x.p;
if (x.p == NULL) {
root = y;
} else {
if (x == x.p.right) {
x.p.right = y;
} else {
x.p.left = y;
}
}
y.right = x;
x.p = y;
}
public void clear() {
NULL.color = BLACK;
NULL.left = NULL.right = NULL.p = NULL;
totalNodes = 0;
removedNodes = 0;
root = NULL;
wasCorrectValueReturned = false;
}
private void enlarge() {
int newLength = Math.max(nodes.length + 1, (int) (nodes.length * ENLARGE_SCALE));
nodes = Arrays.copyOf(nodes, newLength);
}
private Node firstNode() {
Node x = root;
while (x.left != NULL) {
x = x.left;
}
return x;
}
private Node lastNode() {
Node x = root;
while (x.right != NULL) {
x = x.right;
}
return x;
}
public long getFirst() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = firstNode();
wasCorrectValueReturned = true;
return x.key;
}
public long getLast() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = lastNode();
wasCorrectValueReturned = true;
return x.key;
}
public long removeFirst() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = firstNode();
wasCorrectValueReturned = true;
final long removedElement = x.key;
removeNode(x);
return removedElement;
}
public long removeLast() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = lastNode();
wasCorrectValueReturned = true;
final long removedElement = x.key;
removeNode(x);
return removedElement;
}
public long floor(long element) {
Node x = root;
while (x != NULL) {
if (element > x.key) {
if (x.right != NULL) {
x = x.right;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else if (element < x.key) {
if (x.left != NULL) {
x = x.left;
} else {
Node y = x.p;
while (y != NULL && x == y.left) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
} else {
wasCorrectValueReturned = true;
return x.key;
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public long ceiling(long element) {
Node x = root;
while (x != NULL) {
if (element < x.key) {
if (x.left != NULL) {
x = x.left;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else if (element > x.key) {
if (x.right != NULL) {
x = x.right;
} else {
Node y = x.p;
while (y != NULL && x == y.right) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
} else {
wasCorrectValueReturned = true;
return x.key;
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public long lower(long element) {
Node x = root;
while (x != NULL) {
if (element > x.key) {
if (x.right != NULL) {
x = x.right;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else {
if (x.left != NULL) {
x = x.left;
} else {
Node y = x.p;
while (y != NULL && x == y.left) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public long higher(long element) {
Node x = root;
while (x != NULL) {
if (element < x.key) {
if (x.left != NULL) {
x = x.left;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else {
if (x.right != NULL) {
x = x.right;
} else {
Node y = x.p;
while (y != NULL && x == y.right) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public boolean wasCorrectValueReturned() {
return wasCorrectValueReturned;
}
}
| Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 8 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | 91e997e723d2647ae7472e42b351c737 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
public class A {
static int[][] down, up, left, right;
static int H, W;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
H = sc.nextInt();
W = sc.nextInt();
long target = sc.nextLong();
int[][] grid = new int[H][W];
int ff = sc.nextInt();
int uu = sc.nextInt();
int dd = sc.nextInt();
int[] delta = new int[] { dd, ff, uu };
for (int a = 0; a < H; a++) {
for (int b = 0; b < W; b++) {
grid[a][b] = sc.nextInt();
}
}
down = new int[H][W];
up = new int[H][W];
left = new int[H][W];
right = new int[H][W];
for (int a = 0; a < H; a++) {
for (int b = 1; b < W; b++) {
int change = grid[a][b] - grid[a][b - 1];
right[a][b] = right[a][b - 1]
+ delta[(int) (Math.signum(change) + 1)];
}
}
for (int a = 0; a < H; a++) {
for (int b = W - 2; b >= 0; b--) {
int change = grid[a][b] - grid[a][b + 1];
left[a][b] = left[a][b + 1]
+ delta[(int) (Math.signum(change) + 1)];
}
}
for (int b = 0; b < W; b++) {
for (int a = 1; a < H; a++) {
int change = grid[a][b] - grid[a - 1][b];
down[a][b] = down[a - 1][b]
+ delta[(int) (Math.signum(change) + 1)];
}
}
for (int b = 0; b < W; b++) {
for (int a = H - 2; a >= 0; a--) {
int change = grid[a][b] - grid[a + 1][b];
up[a][b] = up[a + 1][b]
+ delta[(int) (Math.signum(change) + 1)];
}
}
long best = Long.MAX_VALUE;
String bestS = "";
for (int a = 0; a < H; a++) {
for (int b = 0; b < W; b++) {
// topleft = ab
for (int c = a + 2; c < H; c++) {
int low = b+2;
int high = W-1;
int mid =0;
while(low<=high){
mid = (low+high)>>1;
long clockwise = calc(a, b, c, mid);
// System.out.println(mid+" "+clockwise);
if(Math.abs(clockwise-target)<best){
best = Math.abs(clockwise-target);
bestS = (a+1)+" "+(b+1)+" "+(c+1)+" "+(mid+1);
}
if(clockwise>target){
high = mid-1;
}
else if(clockwise<target){
low = mid+1;
}
else{
break;
}
}
}
}
}
out.println(bestS);
out.close();
}
private static long calc(int a, int b, int c, int d) {
long R= right[a][d]-right[a][b];
long D= down[c][d]-down[a][d];
long L= left[c][b]-left[c][d];
long U= up[a][b]-up[c][b];
return R+D+L+U;
}
} | Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 6 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | de063f71072dfe58cddb0d176b1713b0 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CF242_D solver = new CF242_D();
solver.solve(1, in, out);
out.close();
}
}
class CF242_D {
static class Pair implements Comparable<Pair> {
int value;
int index;
Pair(int value, int index) {
this.value = value;
this.index = index;
}
public int compareTo(Pair o) {
if (value == o.value) {
return index - o.index;
}
return value - o.value;
}
}
int n, m, tNeed;
int tPlain, tUp, tDown;
int[][] h;
int[][] prefRowsLeft;
int[][] prefRowsRight;
int[][] prefColsDown;
int[][] prefColsUp;
TreeSet<Pair> set = new TreeSet<Pair>();
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
m = in.readInt();
tNeed = in.readInt();
tPlain = in.readInt();
tUp = in.readInt();
tDown = in.readInt();
h = IOUtils.readIntTable(in, n, m);
prefRowsLeft = new int[n][m];
prefRowsRight = new int[n][m];
prefColsDown = new int[m][n];
prefColsUp = new int[m][n];
precalcPrefixSums();
int bestR1 = -1, bestR2 = -1;
int bestC1 = -1, bestC2 = -1;
int bestDiff = (int) 1e9;
for (int r1 = 0; r1 < n; r1++) {
for (int r2 = r1 + 2; r2 < n; r2++) {
set.clear();
for (int c1 = 0, c2 = 2; c2 < m; c1++, c2++) {
set.add(new Pair(getSum1(r1, r2, c1), c1));
Pair toFind = new Pair(tNeed - getSum2(r1, r2, c2), -1);
Pair ceiling = set.ceiling(toFind);
if (ceiling != null) {
int diff = Math.abs(toFind.value - ceiling.value);
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = ceiling.index; bestC2 = c2;
}
}
Pair floor = set.floor(toFind);
if (floor != null) {
int diff = Math.abs(toFind.value - floor.value);
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = floor.index; bestC2 = c2;
}
}
}
}
}
out.printLine(bestR1 + 1, bestC1 + 1, bestR2 + 1, bestC2 + 1);
}
private int getSum1(int r1, int r2, int c1) {
return getSumLeft(r2, c1, m-1)
+ getSumUp(c1, r1, r2)
+ getSumRight(r1, c1, m-1);
}
private int getSum2(int r1, int r2, int c2) {
return - getSumLeft(r2, c2, m-1)
+ getSumDown(c2, r1, r2)
- getSumRight(r1, c2, m-1);
}
private int getSumLeft(int r, int c1, int c2) {
return prefRowsLeft[r][c1] - prefRowsLeft[r][c2];
}
private int getSumRight(int r, int c1, int c2) {
return prefRowsRight[r][c2] - prefRowsRight[r][c1];
}
private int getSumDown(int c, int r1, int r2) {
return prefColsDown[c][r2] - prefColsDown[c][r1];
}
private int getSumUp(int c, int r1, int r2) {
return prefColsUp[c][r1] - prefColsUp[c][r2];
}
private void precalcPrefixSums() {
for (int r = 0; r < n; r++) {
for (int c = 1; c < m; c++) {
int val = prefRowsRight[r][c-1];
if (h[r][c-1] < h[r][c]) {
val += tUp;
} else if (h[r][c-1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsRight[r][c] = val;
}
}
for (int r = 0; r < n; r++) {
for (int c = m-2; c >= 0; c--) {
int val = prefRowsLeft[r][c+1];
if (h[r][c+1] < h[r][c]) {
val += tUp;
} else if (h[r][c+1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsLeft[r][c] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = 1; r < n; r++) {
int val = prefColsDown[c][r-1];
if (h[r-1][c] < h[r][c]) {
val += tUp;
} else if (h[r-1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsDown[c][r] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = n-2; r >= 0; r--) {
int val = prefColsUp[c][r+1];
if (h[r+1][c] < h[r][c]) {
val += tUp;
} else if (h[r+1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsUp[c][r] = val;
}
}
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
}
| Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 6 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | 25d3c39e9044955c628aacb13d248a40 | train_000.jsonl | 1398409200 | Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.*;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CF242_D solver = new CF242_D();
solver.solve(1, in, out);
out.close();
}
}
class CF242_D {
// static class Pair implements Comparable<Pair> {
// int value;
// int index;
//
// Pair(int value, int index) {
// this.value = value;
// this.index = index;
// }
//
// public int compareTo(Pair o) {
// if (value == o.value) {
// return index - o.index;
// }
// return value - o.value;
// }
// }
int n, m, tNeed;
int tPlain, tUp, tDown;
int[][] h;
int[][] prefRowsLeft;
int[][] prefRowsRight;
int[][] prefColsDown;
int[][] prefColsUp;
//TreeSet<Pair> set = new TreeSet<Pair>();
EzLongTreeSet set = new EzLongTreeSet();
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
m = in.readInt();
tNeed = in.readInt();
tPlain = in.readInt();
tUp = in.readInt();
tDown = in.readInt();
h = IOUtils.readIntTable(in, n, m);
prefRowsLeft = new int[n][m];
prefRowsRight = new int[n][m];
prefColsDown = new int[m][n];
prefColsUp = new int[m][n];
precalcPrefixSums();
int bestR1 = -1, bestR2 = -1;
int bestC1 = -1, bestC2 = -1;
int bestDiff = (int) 1e9;
for (int r1 = 0; r1 < n; r1++) {
for (int r2 = r1 + 2; r2 < n; r2++) {
set.clear();
for (int c1 = 0, c2 = 2; c2 < m; c1++, c2++) {
set.add(zip(getSum1(r1, r2, c1), c1));
long toFind = zip(tNeed - getSum2(r1, r2, c2), -1);
long ceiling = set.ceiling(toFind);
if (set.wasCorrectValueReturned()) {
int diff = Math.abs(value(toFind) - value(ceiling));
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = index(ceiling); bestC2 = c2;
}
}
long floor = set.floor(toFind);
if (set.wasCorrectValueReturned()) {
int diff = Math.abs(value(toFind) - value(floor));
if (diff < bestDiff) {
bestDiff = diff;
bestR1 = r1; bestR2 = r2;
bestC1 = index(floor); bestC2 = c2;
}
}
}
}
}
out.printLine(bestR1 + 1, bestC1 + 1, bestR2 + 1, bestC2 + 1);
}
private long zip(int a, int b) {
return ((long)a << 32) | (b & 0x00000000FFFFFFFFL);
}
private int value(long z) {
return (int) (z >>> 32);
}
private int index(long z) {
return (int) z;
}
private int getSum1(int r1, int r2, int c1) {
return getSumLeft(r2, c1, m-1)
+ getSumUp(c1, r1, r2)
+ getSumRight(r1, c1, m-1);
}
private int getSum2(int r1, int r2, int c2) {
return - getSumLeft(r2, c2, m-1)
+ getSumDown(c2, r1, r2)
- getSumRight(r1, c2, m-1);
}
private int getSumLeft(int r, int c1, int c2) {
return prefRowsLeft[r][c1] - prefRowsLeft[r][c2];
}
private int getSumRight(int r, int c1, int c2) {
return prefRowsRight[r][c2] - prefRowsRight[r][c1];
}
private int getSumDown(int c, int r1, int r2) {
return prefColsDown[c][r2] - prefColsDown[c][r1];
}
private int getSumUp(int c, int r1, int r2) {
return prefColsUp[c][r1] - prefColsUp[c][r2];
}
private void precalcPrefixSums() {
for (int r = 0; r < n; r++) {
for (int c = 1; c < m; c++) {
int val = prefRowsRight[r][c-1];
if (h[r][c-1] < h[r][c]) {
val += tUp;
} else if (h[r][c-1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsRight[r][c] = val;
}
}
for (int r = 0; r < n; r++) {
for (int c = m-2; c >= 0; c--) {
int val = prefRowsLeft[r][c+1];
if (h[r][c+1] < h[r][c]) {
val += tUp;
} else if (h[r][c+1] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefRowsLeft[r][c] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = 1; r < n; r++) {
int val = prefColsDown[c][r-1];
if (h[r-1][c] < h[r][c]) {
val += tUp;
} else if (h[r-1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsDown[c][r] = val;
}
}
for (int c = 0; c < m; c++) {
for (int r = n-2; r >= 0; r--) {
int val = prefColsUp[c][r+1];
if (h[r+1][c] < h[r][c]) {
val += tUp;
} else if (h[r+1][c] > h[r][c]) {
val += tDown;
} else {
val += tPlain;
}
prefColsUp[c][r] = val;
}
}
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
}
class EzLongTreeSet {
private static final int DEFAULT_CAPACITY = 10;
private static final double ENLARGE_SCALE = 2.0;
private static final boolean BLACK = false;
private static final boolean RED = true;
private static final class Node {
private long key;
private Node left;
private Node right;
private Node p;
private boolean color;
private Node(long key, Node left, Node right, Node p, boolean color) {
this.key = key;
this.left = left;
this.right = right;
this.p = p;
this.color = color;
}
}
// Arrays are 1-indexed. Index 0 is a null node.
private Node[] nodes;
private final Node NULL;
// TODO add size field, add swapping with last element while removing
private int totalNodes;
private int removedNodes;
private Node root;
private boolean wasCorrectValueReturned;
public EzLongTreeSet() {
this(DEFAULT_CAPACITY);
}
public EzLongTreeSet(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity must be non-negative");
}
capacity++;
nodes = new Node[capacity];
totalNodes = 0;
removedNodes = 0;
NULL = new Node((long) 0, null, null, null, BLACK);
NULL.left = NULL.right = NULL.p = NULL;
nodes[0] = NULL;
root = NULL;
wasCorrectValueReturned = false;
}
public int size() {
return totalNodes - removedNodes;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean contains(long element) {
Node x = root;
while (x != NULL) {
if (element < x.key) {
x = x.left;
} else if (element > x.key) {
x = x.right;
} else {
return true;
}
}
return false;
}
public long[] toArray() {
long[] result = new long[size()];
Node x = firstNode();
for (int i = 0; x != NULL; x = successorNode(x), i++) {
result[i] = x.key;
}
return result;
}
public boolean add(long element) {
Node y = NULL;
Node x = root;
while (x != NULL) {
//noinspection SuspiciousNameCombination
y = x;
if (element < x.key) {
x = x.left;
} else if (element > x.key) {
x = x.right;
} else {
return false;
}
}
if (totalNodes == nodes.length - 1) {
enlarge();
}
Node z = new Node(element, NULL, NULL, y, RED);
nodes[++totalNodes] = z;
if (y == NULL) {
root = z;
} else {
if (element < y.key) {
y.left = z;
} else {
y.right = z;
}
}
fixAfterAdd(z);
return true;
}
public boolean remove(long element) {
Node z = root;
while (z != NULL) {
if (element < z.key) {
z = z.left;
} else if (element > z.key) {
z = z.right;
} else {
removeNode(z);
return true;
}
}
return false;
}
private void removeNode(Node z) {
Node y = (z.left == NULL || z.right == NULL) ? z : successorNode(z);
Node x = (y.left!= NULL) ? y.left : y.right;
x.p = y.p;
if (y.p == NULL) {
root = x;
} else {
if (y == y.p.left) {
y.p.left = x;
} else {
y.p.right = x;
}
}
if (y != z) {
z.key = y.key;
}
//noinspection PointlessBooleanExpression
if (y.color == BLACK) {
fixAfterRemove(x);
}
removedNodes++;
}
private Node successorNode(Node x) {
if (x.right != NULL) {
x = x.right;
while (x.left != NULL) {
x = x.left;
}
return x;
} else {
Node y = x.p;
while (y != NULL && x == y.right) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
return y;
}
}
@SuppressWarnings("PointlessBooleanExpression")
private void fixAfterAdd(Node z) {
while (z.p.color == RED) {
if (z.p == z.p.p.left) {
Node y = z.p.p.right;
if (y.color == RED) {
z.p.color = BLACK;
y.color = BLACK;
z.p.p.color = RED;
z = z.p.p;
} else {
if (z == z.p.right) {
z = z.p;
rotateLeft(z);
}
z.p.color = BLACK;
z.p.p.color = RED;
rotateRight(z.p.p);
}
} else {
Node y = z.p.p.left;
if (y.color == RED) {
z.p.color = BLACK;
y.color = BLACK;
z.p.p.color = RED;
z = z.p.p;
} else {
if (z == z.p.left) {
z = z.p;
rotateRight(z);
}
z.p.color = BLACK;
z.p.p.color = RED;
rotateLeft(z.p.p);
}
}
}
root.color = BLACK;
}
@SuppressWarnings("PointlessBooleanExpression")
private void fixAfterRemove(Node x) {
while (x != root && x.color == BLACK) {
if (x == x.p.left) {
Node w = x.p.right;
if (w.color == RED) {
w.color = BLACK;
x.p.color = RED;
rotateLeft(x.p);
w = x.p.right;
}
if (w.left.color == BLACK && w.right.color == BLACK) {
w.color = RED;
x = x.p;
} else {
if (w.right.color == BLACK) {
w.left.color = BLACK;
w.color = RED;
rotateRight(w);
w = x.p.right;
}
w.color = x.p.color;
x.p.color = BLACK;
w.right.color = BLACK;
rotateLeft(x.p);
x = root;
}
} else {
Node w = x.p.left;
if (w.color == RED) {
w.color = BLACK;
x.p.color = RED;
rotateRight(x.p);
w = x.p.left;
}
if (w.left.color == BLACK && w.right.color == BLACK) {
w.color = RED;
x = x.p;
} else {
if (w.left.color == BLACK) {
w.right.color = BLACK;
w.color = RED;
rotateLeft(w);
w = x.p.left;
}
w.color = x.p.color;
x.p.color = BLACK;
w.left.color = BLACK;
rotateRight(x.p);
x = root;
}
}
}
x.color = BLACK;
}
private void rotateLeft(Node x) {
Node y = x.right;
x.right = y.left;
if (y.left != NULL) {
y.left.p = x;
}
y.p = x.p;
if (x.p == NULL) {
root = y;
} else {
if (x == x.p.left) {
x.p.left = y;
} else {
x.p.right = y;
}
}
y.left = x;
x.p = y;
}
private void rotateRight(Node x) {
Node y = x.left;
x.left = y.right;
if (y.right != NULL) {
y.right.p = x;
}
y.p = x.p;
if (x.p == NULL) {
root = y;
} else {
if (x == x.p.right) {
x.p.right = y;
} else {
x.p.left = y;
}
}
y.right = x;
x.p = y;
}
public void clear() {
NULL.color = BLACK;
NULL.left = NULL.right = NULL.p = NULL;
totalNodes = 0;
removedNodes = 0;
root = NULL;
wasCorrectValueReturned = false;
}
private void enlarge() {
int newLength = Math.max(nodes.length + 1, (int) (nodes.length * ENLARGE_SCALE));
nodes = Arrays.copyOf(nodes, newLength);
}
private Node firstNode() {
Node x = root;
while (x.left != NULL) {
x = x.left;
}
return x;
}
private Node lastNode() {
Node x = root;
while (x.right != NULL) {
x = x.right;
}
return x;
}
public long getFirst() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = firstNode();
wasCorrectValueReturned = true;
return x.key;
}
public long getLast() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = lastNode();
wasCorrectValueReturned = true;
return x.key;
}
public long removeFirst() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = firstNode();
wasCorrectValueReturned = true;
final long removedElement = x.key;
removeNode(x);
return removedElement;
}
public long removeLast() {
if (root == NULL) {
wasCorrectValueReturned = false;
return NULL.key;
}
final Node x = lastNode();
wasCorrectValueReturned = true;
final long removedElement = x.key;
removeNode(x);
return removedElement;
}
public long floor(long element) {
Node x = root;
while (x != NULL) {
if (element > x.key) {
if (x.right != NULL) {
x = x.right;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else if (element < x.key) {
if (x.left != NULL) {
x = x.left;
} else {
Node y = x.p;
while (y != NULL && x == y.left) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
} else {
wasCorrectValueReturned = true;
return x.key;
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public long ceiling(long element) {
Node x = root;
while (x != NULL) {
if (element < x.key) {
if (x.left != NULL) {
x = x.left;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else if (element > x.key) {
if (x.right != NULL) {
x = x.right;
} else {
Node y = x.p;
while (y != NULL && x == y.right) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
} else {
wasCorrectValueReturned = true;
return x.key;
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public long lower(long element) {
Node x = root;
while (x != NULL) {
if (element > x.key) {
if (x.right != NULL) {
x = x.right;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else {
if (x.left != NULL) {
x = x.left;
} else {
Node y = x.p;
while (y != NULL && x == y.left) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public long higher(long element) {
Node x = root;
while (x != NULL) {
if (element < x.key) {
if (x.left != NULL) {
x = x.left;
} else {
wasCorrectValueReturned = true;
return x.key;
}
} else {
if (x.right != NULL) {
x = x.right;
} else {
Node y = x.p;
while (y != NULL && x == y.right) {
//noinspection SuspiciousNameCombination
x = y;
y = y.p;
}
wasCorrectValueReturned = (y != NULL);
return y.key;
}
}
}
wasCorrectValueReturned = false;
return NULL.key;
}
public boolean wasCorrectValueReturned() {
return wasCorrectValueReturned;
}
}
| Java | ["6 7 48\n3 6 2\n5 4 8 3 3 7 9\n4 1 6 8 7 1 1\n1 6 4 6 4 8 6\n7 2 6 1 6 9 4\n1 9 8 6 3 9 2\n4 5 6 8 4 3 7"] | 4.5 seconds | ["4 3 6 7"] | null | Java 6 | standard input | [
"dp",
"constructive algorithms",
"data structures",
"binary search",
"brute force"
] | 667d00cac98b3bd07fc7c78be5373fb5 | The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. | 2,300 | In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. | standard output | |
PASSED | ad23503acf152f847f143259952a454d | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.lang.Comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
private static final int COORD_MOD = 5010;
private static final int MAX_COORD = 5000 + COORD_MOD;
private static Scanner in = new Scanner(System.in);
private static List<Vertical> vert;
private static List<Horizontal> hori;
public static void main(String[] args) {
int n = in.nextInt();
vert = new ArrayList<Vertical>();
hori = new ArrayList<Horizontal>();
for (int i = 0; i < n; i += 1) {
Segment seg = readSegment();
if (seg.isVertical()) {
vert.add(new Vertical(seg));
} else {
hori.add(new Horizontal(seg));
}
}
long res = solve();
System.out.println(res);
}
private static Segment readSegment() {
Segment seg = new Segment();
seg.x1 = in.nextInt() + COORD_MOD;
seg.y1 = in.nextInt() + COORD_MOD;
seg.x2 = in.nextInt() + COORD_MOD;
seg.y2 = in.nextInt() + COORD_MOD;
return seg;
}
private static long solve() {
Collections.sort(vert);
Collections.sort(hori);
long rectangles = 0;
for (int i = 1; i < vert.size(); i += 1) {
final Vertical rightVert = vert.get(i);
Bit bit = makeBit(rightVert);
int marker = hori.size() - 1;
for (int j = i - 1; j >= 0; j -= 1) {
final Vertical leftVert = vert.get(j);
while (marker >= 0 && leftVert.x < hori.get(marker).left) {
if (rightVert.touches(hori.get(marker))) {
bit.add(hori.get(marker).y, -1);
}
marker -= 1;
}
long goodHorizontals = bit.get(leftVert.bottom, leftVert.top);
rectangles += goodHorizontals * (goodHorizontals - 1) / 2;
}
}
return rectangles;
}
private static Bit makeBit(final Vertical v) {
Bit bit = new Bit(MAX_COORD);
for (final Horizontal h : hori) {
if (v.touches(h)) {
bit.add(h.y, 1);
}
}
return bit;
}
}
class Bit {
private long[] bit;
public Bit(int size) {
bit = new long[size + 1];
}
public void add(int pos, final long value) {
while (pos < bit.length) {
bit[pos] += value;
pos += lsb(pos);
}
}
public long get(int left, int right) {
return get(right) - get(left - 1);
}
public long get(int right) {
long sum = 0;
while (right > 0) {
sum += bit[right];
right -= lsb(right);
}
return sum;
}
private static int lsb(int num) {
return num & -num;
}
}
class Vertical implements Comparable<Vertical> {
public int x;
public int top;
public int bottom;
public Vertical(final Segment seg) {
x = seg.x1;
top = Math.max(seg.y1, seg.y2);
bottom = Math.min(seg.y1, seg.y2);
}
public boolean touches(final Horizontal hori) {
return hori.left <= x && x <= hori.right
&& bottom <= hori.y && hori.y <= top;
}
public boolean aboveOrBelow(final Vertical other) {
return x == other.x;
}
@Override
public int compareTo(final Vertical other) {
return x - other.x;
}
}
class Horizontal implements Comparable<Horizontal> {
public int y;
public int left;
public int right;
public Horizontal(final Segment seg) {
y = seg.y1;
left = Math.min(seg.x1, seg.x2);
right = Math.max(seg.x1, seg.x2);
}
@Override
public int compareTo(final Horizontal other) {
if (left != other.left) {
return left - other.left;
}
return right - other.right;
}
}
class Segment {
public int x1, y1;
public int x2, y2;
public boolean isVertical() {
return x1 == x2;
}
} | Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | b705805f3d357595518c39f2e92905d2 | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.util.*;
import java.io.*;
public class E{
static PrintWriter out;
static InputReader in;
public static void main(String args[]){
out = new PrintWriter(System.out);
in = new InputReader();
new E();
out.flush(); out.close();
}
E(){
solve();
}
class pair{
int F, S, T;
pair(int a, int b, int c){
a += add; b += add; c += add;
if(a > b){
a ^= b; b ^= a; a ^= b;
}
F = a; S = b; T = c;
}
}
final int add = 5001;
final int max = 2 * add;
int n;
int f[][] = new int[max][2];
ArrayList<pair> v = new ArrayList<>();
ArrayList<pair> h = new ArrayList<>();
ArrayList<pair> al = new ArrayList<>();
TreeSet<pair> ts = new TreeSet<>((A, B) -> A.S == B.S ? A.T - B.T : A.S - B.S);
void solve(){
n = in.nextInt();
for(int i = 0; i < n; i++){
int x1 = in.nextInt(), y1 = in.nextInt(), x2 = in.nextInt(), y2 = in.nextInt();
if(x1 == x2){
v.add(new pair(y1, y2, x1));
}else{
h.add(new pair(x1, x2, y1));
}
}
Collections.sort(v, (A, B) -> A.T - B.T);
Collections.sort(h, (A, B) -> A.F - B.F);
int y = 0;
for(int i = 0; i < v.size() - 1; i++){
al.clear();
pair p = v.get(i);
for(int j = y; j < h.size(); j++){
pair p1 = h.get(j);
if(p1.F <= p.T){
ts.add(p1);
add(p1.T, 0, 1);
}else{
y = j; break;
}
if(j == h.size() - 1){
y = j + 1;
}
}
for(Iterator it = ts.iterator(); it.hasNext();){
al.add((pair)it.next());
}
for(int j = 0; j < max; j++){
f[j][1] = f[j][0];
}
int x = 0;
for(int j = i + 1; j < v.size(); j++){
pair p1 = v.get(j);
for(int k = x; k < al.size(); k++){
pair p2 = al.get(k);
if(p2.S < p1.T){
add(p2.T, 1, -1);
}else{
x = k; break;
}
if(k == al.size() - 1){
x = k + 1;
}
}
int tot = get(Math.max(p.F, p1.F), Math.min(p.S, p1.S), 1);
ans += (long)tot * (tot - 1) / 2;
}
}
out.println(ans);
}
long ans = 0;
void add(int x, int t, int v){
while(x < max){
f[x][t] += v;
x += x & -x;
}
}
int get(int l, int r, int t){
// System.out.println(l + " " + r);
if(l > r)return 0;
return get(r, t) - get(l - 1, t);
}
int get(int x, int t){
int val = 0;
while(x > 0){
val += f[x][t];
x -= x & -x;
}return val;
}
public static class InputReader{
BufferedReader br;
StringTokenizer st;
InputReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
public String next(){
while(st == null || !st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){}
}
return st.nextToken();
}
}
}
| Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | dc2ba391af7b66701adbc3beaaf7b1e8 | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.util.*;
import java.io.*;
public class EE {
static int o = 5001;
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = scanner.nextInt();
long ans = 0;
ArrayList<HLine> horiz = new ArrayList<>();
ArrayList<VLine> vert = new ArrayList<>();
for(int i = 0; i < N; i++) {
int x1 = scanner.nextInt();
int y1 = scanner.nextInt();
int x2 = scanner.nextInt();
int y2 = scanner.nextInt();
if (x1 == x2) vert.add(new VLine(new P(x1, y1), new P(x2, y2)));
if (y1 == y2) horiz.add(new HLine(new P(x1, y1), new P(x2, y2)));
}
Collections.sort(vert, (a,b)->Integer.compare(a.p.x, b.p.x));
BIT bit = new BIT(10005);
for(int i =0; i < vert.size(); i++) {
ArrayList<P> inters = new ArrayList<>();
VLine cur = vert.get(i);
HLine h = null;
for(int j = 0; j < horiz.size(); j++) {
h = horiz.get(j);
if (inters(cur.p.x, h)) {
inters.add(new P(h.q.x, h.p.y));
bit.update(h.p.y + o, 1);
}
}
Collections.sort(inters, (a,b)->Integer.compare(a.x, b.x));
int ind = 0;
for(int j = i + 1; j < vert.size() && ind < inters.size(); j++) {
VLine v = vert.get(j);
while(ind < inters.size() && v.p.x > inters.get(ind).x) {
bit.update(inters.get(ind).y + o, -1);
ind++;
}
int l = Math.max(cur.p.y, v.p.y); int r = Math.min(cur.q.y, v.q.y);
long ret = bit.rangeSum(l + o, r + o);
ans += (ret * (ret -1))/2;
}
while(ind < inters.size()) bit.update(inters.get(ind++).y + o, -1);
}
out.println(ans);
out.flush();
}
static boolean inters(int v, HLine h) {
return h.p.x <= v && h.q.x >= v;
}
public static class P {
final int x, y;
public P(int xx, int yy) { x = xx; y = yy; }
}
public static class VLine {
P p, q;
public VLine(P pp, P qq) {
p = pp.y < qq.y ? pp : qq;
q = pp.y < qq.y ? qq : pp;
}
}
public static class HLine {
P p, q;
public HLine(P pp, P qq) {
p = pp.x < qq.x ? pp : qq;
q = pp.x < qq.x ? qq : pp;
}
}
public static class BIT {
long[] table;
int sz;
public BIT(int ss) {
sz= ss;
table = new long[ss];
}
void update(int loc, long amt) {
while(loc < sz) {
table[loc] += amt;
loc += Integer.lowestOneBit(loc);
}
}
long pref(int loc) {
long ret = 0;
while(loc > 0) {
ret += table[loc];
loc-= Integer.lowestOneBit(loc);
}
return ret;
}
long rangeSum(int l, int r) {
if (l > r) return 0;
return pref(r) - pref(l-1);
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
}
}
| Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | 420a7973f86b86c08d6f1aecdef1cc5f | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class E {
public static class FixedBitSet extends BitSet {
private final long[] bits; // Array of longs holding the bits
private final int numBits; // The number of bits in use
private final int numWords; // The exact number of longs needed to hold numBits (<= bits.length)
public FixedBitSet(int numBits) {
this.numBits = numBits;
bits = new long[bits2words(numBits)];
numWords = bits.length;
}
public static int bits2words(int numBits) {
return ((numBits - 1) >> 6) + 1; // I.e.: get the word-offset of the last bit and add one (make sure to use >> so 0 returns 0!)
}
public void set(int index) {
assert index >= 0 && index < numBits: "index=" + index + ", numBits=" + numBits;
int wordNum = index >> 6; // div 64
long bitmask = 1L << index;
bits[wordNum] |= bitmask;
}
public static long intersectionCount(FixedBitSet a, FixedBitSet b) {
// Depends on the ghost bits being clear!
return pop_intersect(a.bits, b.bits, 0, Math.min(a.numWords, b.numWords));
}
public static long pop_intersect(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] & arr2[i]);
}
return popCount;
}
}
public long choose(long n) {
if(n < 2)
return 0;
return (n * (n - 1)) / 2;
}
public void realMain() throws Exception {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in), 1000000);
String in = fin.readLine();
String[] ar = in.split(" ");
int n = Integer.parseInt(ar[0]);
ArrayList<Integer> horizx1 = new ArrayList<Integer>();
ArrayList<Integer> horizy1 = new ArrayList<Integer>();
ArrayList<Integer> vertx1 = new ArrayList<Integer>();
ArrayList<Integer> verty1 = new ArrayList<Integer>();
ArrayList<Integer> horizx2 = new ArrayList<Integer>();
ArrayList<Integer> horizy2 = new ArrayList<Integer>();
ArrayList<Integer> vertx2 = new ArrayList<Integer>();
ArrayList<Integer> verty2 = new ArrayList<Integer>();
for(int i = 0; i < n; i++) {
in = fin.readLine();
ar = in.split(" ");
int x1 = Integer.parseInt(ar[0]);
int y1 = Integer.parseInt(ar[1]);
int x2 = Integer.parseInt(ar[2]);
int y2 = Integer.parseInt(ar[3]);
if(y1 == y2) {
horizx1.add(x1);
horizy1.add(y1);
horizx2.add(x2);
horizy2.add(y2);
} else {
vertx1.add(x1);
verty1.add(y1);
vertx2.add(x2);
verty2.add(y2);
}
}
int nhoriz = horizx1.size();
int nvert = vertx1.size();
ArrayList<FixedBitSet> intersects = new ArrayList<FixedBitSet>();
for(int i = 0; i < nhoriz; i++) {
FixedBitSet bs = new FixedBitSet(nvert);
intersects.add(bs);
}
for(int i = 0; i < nhoriz; i++) {
for(int j = 0; j < nvert; j++) {
boolean x1 = false, x2 = false, y1 = false, y2 = false;
if(horizx1.get(i) <= vertx1.get(j) && horizx2.get(i) >= vertx1.get(j)) {
x1 = true;
}
if(horizx1.get(i) >= vertx1.get(j) && horizx2.get(i) <= vertx1.get(j)) {
x2 = true;
}
if(verty1.get(j) <= horizy1.get(i) && verty2.get(j) >= horizy1.get(i)) {
y1 = true;
}
if(verty1.get(j) >= horizy1.get(i) && verty2.get(j) <= horizy1.get(i)) {
y2 = true;
}
if((x1 || x2) && (y1 || y2)) {
/* System.out.println("intersect");
System.out.println(horizx1.get(i));
System.out.println(horizy1.get(i));
System.out.println(horizx2.get(i));
System.out.println(horizy2.get(i));
System.out.println(vertx1.get(j));
System.out.println(verty1.get(j));
System.out.println(vertx2.get(j));
System.out.println(verty2.get(j));*/
intersects.get(i).set(j);
}
}
}
/* for(int i = 0; i < nhoriz; i++) {
System.out.println(intersects.get(i));
}
*/
long ret = 0;
int card2500count = 0;
for(int i = 0; i < nhoriz; i++) {
for(int j = i + 1; j < nhoriz; j++) {
ret += choose( FixedBitSet.intersectionCount(intersects.get(i), intersects.get(j)));
//if(bs.cardinality() == 2500) {
// card2500count++;
//}
}
}
//System.out.println(card2500count);
System.out.println(ret);
/*BigInteger res = BigInteger.ZERO;
for(long i = 0; i < 2499; i++) {
res = res.add(new BigInteger("" + ((i * i + i) / 2)));
}
res = res.multiply(new BigInteger("2500"));
System.out.println(res);
*/
}
public static void main(String[] args) throws Exception {
E e = new E();
e.realMain();
}
} | Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | a14d7313328cafd407af05863b13dc77 | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.function.Function;
public class MainE {
static int N;
static List<Segment> H;
static List<Segment> V;
public static void main(String[] args) {
FastScanner sc = new FastScanner(System.in);
N = sc.nextInt();
H = new ArrayList<>();
V = new ArrayList<>();
for (int i = 0; i < N; i++) {
int x1 = sc.nextInt() + 5000;
int y1 = sc.nextInt() + 5000;
int x2 = sc.nextInt() + 5000;
int y2 = sc.nextInt() + 5000;
if( x1 == x2 ) {
V.add( new Segment(x1, Math.min(y1, y2), Math.max(y1, y2)));
} else {
H.add( new Segment(y1, Math.min(x1, x2), Math.max(x1, x2)));
}
}
System.out.println(solve());
}
static long solve() {
// バケツ
List<Segment>[] HB = new List[10005];
List<Segment>[] VB = new List[10005];
ArrayDeque<Segment>[] EB = new ArrayDeque[10005];
for (int i = 0; i < 10005; i++) {
HB[i] = new ArrayList<>();
VB[i] = new ArrayList<>();
EB[i] = new ArrayDeque<>();
}
for (Segment v : V) {
VB[v.n].add(v);
}
for (Segment h : H) {
HB[h.n].add(h);
}
FenwickTree bit = new FenwickTree(10005, FenwickTree.SUM);
long ret = 0;
for (int i = 0; i < H.size(); i++) {
Arrays.fill(bit.bit, 0);
// これを底面とした四角形を数える
Segment h = H.get(i);
int hy = h.n;
// 交差している縦を探す
for (int x = h.lo; x <= h.hi; x++) {
for (int j = 0; j < VB[x].size(); j++) {
Segment v = VB[x].get(j);
int y1 = v.lo;
int y2 = v.hi;
if( y1 <= hy && hy < y2 ) {
bit.add(x, 1);
EB[y2].add(v);
}
}
}
// イベントソートの要領で良い感じに数える
for (int y = hy+1; y < 10005; y++) {
for (int j = 0; j < HB[y].size(); j++) {
Segment h2 = HB[y].get(j);
long cnt = bit.query(h2.lo, h2.hi+1);
ret += cnt * (cnt-1) / 2; // comb(cnt, 2)
}
ArrayDeque<Segment> q = EB[y];
while(!q.isEmpty()) {
Segment v = q.poll();
bit.add(v.n, -1);
}
}
}
return ret;
}
static class Segment {
int n;
int lo, hi;
public Segment(int n, int lo, int hi) {
this.n = n;
this.lo = lo;
this.hi = hi;
}
}
static class FenwickTree {
interface Monoid {
long identity();
long apply(long a, long b);
long inverse(long a);
}
static Monoid SUM = new Monoid() {
public long identity() { return 0; }
public long apply(long a, long b) { return a+b; }
public long inverse(long a) { return -a; }
};
static Monoid MAX = new Monoid() {
public long identity() { return 0; }
public long apply(long a, long b) { return Math.max(a, b); }
public long inverse(long a) { throw new RuntimeException("no inverse"); }
};
int size;
long[] bit;
Monoid m;
long identity;
FenwickTree(int size, Monoid m) {
this.size = 1;
while( this.size < size ) this.size *= 2;
this.bit = new long[this.size+1];
this.identity = m.identity();
if( this.identity != 0 ) {
Arrays.fill(this.bit, this.identity);
}
this.m = m;
}
void add(int i, long v) {
i++; // 0 index -> 1 index
while( i <= size ) {
bit[i] = m.apply(bit[i], v);
i += i & -i;
}
}
// [0, r)
long query(int r) {
// 0 index -> 1 index -> -1
long ret = identity;
while(r > 0) {
ret = m.apply(ret, bit[r]);
r -= r & -r;
}
return ret;
}
long query(int l, int r) {
return query(r) + m.inverse(query(l));
}
int lowerBound(int v) {
if( bit[size] < v ) return size;
int x = 0;
for (int k = size/2; k > 0; k /= 2 ) {
if( bit[x + k] < v ) {
v -= bit[x+k];
x += k;
}
}
return x;
}
}
@SuppressWarnings("unused")
static class FastScanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
long nextLong() {
return Long.parseLong(next());
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[] nextIntArray(int n, int delta) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt() + delta;
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
static <A> void writeLines(A[] as, Function<A, String> f) {
PrintWriter pw = new PrintWriter(System.out);
for (A a : as) {
pw.println(f.apply(a));
}
pw.flush();
}
static void writeLines(int[] as) {
PrintWriter pw = new PrintWriter(System.out);
for (int a : as) pw.println(a);
pw.flush();
}
static void writeLines(long[] as) {
PrintWriter pw = new PrintWriter(System.out);
for (long a : as) pw.println(a);
pw.flush();
}
static int max(int... as) {
int max = Integer.MIN_VALUE;
for (int a : as) max = Math.max(a, max);
return max;
}
static int min(int... as) {
int min = Integer.MAX_VALUE;
for (int a : as) min = Math.min(a, min);
return min;
}
static void debug(Object... args) {
StringJoiner j = new StringJoiner(" ");
for (Object arg : args) {
if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg));
else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg));
else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg));
else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg));
else j.add(arg.toString());
}
System.err.println(j.toString());
}
}
| Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | bd5d1aaf44e256d23ad21b8fe8eccb02 | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.function.Function;
public class MainE {
static int N;
static List<Segment> H;
static List<Segment> V;
public static void main(String[] args) {
FastScanner sc = new FastScanner(System.in);
N = sc.nextInt();
H = new ArrayList<>();
V = new ArrayList<>();
for (int i = 0; i < N; i++) {
int x1 = sc.nextInt() + 5000;
int y1 = sc.nextInt() + 5000;
int x2 = sc.nextInt() + 5000;
int y2 = sc.nextInt() + 5000;
if( x1 == x2 ) {
V.add( new Segment(x1, Math.min(y1, y2), Math.max(y1, y2)));
} else {
H.add( new Segment(y1, Math.min(x1, x2), Math.max(x1, x2)));
}
}
System.out.println(solve());
}
static long solve() {
// バケツ
List<Segment>[] HB = new List[10005];
List<Segment>[] VB = new List[10005];
ArrayDeque<Segment>[] EB = new ArrayDeque[10005];
for (int i = 0; i < 10005; i++) {
HB[i] = new ArrayList<>();
VB[i] = new ArrayList<>();
EB[i] = new ArrayDeque<>();
}
for (Segment v : V) {
VB[v.n].add(v);
}
for (Segment h : H) {
HB[h.n].add(h);
}
FenwickTree bit = new FenwickTree(10005, FenwickTree.SUM);
long ret = 0;
for (int i = 0; i < H.size(); i++) {
Arrays.fill(bit.bit, 0);
// これを底面とした四角形を数える
Segment h = H.get(i);
int hy = h.n;
// 交差している縦を探す
for (int x = h.lo; x <= h.hi; x++) {
for (int j = 0; j < VB[x].size(); j++) {
Segment v = VB[x].get(j);
int y1 = v.lo;
int y2 = v.hi;
if( y1 <= hy && hy < y2 ) {
bit.add(x, 1);
EB[y2].add(v);
}
}
}
// イベントソートの要領で良い感じに数える
for (int y = hy+1; y < 10005; y++) {
for (Segment h2 : HB[y]) {
long cnt = bit.query(h2.lo, h2.hi+1);
ret += cnt * (cnt-1) / 2; // comb(cnt, 2)
}
ArrayDeque<Segment> q = EB[y];
while(!q.isEmpty()) {
Segment v = q.poll();
bit.add(v.n, -1);
}
}
}
return ret;
}
static class Segment {
int n;
int lo, hi;
public Segment(int n, int lo, int hi) {
this.n = n;
this.lo = lo;
this.hi = hi;
}
}
static class FenwickTree {
interface Monoid {
long identity();
long apply(long a, long b);
long inverse(long a);
}
static Monoid SUM = new Monoid() {
public long identity() { return 0; }
public long apply(long a, long b) { return a+b; }
public long inverse(long a) { return -a; }
};
static Monoid MAX = new Monoid() {
public long identity() { return 0; }
public long apply(long a, long b) { return Math.max(a, b); }
public long inverse(long a) { throw new RuntimeException("no inverse"); }
};
int size;
long[] bit;
Monoid m;
long identity;
FenwickTree(int size, Monoid m) {
this.size = 1;
while( this.size < size ) this.size *= 2;
this.bit = new long[this.size+1];
this.identity = m.identity();
if( this.identity != 0 ) {
Arrays.fill(this.bit, this.identity);
}
this.m = m;
}
void add(int i, long v) {
i++; // 0 index -> 1 index
while( i <= size ) {
bit[i] = m.apply(bit[i], v);
i += i & -i;
}
}
// [0, r)
long query(int r) {
// 0 index -> 1 index -> -1
long ret = identity;
while(r > 0) {
ret = m.apply(ret, bit[r]);
r -= r & -r;
}
return ret;
}
long query(int l, int r) {
return query(r) + m.inverse(query(l));
}
int lowerBound(int v) {
if( bit[size] < v ) return size;
int x = 0;
for (int k = size/2; k > 0; k /= 2 ) {
if( bit[x + k] < v ) {
v -= bit[x+k];
x += k;
}
}
return x;
}
}
@SuppressWarnings("unused")
static class FastScanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
long nextLong() {
return Long.parseLong(next());
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[] nextIntArray(int n, int delta) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt() + delta;
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
static <A> void writeLines(A[] as, Function<A, String> f) {
PrintWriter pw = new PrintWriter(System.out);
for (A a : as) {
pw.println(f.apply(a));
}
pw.flush();
}
static void writeLines(int[] as) {
PrintWriter pw = new PrintWriter(System.out);
for (int a : as) pw.println(a);
pw.flush();
}
static void writeLines(long[] as) {
PrintWriter pw = new PrintWriter(System.out);
for (long a : as) pw.println(a);
pw.flush();
}
static int max(int... as) {
int max = Integer.MIN_VALUE;
for (int a : as) max = Math.max(a, max);
return max;
}
static int min(int... as) {
int min = Integer.MAX_VALUE;
for (int a : as) min = Math.min(a, min);
return min;
}
static void debug(Object... args) {
StringJoiner j = new StringJoiner(" ");
for (Object arg : args) {
if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg));
else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg));
else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg));
else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg));
else j.add(arg.toString());
}
System.err.println(j.toString());
}
}
| Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | ae9792001aec530c5a47a518f8384a63 | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author cunbidun
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
ECountTheRectangles solver = new ECountTheRectangles();
solver.solve(1, in, out);
out.close();
}
static class ECountTheRectangles {
private InputReader in;
private OutputWriter out;
public void solve(int testNumber, InputReader in, OutputWriter out) {
this.in = in;
this.out = out;
int n = in.nextInt();
ArrayList<TripIII> v = new ArrayList<>();
ArrayList<TripIII> h = new ArrayList<>();
for (int i = 1; i <= n; i++) {
int x1 = in.nextInt();
int y1 = in.nextInt();
int x2 = in.nextInt();
int y2 = in.nextInt();
if (x1 > x2) {
int tmp = x2;
x2 = x1;
x1 = tmp;
}
if (y1 > y2) {
int tmp = y2;
y2 = y1;
y1 = tmp;
}
if (y1 == y2) {
h.add(new TripIII(y1, x1, x2));
} else {
v.add(new TripIII(x1, y1, y2));
}
}
if (v.size() > h.size()) {
ArrayList<TripIII> tmp = new ArrayList<>(v);
v = new ArrayList<>(h);
h.clear();
h = new ArrayList<>(tmp);
}
ImmutableBitSet[] bit = new ImmutableBitSet[v.size()];
for (int i = 0; i < v.size(); i++) {
bit[i] = new ImmutableBitSet(h.size());
for (int j = 0; j < h.size(); j++) {
if (intersect(v.get(i), h.get(j))) bit[i].set(j);
}
}
long ans = 0;
for (int i = 0; i < v.size(); i++) {
for (int j = i + 1; j < v.size(); j++) {
long res = bit[i].count(bit[j]);
ans += res * (res - 1) / 2;
}
}
out.println(ans);
// ImmutableBitSet t = new ImmutableBitSet(64);
// for (int i = 0; i <= 63; i++) {
// t.set(i);
// }
// out.println(Long.toString(Long.parseUnsignedLong("9223372036854775807"), 2));
}
private boolean intersect(TripIII a, TripIII b) {
return a.first <= b.third && a.first >= b.second && b.first >= a.second && b.first <= a.third;
}
}
static class ImmutableBitSet {
private long[] array;
private int size;
public ImmutableBitSet(int size) {
this.size = (size + 63) / 64;
array = new long[this.size];
}
public int count(ImmutableBitSet that) {
int ans = 0;
for (int i = 0; i < size; ++i)
ans += Long.bitCount(this.getIndex(i) & that.getIndex(i));
return ans;
}
public void set(int i) {
int j = i >> 6;
array[j] |= 1L << (i - (j << 6));
}
private long getIndex(int i) {
return array[i];
}
}
static class InputReader extends InputStream {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class OutputWriter {
private final PrintWriter out;
public OutputWriter(OutputStream outputStream) {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.out = new PrintWriter(writer);
}
public void close() {
out.close();
}
public void println(long i) {
out.println(i);
}
}
static class TripIII implements Comparable<TripIII> {
public int first;
public int second;
public int third;
public TripIII(int first, int second, int third) {
this.first = first;
this.second = second;
this.third = third;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TripIII trip = (TripIII) o;
return first == trip.first && second == trip.second && third == trip.third;
}
public String toString() {
return "(" + first + "," + second + "," + third + ")";
}
public int compareTo(TripIII o) {
int value = Integer.compare(first, o.first);
if (value != 0) {
return value;
}
value = Integer.compare(second, o.second);
if (value != 0) {
return value;
}
return Integer.compare(third, o.third);
}
}
}
| Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | c16bb692e00b303dcef72a92e6add781 | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author cunbidun
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
ECountTheRectangles solver = new ECountTheRectangles();
solver.solve(1, in, out);
out.close();
}
static class ECountTheRectangles {
private InputReader in;
private OutputWriter out;
public void solve(int testNumber, InputReader in, OutputWriter out) {
this.in = in;
this.out = out;
int n = in.nextInt();
ArrayList<TripIII> v = new ArrayList<>();
ArrayList<TripIII> h = new ArrayList<>();
for (int i = 1; i <= n; i++) {
int x1 = in.nextInt();
int y1 = in.nextInt();
int x2 = in.nextInt();
int y2 = in.nextInt();
if (x1 > x2) {
int tmp = x2;
x2 = x1;
x1 = tmp;
}
if (y1 > y2) {
int tmp = y2;
y2 = y1;
y1 = tmp;
}
if (y1 == y2) {
h.add(new TripIII(y1, x1, x2));
} else {
v.add(new TripIII(x1, y1, y2));
}
}
if (v.size() > h.size()) {
ArrayList<TripIII> tmp = new ArrayList<>(v);
v = new ArrayList<>(h);
h.clear();
h = new ArrayList<>(tmp);
}
BitSet[] bit = new BitSet[v.size()];
for (int i = 0; i < v.size(); i++) {
bit[i] = new BitSet(h.size());
for (int j = 0; j < h.size(); j++) {
if (intersect(v.get(i), h.get(j))) bit[i].turnOn(j);
}
}
long ans = 0;
for (int i = 0; i < v.size(); i++) {
for (int j = i + 1; j < v.size(); j++) {
long res = bit[i].countAnd(bit[j]);
ans += res * (res - 1) / 2;
}
}
out.println(ans);
}
private boolean intersect(TripIII a, TripIII b) {
return a.first <= b.third && a.first >= b.second && b.first >= a.second && b.first <= a.third;
}
}
static class InputReader extends InputStream {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class OutputWriter {
private final PrintWriter out;
public OutputWriter(OutputStream outputStream) {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.out = new PrintWriter(writer);
}
public void close() {
out.close();
}
public void println(long i) {
out.println(i);
}
}
static class TripIII implements Comparable<TripIII> {
public int first;
public int second;
public int third;
public TripIII(int first, int second, int third) {
this.first = first;
this.second = second;
this.third = third;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TripIII trip = (TripIII) o;
return first == trip.first && second == trip.second && third == trip.third;
}
public String toString() {
return "(" + first + "," + second + "," + third + ")";
}
public int compareTo(TripIII o) {
int value = Integer.compare(first, o.first);
if (value != 0) {
return value;
}
value = Integer.compare(second, o.second);
if (value != 0) {
return value;
}
return Integer.compare(third, o.third);
}
}
static class BitSet {
private long[] array;
private int size;
public BitSet(int size) {
this.size = (size + 63) / 64;
array = new long[this.size];
}
private BitSet(long[] array) {
this.size = (array.length + 63) / 64;
this.array = array;
}
public void turnOn(int i) {
int j = i >> 6;
array[j] |= 1L << (i - (j << 6));
}
public int countAnd(BitSet that) {
int ans = 0;
for (int i = 0; i < size; ++i)
ans += Long.bitCount(this.array[i] & that.array[i]);
return ans;
}
}
}
| Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | a43e077eb65a6da8b58f71f6400620a3 | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
static int N=5001;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
line[]lines=new line[n];
ArrayList<line>hor=new ArrayList(),ver=new ArrayList();
for(int i=0;i<n;i++) {
lines[i]=new line(sc,i);
if(lines[i].hor)
hor.add(lines[i]);
else
ver.add(lines[i]);
}
long ans=0;
Collections.sort(hor,(x,y)->y.y1-x.y1);
FenwickTree tree=new FenwickTree(2*N+5);
PriorityQueue<Integer>pq=new PriorityQueue<Integer>((x,y)->lines[y].y1-lines[x].y1);
for(int topLine=0;topLine+1<hor.size();topLine++) {
pq.clear();
Arrays.fill(tree.bit,0);
line top=hor.get(topLine);
for(line line:ver) {
if(line.y2>=top.y1) {
pq.add(line.idx);
tree.update(lines[line.idx].x1, 1);
}
}
for(int bott=topLine+1;bott<hor.size();bott++) {
line bottom=hor.get(bott);
if(bottom.y1==top.y1)
continue;
int leftX=Math.max(top.x1, bottom.x1),rightX=Math.min(top.x2, bottom.x2);
while(!pq.isEmpty()) {
int idx=pq.peek();
if(lines[idx].y1>bottom.y1) {
pq.poll();
tree.update(lines[idx].x1, -1);
}
else
break;
}
long cand=tree.query(leftX, rightX);
ans+=cand*(cand-1)/2;
}
}
out.println(ans);
out.close();
}
static class FenwickTree {
int[] bit;
FenwickTree(int n) {
bit = new int[n + 1];
}
void update(int idx, long v) {
while (idx < bit.length) {
bit[idx] += v;
idx += (idx & -idx);
}
}
int query(int idx) {
int ans = 0;
while (idx > 0) {
ans += bit[idx];
idx -= (idx & -idx);
}
return ans;
}
int query(int l, int r) {
if(l>r)
return 0;
return query(r) - query(l - 1);
}
}
static class line{
int x1,y1,x2,y2,idx;
boolean hor;
line(Scanner sc,int i) throws IOException{
x1=sc.nextInt()+N;
y1=sc.nextInt()+N;
x2=sc.nextInt()+N;
y2=sc.nextInt()+N;
if(y1==y2) {
hor=true;
if(x1>x2) {
int tmp=x1;
x1=x2;
x2=tmp;
}
}
else if(y1>y2) {
int tmp=y1;
y1=y2;
y2=tmp;
}
idx=i;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | 18613270f26cd627a61a9038e0c19005 | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
static int N=5001;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
line[]lines=new line[n];
ArrayList<line>hor=new ArrayList(),ver=new ArrayList();
for(int i=0;i<n;i++) {
lines[i]=new line(sc,i);
if(lines[i].hor)
hor.add(lines[i]);
else
ver.add(lines[i]);
}
long ans=0;
Collections.sort(hor,(x,y)->y.y1-x.y1);
FenwickTree tree=new FenwickTree(2*N+5);
PriorityQueue<Integer>pq=new PriorityQueue<Integer>((x,y)->lines[y].y1-lines[x].y1);
for(int topLine=0;topLine+1<hor.size();topLine++) {
while(!pq.isEmpty()) {
int idx=pq.poll();
tree.update(lines[idx].x1, -1);
}
line top=hor.get(topLine);
for(line line:ver) {
if(line.y2>=top.y1) {
pq.add(line.idx);
tree.update(lines[line.idx].x1, 1);
}
}
for(int bott=topLine+1;bott<hor.size();bott++) {
line bottom=hor.get(bott);
if(bottom.y1==top.y1)
continue;
int leftX=Math.max(top.x1, bottom.x1),rightX=Math.min(top.x2, bottom.x2);
while(!pq.isEmpty()) {
int idx=pq.peek();
if(lines[idx].y1>bottom.y1) {
pq.poll();
tree.update(lines[idx].x1, -1);
}
else
break;
}
long cand=tree.query(leftX, rightX);
ans+=cand*(cand-1)/2;
}
}
out.println(ans);
out.close();
}
static class FenwickTree {
int[] bit;
FenwickTree(int n) {
bit = new int[n + 1];
}
void update(int idx, long v) {
while (idx < bit.length) {
bit[idx] += v;
idx += (idx & -idx);
}
}
int query(int idx) {
int ans = 0;
while (idx > 0) {
ans += bit[idx];
idx -= (idx & -idx);
}
return ans;
}
int query(int l, int r) {
if(l>r)
return 0;
return query(r) - query(l - 1);
}
}
static class line{
int x1,y1,x2,y2,idx;
boolean hor;
line(Scanner sc,int i) throws IOException{
x1=sc.nextInt()+N;
y1=sc.nextInt()+N;
x2=sc.nextInt()+N;
y2=sc.nextInt()+N;
if(y1==y2) {
hor=true;
if(x1>x2) {
int tmp=x1;
x1=x2;
x2=tmp;
}
}
else if(y1>y2) {
int tmp=y1;
y1=y2;
y2=tmp;
}
idx=i;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | fb0c6f995553c78aae2b3b7c0c415e52 | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes |
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.*;
public class CFContest {
public static void main(String[] args) throws Exception {
boolean local = System.getProperty("ONLINE_JUDGE") == null;
boolean async = false;
Charset charset = Charset.forName("ascii");
FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset);
Task task = new Task(io, new Debug(local));
if (async) {
Thread t = new Thread(null, task, "dalt", 1 << 27);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
t.join();
} else {
task.run();
}
if (local) {
io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M");
}
io.flush();
}
public static class Task implements Runnable {
final FastIO io;
final Debug debug;
int inf = (int) 1e8;
public Task(FastIO io, Debug debug) {
this.io = io;
this.debug = debug;
}
@Override
public void run() {
solve();
}
int limit = 5000;
public void solve() {
int n = io.readInt();
List<Line> v = new ArrayList<>();
List<Line> h = new ArrayList<>();
for (int i = 0; i < n; i++) {
int x1 = io.readInt() + limit + 1;
int y1 = io.readInt() + limit + 1;
int x2 = io.readInt() + limit + 1;
int y2 = io.readInt() + limit + 1;
if (x1 > x2) {
int tmp = x1;
x1 = x2;
x2 = tmp;
}
if (y1 > y2) {
int tmp = y1;
y1 = y2;
y2 = tmp;
}
if (x1 == x2) {
Line line = new Line();
line.a = y1;
line.b = y2;
line.c = x1;
v.add(line);
} else {
Line line = new Line();
line.a = x1;
line.b = x2;
line.c = y1;
h.add(line);
}
}
if (v.size() > h.size()) {
List<Line> tmp = v;
v = h;
h = tmp;
}
int x = v.size();
int y = h.size();
BIT[] bits = new BIT[x];
for (int i = 0; i < x; i++) {
bits[i] = new BIT(limit * 2 + 1);
}
Line[] hSortByB = h.toArray(new Line[0]);
Arrays.sort(hSortByB, (a, b) -> a.b - b.b);
int hSortByBPos = 0;
Line[] vArray = v.toArray(new Line[0]);
Arrays.sort(vArray, (a, b) -> a.c - b.c);
for (int j = 0; j < y; j++) {
for (int i = 0; i < x; i++) {
if (intersect(vArray[i], hSortByB[j])) {
bits[i].update(hSortByB[j].c, 1);
}
}
}
long total = 0;
for (int i = 0; i < x; i++) {
Line l = vArray[i];
while (hSortByBPos < y && hSortByB[hSortByBPos].b < l.c) {
for (int j = 0; j < i; j++) {
if (intersect(hSortByB[hSortByBPos], vArray[j])) {
bits[j].update(hSortByB[hSortByBPos].c, -1);
}
}
hSortByBPos++;
}
for (int j = 0; j < i; j++) {
total += choose2(bits[j].query(l.b) - bits[j].query(l.a - 1));
}
}
io.cache.append(total);
}
public boolean intersect(Line a, Line b) {
return a.c >= b.a && a.c <= b.b
&& b.c >= a.a && b.c <= a.b;
}
public long choose2(long n) {
return n * (n - 1) / 2;
}
}
public static class Line {
int a;
int b;
int c;
}
/**
* Created by dalt on 2018/5/20.
*/
public static class BIT {
private short[] data;
private int n;
/**
* 创建大小A[1...n]
*/
public BIT(int n) {
this.n = n;
data = new short[n + 1];
}
/**
* 查询A[1]+A[2]+...+A[i]
*/
public int query(int i) {
int sum = 0;
for (; i > 0; i -= i & -i) {
sum += data[i];
}
return sum;
}
/**
* 将A[i]更新为A[i]+mod
*/
public void update(int i, int mod) {
for (; i <= n; i += i & -i) {
data[i] += mod;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= n; i++) {
builder.append(query(i) - query(i - 1)).append(' ');
}
return builder.toString();
}
}
public static class Randomized {
static Random random = new Random();
public static double nextDouble(double min, double max) {
return random.nextDouble() * (max - min) + min;
}
public static void randomizedArray(int[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
int tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static void randomizedArray(long[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
long tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static void randomizedArray(double[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
double tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static void randomizedArray(float[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
float tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static <T> void randomizedArray(T[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
T tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static int nextInt(int l, int r) {
return random.nextInt(r - l + 1) + l;
}
}
/**
* 模运算
*/
public static class Modular {
int m;
public Modular(int m) {
this.m = m;
}
public int valueOf(int x) {
x %= m;
if (x < 0) {
x += m;
}
return x;
}
public int valueOf(long x) {
x %= m;
if (x < 0) {
x += m;
}
return (int) x;
}
public int mul(int x, int y) {
return valueOf((long) x * y);
}
public int plus(int x, int y) {
return valueOf(x + y);
}
@Override
public String toString() {
return "mod " + m;
}
}
public static class BitOperator {
public int bitAt(int x, int i) {
return (x >> i) & 1;
}
public int bitAt(long x, int i) {
return (int) ((x >> i) & 1);
}
public int setBit(int x, int i, boolean v) {
if (v) {
x |= 1 << i;
} else {
x &= ~(1 << i);
}
return x;
}
public long setBit(long x, int i, boolean v) {
if (v) {
x |= 1L << i;
} else {
x &= ~(1L << i);
}
return x;
}
/**
* Determine whether x is subset of y
*/
public boolean subset(long x, long y) {
return intersect(x, y) == x;
}
/**
* Merge two set
*/
public long merge(long x, long y) {
return x | y;
}
public long intersect(long x, long y) {
return x & y;
}
public long differ(long x, long y) {
return x - intersect(x, y);
}
}
public static class FastIO {
public final StringBuilder cache = new StringBuilder();
private final InputStream is;
private final OutputStream os;
private final Charset charset;
private StringBuilder defaultStringBuf = new StringBuilder(1 << 8);
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastIO(InputStream is, OutputStream os, Charset charset) {
this.is = is;
this.os = os;
this.charset = charset;
}
public FastIO(InputStream is, OutputStream os) {
this(is, os, Charset.forName("ascii"));
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public long readLong() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
long val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public double readDouble() {
boolean sign = true;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+';
next = read();
}
long val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
if (next != '.') {
return sign ? val : -val;
}
next = read();
long radix = 1;
long point = 0;
while (next >= '0' && next <= '9') {
point = point * 10 + next - '0';
radix = radix * 10;
next = read();
}
double result = val + (double) point / radix;
return sign ? result : -result;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
public int readLine(char[] data, int offset) {
int originalOffset = offset;
while (next != -1 && next != '\n') {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(char[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(byte[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (byte) next;
next = read();
}
return offset - originalOffset;
}
public char readChar() {
skipBlank();
char c = (char) next;
next = read();
return c;
}
public void flush() {
try {
os.write(cache.toString().getBytes(charset));
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasMore() {
skipBlank();
return next != -1;
}
}
public static class Debug {
private boolean allowDebug;
public Debug(boolean allowDebug) {
this.allowDebug = allowDebug;
}
public void assertTrue(boolean flag) {
if (!allowDebug) {
return;
}
if (!flag) {
fail();
}
}
public void fail() {
throw new RuntimeException();
}
public void assertFalse(boolean flag) {
if (!allowDebug) {
return;
}
if (flag) {
fail();
}
}
private void outputName(String name) {
System.out.print(name + " = ");
}
public void debug(String name, int x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, long x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, double x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, int[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, long[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, double[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, Object x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, Object... x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.deepToString(x));
}
}
} | Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | df80495260c2177e63e43028dc36d251 | train_000.jsonl | 1563115500 | There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class countTheRectangles {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int[][] data=new int[n][4];
int hct=0;
for(int i=0;i<n;i++) {
for(int j=0;j<4;j++) {
data[i][j]=scan.nextInt();
}
if(data[i][0]>data[i][2]) {
int temp=data[i][0];
data[i][0]=data[i][2];
data[i][2]=temp;
}
if(data[i][1]>data[i][3]) {
int temp=data[i][1];
data[i][1]=data[i][3];
data[i][3]=temp;
}
if(data[i][1]==data[i][3]) hct++;
}
horiz[] h=new horiz[hct];
for(int i=0;i<n;i++) {
if(data[i][1]==data[i][3]) h[--hct]=new horiz(data[i][0],data[i][2],data[i][1]);
}
Arrays.sort(h);
final int OFFSET=5001;
ArrayList<event> a=new ArrayList<>();
for(int i=0;i<n;i++) {
if(data[i][0]==data[i][2]) {
event e1=new event(data[i][0],data[i][0],data[i][1],1);
event e2=new event(data[i][0],data[i][0],data[i][3],2);
a.add(e1);
a.add(e2);
e2.below=e1;
}
else {
a.add(new event(data[i][0],data[i][2],data[i][1],3));
}
}
Collections.sort(a);
long res=0L;
for(int i=0;i<h.length;i++) {
bit b=new bit(100000);
for(int j=0;j<a.size();j++) {
event e=a.get(j);
if(e.type==1) {
if(e.x1>=h[i].x1&&e.x1<=h[i].x2&&e.y<=h[i].y) {
b.update(e.x1+OFFSET,1);
}
}
else if(e.type==2) {
if(e.x1>=h[i].x1&&e.x1<=h[i].x2&&e.below.y<=h[i].y) {
b.update(e.x1+OFFSET,-1);
}
}
else {
if(e.y>h[i].y) {
long x=b.sum(e.x1+OFFSET,e.x2+OFFSET);
res+=x*(x-1)/2;
}
}
}
}
System.out.println(res);
}
/*
7
-1 4 -1 -2
6 -1 -2 -1
-1 3 6 3
2 -2 2 4
4 -1 4 3
5 3 5 1
5 2 1 2
*/
static class bit {
int n;
int[] a;
public bit(int size) {
this.n=size+1;
a = new int[n];
}
void update(int i,int delta) {
while(i<n) {
a[i]+=delta;
i+=Integer.lowestOneBit(i);
}
}
long sum(int i) {
long res=0L;
while(i>0) {
res+=a[i];
i-=Integer.lowestOneBit(i);
}
return res;
}
long sum(int i,int j) {
return sum(j)-sum(i-1);
}
}
static class event implements Comparable<event> {
int x1,x2,y;
int type;//1=open, 2=close, 3=horizontal
event below;//only applicable for type=2
event(int x1, int x2, int y, int type) {
this.x1=x1;
this.x2=x2;
this.y=y;
this.type=type;
}
@Override
public int compareTo(event o) {
if(y==o.y) {
if(type==3) return -1;
if(o.type==3) return 1;
return 0;
}
return y-o.y;
}
public String toString() {
return x1+" "+x2+" "+y+" "+type;
}
}
static class horiz implements Comparable<horiz> {
int x1,x2,y;
horiz(int x1, int x2, int y) {
this.x1=x1;
this.x2=x2;
this.y=y;
}
@Override
public int compareTo(horiz o) {
return y-o.y;
}
}
} | Java | ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"] | 2 seconds | ["7", "0"] | NoteThe following pictures represent sample cases: | Java 8 | standard input | [
"geometry",
"bitmasks",
"sortings",
"data structures",
"brute force"
] | 09890f75bdcfff81f67eb915379b325e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. | 2,200 | Print one integer — the number of ways to choose four segments so they form a rectangle. | standard output | |
PASSED | 7f45c9a44a21e69cf7367ca90ae3eb0e | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.function.BiFunction;
import java.util.function.Function;
public class Main {
static BiFunction<Integer, Integer, Integer> ADD = (x, y) -> (x + y);
static Function<Pair<Integer, Integer>, Integer> GET_FIRST = (x) -> (x.first);
static Function<Pair<Integer, Integer>, Integer> GET_SECOND = (x) -> (x.second);
static Comparator<Pair<Integer, Integer>> C = Comparator.comparing(GET_FIRST).thenComparing(GET_SECOND);
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
int t = in.nextInt();
while (t-- > 0) {
solve();
}
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");
exit(0);
}
/*
Try to take 0 b and see.
Try to take 1 b and see.
*/
static void solve() {
int k = in.nextInt();
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int low = 0;
int high = n;
int mid;
long ans = -1;
while (low <= high) {
mid = (low + high) / 2;
long res = f(a, b, mid, k, n);
if (res >= 0) {
ans = Math.max(ans, res);
high = mid - 1;
} else {
low = mid + 1;
}
}
out.println(Math.min(ans, n));
}
static long f(long a, long b, long mul, long k, long n) {
k -= mul * b;
if (k > 0) {
long r = k / a;
// Check if battery is strictly > 0
long rem = n - mul;
k -= (rem * a);
if (k > 0) {
return rem;
}
}
return Integer.MIN_VALUE;
}
static void debug(Object... args) {
for (Object a : args) {
out.println(a);
}
}
static void y() {
out.println("YES");
}
static void n() {
out.println("NO");
}
static void fail() {
out.println("-1");
exit(0);
}
static class Pair<T, R> {
public T first;
public R second;
public Pair(T first, R second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Pair<?, ?> pair = (Pair<?, ?>) o;
return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "Pair{" + "a=" + first + ", b=" + second + '}';
}
public T getFirst() {
return first;
}
public R getSecond() {
return second;
}
}
static <T, R> Pair<T, R> make_pair(T a, R b) {
return new Pair<>(a, b);
}
static class ArrayUtils {
static int[] reverse(int[] data) {
int[] p = new int[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static void prefixSum(long[] data) {
for (int i = 1; i < data.length; i++) {
data[i] += data[i - 1];
}
}
static void prefixSum(int[] data) {
for (int i = 1; i < data.length; i++) {
data[i] += data[i - 1];
}
}
static long[] reverse(long[] data) {
long[] p = new long[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static char[] reverse(char[] data) {
char[] p = new char[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static int[] MergeSort(int[] A) {
if (A.length > 1) {
int q = A.length / 2;
int[] left = new int[q];
int[] right = new int[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
int[] left_sorted = MergeSort(left);
int[] right_sorted = MergeSort(right);
return Merge(left_sorted, right_sorted);
} else {
return A;
}
}
static int[] Merge(int[] left, int[] right) {
int[] A = new int[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
static long[] MergeSort(long[] A) {
if (A.length > 1) {
int q = A.length / 2;
long[] left = new long[q];
long[] right = new long[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
long[] left_sorted = MergeSort(left);
long[] right_sorted = MergeSort(right);
return Merge(left_sorted, right_sorted);
} else {
return A;
}
}
static long[] Merge(long[] left, long[] right) {
long[] A = new long[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
}
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 long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readAllInts(int n) {
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
}
return p;
}
public int[] readAllInts(int n, int s) {
int[] p = new int[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextInt();
}
return p;
}
public long[] readAllLongs(int n) {
long[] p = new long[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextLong();
}
return p;
}
public long[] readAllLongs(int n, int s) {
long[] p = new long[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextLong();
}
return p;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static void exit(int a) {
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
| Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | e8a4c964b4fad1a6346b653a14c9dddd | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.*;
import static java.lang.Integer.parseInt;
public class m {
private static final boolean ONLINE_JUDGE = true; //System.getProperty("ONLINE_JUDGE") != null;
public static void main(String[] args) {
try (BufferedReader reader = ONLINE_JUDGE ? new BufferedReader(new InputStreamReader(System.in))
: new BufferedReader(new FileReader("input"));
Writer writer = ONLINE_JUDGE ? new OutputStreamWriter(System.out) : new FileWriter("output");
PrintWriter printWriter = new PrintWriter(writer);) {
Solver solver = new Solver(reader, printWriter);
while (solver.solve());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
static final class Solver {
final BufferedReader in;
final PrintWriter out;
public Solver(BufferedReader reader, PrintWriter writer) {
in = reader;
out = writer;
}
boolean solve() throws IOException {
String line = in.readLine();
if (line == null) {
return false;
}
if (line.isEmpty()) {
return true;
}
int q = Integer.parseInt(line);
for (int qq = 0; qq < q; ++qq) {
StringTokenizer tok = new StringTokenizer(in.readLine());
int k = Integer.parseInt(tok.nextToken());
int n = Integer.parseInt(tok.nextToken());
int a = Integer.parseInt(tok.nextToken());
int b = Integer.parseInt(tok.nextToken());
if ((k - 1) / b < n) {
out.println(-1);
continue;
}
int l = -1;
int r = n + 1;
while (l + 1 < r) {
int mid = l + ((r - l) >> 1);
long zar = k;
long steps = mid;
zar -= mid * 1L * a;
long steps2 = 0;
if (zar > b) {
steps2 = (zar - 1) / b;
steps += steps2;
}
zar -= steps2 * 1L * b;
if (steps >= n && zar > 0) {
l = mid;
} else {
r = mid;
}
}
//debug("play " + movesJustPlay + " charge " + movesPlayAndCharge);
out.println(l);
}
return true;
}
}
static void debug(String s) {
System.out.println(s);
}
}
| Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 44b905c30103fdc2db31ba3156fd0967 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
public class R570D3C {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine());
int[] answers = new int[t];
for(int i = 0;i<t;i++){
StringTokenizer st = new StringTokenizer(bf.readLine());
long k = Long.parseLong(st.nextToken());
long n = Long.parseLong(st.nextToken());
long a = Long.parseLong(st.nextToken());
long b = Long.parseLong(st.nextToken());
if (k - b*n <= 0){
answers[i] = -1;
continue;
}
int x = (int)(Math.ceil((k-b*n+0.0)/(a-b+0.0)-1));
answers[i] = Math.min(x, (int)(n));
}
for(int i = 0;i<t;i++){
System.out.println(answers[i]);
}
}
}
| Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | b3e399fc665bcbfdb923ddc50d4be666 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java .util.*;
public class game {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t=scn.nextInt();
for(int p=0;p<t;p++) {
long k=scn.nextLong();
long n=scn.nextLong();
long a=scn.nextLong();
long b=scn.nextLong();
long c=k-(a*n);
if(c>0)
System.out.println(n);
else
{
long turn;
turn =(-c+1)/(a-b);
if(turn>n)
System.out.println("-1");
else {
if((-c+1)%(a-b)!=0)
System.out.println(n-turn-1);
else
System.out.println(n-turn);
}
}
}
}
}
| Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 121a99b8a4a44275cf748d9da30071d6 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 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);
int t = sc.nextInt();
while(t-- > 0) {
int k = sc.nextInt();
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
long v = (n * (long)b) + 1;
if(v > (long)k) {
System.out.println(-1);
} else {
int diff = a - b;
int val = k - (n * b);
int quo = val / diff;
if(quo > n) {
System.out.println(n);
} else if(quo == n) {
if(val % diff == 0) {
System.out.println(n - 1);
} else {
System.out.println(n);
}
} else {
if(val % diff == 0) {
System.out.println(quo - 1);
} else {
System.out.println(quo);
}
}
}
}
}
} | Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 3b939c07b01fd464546f0899452e6f4f | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | 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 long searchMaxA(long k,long n,long a,long b){
long left=0,right=n,mid=0;
while(left<right){
mid=(left+right+1)/2;
if((mid*a+(n-mid)*b)<k)
left=mid;
else if((mid*a+(n-mid)*b)>=k)
right=mid-1;
}
return left;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t-- > 0){
String[] str=br.readLine().split(" ");
long k=Long.parseLong(str[0]);
long n=Long.parseLong(str[1]);
long a=Long.parseLong(str[2]);
long b=Long.parseLong(str[3]);
if(k>n*b){
System.out.println(searchMaxA(k,n,a,b));
}
else
System.out.println(-1);
}
}
} | Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 8f02cfd907b3e93cefdc96b01677e052 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
//Scanner scanner = new Scanner(new FileInputStream(new File("test")));
Scanner scanner = new Scanner(System.in);
int Q = scanner.nextInt();
while (Q --> 0) {
long K = scanner.nextLong();
long N = scanner.nextLong();
long A = scanner.nextLong();
long B = scanner.nextLong();
System.out.println(check(K, N, A, B));
}
scanner.close();
}
private static long check(long K, long N, long A, long B) {
long a = 0;
long b = K / B;
if (b < N) return -1;
if (b == N && K % B == 0) return -1;
//System.out.printf("%d %d %d %d\n", K, N, A, B);
long l = 0, r = b;
while (l < r) {
//System.out.printf("N: %d, ", a+b);
b = (l + r) / 2;//b--;
long temp = (K - B * b);
a = temp / A; if (temp % A == 0) a--;
//System.out.printf("a:%d, b: %d\n", a, b);
if (a + b < N) {
l = b + 1;
} else {
r = b;
}
}
//if (a == 0 && K % B == 0) return -1;
//b++;
//long temp = (K - B * b);
//a = temp / A; if (temp % A == 0) a--;
return Math.min(N, a);
}
}
| Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | d32ac1566f0e28568e4b3825ade9c478 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
public class C {
static Random random;
private static void mySort(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
Arrays.sort(s);
}
static class Pair{
int x;
int y;
public Pair(int x, int y) {
this.x=x;
this.y=y;
}
}
public static void sortPairX(Pair[] p) {
Arrays.sort(p, new Comparator<Pair>() {
public int compare(Pair o1, Pair o2) {
return o1.x-o2.x;
}
});
}
public static void sortPairY(Pair[] p) {
Arrays.sort(p, new Comparator<Pair>() {
public int compare(Pair o1, Pair o2) {
return o1.y-o2.y;
}
});
}
public static void main(String[] args) {
random = new Random(543534151132L + System.currentTimeMillis());
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int nb=in.nextInt();
for(int i=0;i<nb;i++) {
int k=in.nextInt();
int n=in.nextInt();
int a=in.nextInt();
int b=in.nextInt();
if((long)b*n>=k)out.println(-1);
else {
int re=k-n*b;
int nbA=0;
int nbT=n;
if(re>=a) {
int rr=re/a;
re=re%a;
nbA+=rr;
re+=b*rr;
}
nbA+=re/(a-b);
re=re%(a-b);
if(re==0)nbA--;
out.println(Math.min(nbA, n));
}
}
out.close();
}
public static int gcd(int a, int b)
{
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
public static long gcd(long a, long b)
{
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.longValue();
}
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());
}
public float nextFloat() {
return Float.parseFloat(next());
}
}
} | Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 247f2f851e368140de7a314e44badfea | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for(int i=0;i<q;i++)
{
long ans =-1;
long k = in.nextLong();
long n = in.nextLong();
long a = in.nextLong();
long b = in.nextLong();
k -= n * a;
if(k > 0)
ans=n;
else {
k = -k;
++k;
long diff = a - b;
long turns = (k + diff - 1) / diff;
if (turns> n)
ans=-1;
else
ans=n-turns;
}
System.out.println(ans);
}
}
} | Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 12000807c0f4108a373759741113e8b6 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException{
Reader reader = new Reader();
int q = reader.nextInt();
StringBuilder stringBuilder = new StringBuilder();
while(q-- > 0){
long k = reader.nextInt();
long n = reader.nextInt();
long a = reader.nextInt();
long b = reader.nextInt();
if(k - n * b <= 0) stringBuilder.append(-1);
else {
long l = 0;
long r = n;
long ans = -1;
while(l <= r){
long m = (l + r) / 2;
if(m * a + (n - m) * b < k){
ans = m;
l = m + 1;
}else r = m - 1;
}
stringBuilder.append(ans);
}
stringBuilder.append("\n");
}
System.out.println(stringBuilder);
}
}
class Reader{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() throws IOException{
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();
}
} | Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | b4581349319a5e202a69bb251db6914b | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException{
Reader reader = new Reader();
int q = reader.nextInt();
while(q-- > 0){
long k = reader.nextInt();
long n = reader.nextInt();
long a = reader.nextInt();
long b = reader.nextInt();
if(k - n * b <= 0) System.out.println(-1);
else {
long l = 0;
long r = n;
long ans = -1;
while(l <= r){
long m = (l + r) / 2;
long charge = k - m * a;
if(charge - (n - m) * b > 0){
ans = m;
l = m + 1;
}else r = m - 1;
}
System.out.println(ans);
}
}
}
}
class Reader{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() throws IOException{
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();
}
} | Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 582c008cd68dec6a6070d1643f694d8e | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException{
Reader reader = new Reader();
int q = reader.nextInt();
StringBuilder stringBuilder = new StringBuilder();
while(q-- > 0){
long k = reader.nextInt();
long n = reader.nextInt();
long a = reader.nextInt();
long b = reader.nextInt();
if(k - n * b <= 0) stringBuilder.append(-1);
else {
long l = 0;
long r = n;
long ans = -1;
while(l <= r){
long m = (l + r) / 2;
long charge = k - m * a;
if(charge - (n - m) * b > 0){
ans = m;
l = m + 1;
}else r = m - 1;
}
stringBuilder.append(ans);
}
stringBuilder.append("\n");
}
System.out.println(stringBuilder);
}
}
class Reader{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() throws IOException{
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();
}
} | Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 764c11ba18069f1004aa76a5f3f562b8 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
public class ComputerGame {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long q = sc.nextInt();
for (long i = 0; i < q; i++) {
long charge = sc.nextInt();
long turns = sc.nextInt();
long a = sc.nextInt();
long b = sc.nextInt();
if (b * turns >= charge) {
System.out.println(-1);
continue;
}
long l = 0;
long r = turns + 1;
while (l < r - 1) {
long mid = (long) Math.floor((l + r) / 2);
if (mid * a + (turns - mid) * b < charge) {
l = mid;
} else {
r = mid;
}
}
System.out.println(l);
}
sc.close();
}
}
| Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 7b6ab91d314ebc9bfa0ce853820edd50 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
/**
* #
*
* @author pttrung
*/
public class C_Round_570_Div3 {
public static long MOD = 998244353;
static int[][] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int q = in.nextInt();
for (int z = 0; z < q; z++) {
long k = in.nextInt();
long n = in.nextInt();
long a = in.nextInt();
long b = in.nextInt();
long max = k / b;
if (k % b == 0) {
max--;
}
if (max < n) {
out.println(-1);
} else {
long st = 0;
long ed = k / a;
if (k % a == 0) {
ed--;
}
long re = 0;
while (st <= ed) {
long mid = (st + ed) / 2;
long left = k - mid * a;
long other = left / b;
if (left % b == 0) {
other--;
}
//System.out.println(mid + " " + other + left );
if (mid + other >= n && left > 0) {
re = mid;
st = mid + 1;
} else {
ed = mid - 1;
}
}
out.println(Long.min(n, re));
}
}
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * (val * a);
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 42691e8563237359b8eac97f57c65eb1 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
public class cf570C
{
public static void main(String args[]) throws Exception
{
FastReader sc=new FastReader();
StringBuffer buf=new StringBuffer();
int t=sc.nextInt();
for(int k1=0;k1<t;k1++)
{
long k=sc.nextInt();
long n=sc.nextInt();
long a=sc.nextInt();
long b=sc.nextInt();
if((k<=(b*n)))
{
buf.append(-1+"\n");
}
else
{
long f=(k-(b*n)-1)/(a-b);
//float i=(float)Math.floor(f);
//int ans=(int)i;
f=Math.min(f, n);
buf.append(f+"\n");
}
}
System.out.print(buf);
}
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 | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | ed012bb2a5fc0b9fe8416c769e98a44f | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Main{
public static long search(long l,long r,long a,long b,long k,long N) {
if (l+1>=r) {
// System.out.println(l+" "+r);
long A = l*a+(N-l)*b;
long B = r*a+(N-r)*b;
// System.out.println(A+" "+B);
if (A<k && A>=0 && B<k && B>=0) {
return r;
}
else if (A<k && A>=0 && B>=k) {
return l;
}
else if (A>=k && B<k && B>=0) {
return r;
}
else {
return -1;
}
}
long mid = (l+r)/2;
if (mid*a+(N-mid)*b<k) {
return search(mid,r, a, b, k, N);
}
else {
return search(l, mid, a, b, k, N);
}
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
for (int A=0;A<T;A++){
long k = scan.nextLong();
long n = scan.nextLong();
long a = scan.nextLong();
long b = scan.nextLong();
long r = (k-1)/a;
if (r>=n) {
System.out.println(n);
}
else {
System.out.println(search(0, r,a, b, k, n));
}
}
}
} | Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 81538c9a074c660b13d5ef645e17dbb2 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main extends ArrayList 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();
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static int log2(int n)
{
int p = 1;
if (n > 0 && (n & (n - 1)) == 0)
return n;
while (p < n)
p <<= 1;
return p;
}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int q=sc.nextInt();
for(int i=0;i<q;i++)
{
long k=sc.nextLong();
long n=sc.nextLong();
long a=sc.nextLong();
long b=sc.nextLong();
if(1!=1)
{
w.println("-1");
}
else
{
long r=a-b;
long t=a*n;
long t1=t-k;
long ans=0;
//w.println(t1+" "+k+" "+t+" ");
if(t1<0)
{
ans=0;
}
else if(t1>=0)
{
ans=t1/r;
ans++;
//w.print(ans);
if(ans>=n && n*b<k)
{
ans=n;
}
else if(ans>=n)
{
ans=n+1;
}
//w.print(ans);
}
w.println(n-ans);
}
}
w.close();
}
} | Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | c5870847bf8194bbf218aa9eeb288688 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | //Author: Patel Rag
//Java version "1.8.0_211"
import java.util.*;
import java.io.*;
public class Main
{
static class Reader
{
private byte[] buffer = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader()
{
in = System.in;
}
public int scan() throws IOException
{
if(total < 0)
{
throw new InputMismatchException();
}
if(index >= total)
{
index = 0;
total = in.read(buffer);
if(total <= 0)
{
return -1;
}
}
return buffer[index++];
}
public int nextInt() 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 long nextLong() 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 nextDouble() 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 nextString() 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;
}
}
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;
}
void close() throws IOException
{
br.close();
}
}
static class Print
{
private final BufferedWriter bw;
public Print()
{
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object)throws IOException
{
bw.append(""+object);
}
public void println(Object object)throws IOException
{
print(object);
bw.append("\n");
}
public void close()throws IOException
{
bw.close();
}
}
static long modExp(long x, long n, long mod) //Modular exponentiation
{
long result = 1;
while(n > 0)
{
if(n % 2 == 1)
result = (result%mod * x%mod)%mod;
x = (x%mod * x%mod)%mod;
n=n/2;
}
return result;
}
static long gcd(long a, long b)
{
if(a==0) return b;
return gcd(b%a,a);
}
static String swap(String a,int i, int j)
{
char temp;
char[] s1 = a.toCharArray();
temp = s1[i];
s1[i] = s1[j];
s1[j] = temp;
return String.valueOf(s1);
}
public static void main(String[] args)
throws IOException
{
Reader fr = new Reader();
//Print log = new Print();
int T = fr.nextInt();
for(int t = 0; t < T; t++)
{
long k = fr.nextLong();
long n = fr.nextLong();
long a = fr.nextLong();
long b = fr.nextLong();
long res = -1;
if(k > n*b)
{
res = 0;
long l = 0;
long r = n;
while(r >= l)
{
long mid = (l + r)/2;
long lft = k - mid*a - (n - mid)*b;
if(lft > 0)
{
res = mid;
l = mid + 1;
}
else
{
r = mid - 1;
}
}
}
System.out.println(res);
}
}
}
class Pair<U, V> // Pair class
{
public final U first; // first field of a Pair
public final V second; // second field of a Pair
private Pair(U first, V second)
{
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (!first.equals(pair.first)) return false;
return second.equals(pair.second);
}
@Override
public int hashCode()
{
return 31 * first.hashCode() + second.hashCode();
}
public static <U, V> Pair <U, V> of(U a, V b)
{
return new Pair<>(a, b);
}
}
class myComp implements Comparator<Pair>
{
public int compare(Pair a,Pair b)
{
if((Integer)a.second > (Integer)b.second) return -1;
if((Integer)a.second < (Integer)b.second) return 1;
if((Integer)a.first > (Integer)b.first) return 1;
return -1;
}
}
class BIT //Binary Indexed Tree
{
public long[] m_array;
public BIT(long[] dat)
{
m_array = new long[dat.length + 1];
Arrays.fill(m_array,0);
for(int i = 0; i < dat.length; i++)
{
m_array[i + 1] = dat[i];
}
for(int i = 1; i < m_array.length; i++)
{
int j = i + (i & -i);
if(j < m_array.length)
{
m_array[j] = m_array[j] + m_array[i];
}
}
}
public final long prefix_query(int i)
{
long result = 0;
for(++i; i > 0; i = i - (i & -i))
{
result = result + m_array[i];
}
return result;
}
public final long range_query(int fro, int to)
{
if(fro == 0)
{
return prefix_query(to);
}
else
{
return (prefix_query(to) - prefix_query(fro - 1));
}
}
public void update(int i, long add)
{
for(++i; i < m_array.length; i = i + (i & -i))
{
m_array[i] = m_array[i] + add;
}
}
}
| Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | aec3e61f3e67a9d2af2101eebc824d0b | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;
/**
*
* @author KIIT
*/
public class ComputerGame {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long q = sc.nextInt();
while(q-->0)
{
long battery = sc.nextInt();
long n = sc.nextInt();
long a = sc.nextInt();
long b = sc.nextInt();
long l= 0;
long u = n;
boolean flag = false;
while(l<u)
{
long mid = l + (u-l+1)/2;
// System.out.println(l+" "+mid+" "+u);
if(ifPossible(battery,mid,a,b,n))
{
l = mid;
}
else
{
u = mid - 1;
}
}
if(ifPossible(battery,l,a,b,n))
System.out.println(l);
else
System.out.println(-1);
}
}
private static boolean ifPossible(long battery, long mid, long a, long b,long n) {
if( battery - a*mid>0)
{
battery-=a*mid;
}
else
return false;
if(battery-(n-mid)*b>0)
return true;
return false;
}
}
| Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 843d73e04dcfa47f045cfb4667c8b4d1 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class cf_5_3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
for(int i=0;i<q;i++){
long k = sc.nextInt();
long n = sc.nextInt();
long a = sc.nextInt();
long b = sc.nextInt();
// System.out.println(k/b);
long d = k-(b*n)-1;
long c = (a-b);
long m = d/c;
if(b*n>=k) {
System.out.println(-1);;
}
else {
System.out.println(Math.min(n, m));
}
}
}
}
| Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | ec6ea19fa9570301d50cd09bc4fd0628 | train_000.jsonl | 1561559700 | Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
public class Cy {
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[1000000]; // 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 sc=new Reader();
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int i,j;
int t=sc.nextInt();
while(t-->0){
long k=sc.nextInt();
long n=sc.nextInt();
long a=sc.nextInt();
long b=sc.nextInt();
if(k<=n*b)
pw.println("-1");
else{
// long l=0;
// long h=n;
// long y=k-1;
// while(h>=l){
// long mid=(l+h)/2;
// if(a*l+b*(n-l)==y)
// break;
// if(a*l+b*(n-l)<y)
// {
// l=mid+1;
// continue;
// }
// else{
// h=mid-1;
// continue;
// }
// }
// if(l>h)
// l=h;
// if(a*l+b*(n-l)>y)
// {
// // pw.print("1 ");
// while(a*l+b*(n-l)>y&&l>=1)
// l--;
// pw.println(l);
// }
// else{
// // pw.print("2 ");
// pw.println(l);
// }
long p=(long)Math.pow(10,(int)Math.log10(n));
long l=0;
// long )
for(i=(int)Math.log10(n)+1;i>=0;i--){
// pw.println(l);
// pw.println("i "+i);
long ai=(long)Math.pow(10,i);
// pw.println(ai);
// if(i!=(int)Math.log10(n))
l+=9*ai;
while(a*l+b*Math.max((n-l),0)>=k&&l>=ai){
l-=ai;
// pw.println("l "+l);
}
// l+=ai;
//l-=ai;
// break;
}
if(a*l+b*(n-l)>=k&&l>0)
l--;
pw.println(Math.min(l,n));
}
}
pw.close();
}
} | Java | ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"] | 3 seconds | ["4\n-1\n5\n2\n0\n1"] | NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn. | Java 8 | standard input | [
"binary search",
"math"
] | 2005224ffffb90411db3678ac4996f84 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly. | 1,400 | For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise. | standard output | |
PASSED | 142925538b8c0a22827bbab50eabc41d | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.io.*;
import java.util.*;
public class DivisionIntoTeams {
static class Player implements Comparable<Player> {
int skill, number;
public Player(int skill, int number) {
this.skill = skill;
this.number = number;
}
@Override
public int compareTo(Player p) {
return this.skill - p.skill;
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
int n = in.nextInt();
Player[] a = new Player[n];
for (int i = 0; i < n; ++i)
a[i] = new Player(in.nextInt(), i + 1);
Arrays.sort(a);
ArrayList<Integer> p = new ArrayList<Integer>();
ArrayList<Integer> q = new ArrayList<Integer>();
int sum1 = 0;
int sum2 = 0;
for (int i = 0; i < n / 2 * 2; ++i)
if (i % 2 == 0) {
p.add(a[i].number);
sum1 += a[i].skill;
} else {
q.add(a[i].number);
sum2 += a[i].skill;
}
if (n % 2 == 1) {
if (sum1 < sum2)
p.add(a[n - 1].number);
else
q.add(a[n - 1].number);
}
System.out.println(p.size());
System.out.print(p.get(0));
for (int i = 1; i < p.size(); ++i)
System.out.print(" " + p.get(i));
System.out.println();
System.out.println(q.size());
System.out.print(q.get(0));
for (int i = 1; i < q.size(); ++i)
System.out.print(" " + q.get(i));
System.out.println();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = new StringTokenizer("");
}
public String next() {
try {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
public String nextLine() {
String line = null;
try {
tokenizer = new StringTokenizer("");
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String line = nextLine();
if (line == null) return false;
tokenizer = new StringTokenizer(line);
}
return true;
}
}
}
| Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | ecad28074e6649764dc00c0ae4415b66 | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.io.*;
import java.util.*;
public class DivisionIntoTeams {
static class Player implements Comparable<Player> {
int skill, number;
public Player(int skill, int number) {
this.skill = skill;
this.number = number;
}
@Override
public int compareTo(Player p) {
return this.skill - p.skill;
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
int n = in.nextInt();
Player[] a = new Player[n];
for (int i = 0; i < n; ++i)
a[i] = new Player(in.nextInt(), i + 1);
Arrays.sort(a);
ArrayList<Integer> p = new ArrayList<Integer>();
ArrayList<Integer> q = new ArrayList<Integer>();
int sum1 = 0;
int sum2 = 0;
for (int i = 0; i < n / 2 * 2; ++i)
if (i % 2 == 0) {
p.add(a[i].number);
sum1 += a[i].skill;
} else {
q.add(a[i].number);
sum2 += a[i].skill;
}
if (n % 2 == 1) {
if (sum1 < sum2)
p.add(a[n - 1].number);
else
q.add(a[n - 1].number);
}
System.out.println(p.size());
System.out.print(p.get(0));
for (int i = 1; i < p.size(); ++i)
System.out.print(" " + p.get(i));
System.out.println();
System.out.println(q.size());
System.out.print(q.get(0));
for (int i = 1; i < q.size(); ++i)
System.out.print(" " + q.get(i));
System.out.println();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = new StringTokenizer("");
}
public String next() {
try {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
public String nextLine() {
String line = null;
try {
tokenizer = new StringTokenizer("");
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String line = nextLine();
if (line == null) return false;
tokenizer = new StringTokenizer(line);
}
return true;
}
}
}
| Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | 2c7a7cbb4695cea336ca3ecf0f5774a7 | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.awt.Paint;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class C13 {
public static void main(String[] args) throws Exception{
int n=in();
point[] a=new point [n];
for (int i=0;i<n;i++)a[i]=new point(in(),i+1);
Arrays.sort(a);
int s1=0;
int x=0;
int s2=0;
int y=0;
StringBuilder b1=new StringBuilder();
StringBuilder b2=new StringBuilder();
boolean t=false;
for (int i=n-1;i>=0;i--){
if (!t){
s1+=a[i].x;
x++;
b1.append(a[i].y+" ");
t=!t;
}
else{
s2+=a[i].x;
y++;
b2.append(a[i].y+" ");
t=!t;
}
}
System.out.println(x);
System.out.println(b1);
System.out.println(y);
System.out.println(b2);
}
static BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static int in() throws IOException{
if (st==null || !st.hasMoreTokens()){
st=new StringTokenizer(buf.readLine());
}
return Integer.parseInt(st.nextToken());
}
static long ll() throws IOException{
if (st==null || !st.hasMoreTokens()){
st=new StringTokenizer(buf.readLine());
}
return Long.parseLong(st.nextToken());
}
static String str() throws IOException{
if (st==null || !st.hasMoreTokens()){
st=new StringTokenizer(buf.readLine());
}
return (st.nextToken());
}
static double dub() throws IOException{
if (st==null || !st.hasMoreTokens()){
st=new StringTokenizer(buf.readLine());
}
return Double.parseDouble(st.nextToken());
}
}
class point extends Point implements Comparable<point>{
public point(int in, int i) {
super();
x=in;
y=i;
}
public int compareTo(point o) {
return x-o.x;
}
}
| Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | 8f3170823d4f14eae43a79fe0210a8a8 | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class C {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int n = in.nextInt();
Player[] players = new Player[n];
for (int i = 1; i <= n; i++) {
players[i - 1] = new Player();
players[i - 1].score = in.nextInt();
players[i - 1].index = i;
}
Arrays.sort(players);
List<Player> team1 = new ArrayList<Player>(), team2 = new ArrayList<Player>();
int sum1 = 0, sum2 = 0;
for (int i = 0; i < n; i++) {
if (sum1 < sum2) {
team1.add(players[i]);
sum1 += players[i].score;
} else {
team2.add(players[i]);
sum2 += players[i].score;
}
}
System.out.println(team1.size());
for (int i = 0; i < team1.size(); i++) {
System.out.print(team1.get(i).index + " ");
}
System.out.println();
System.out.println(team2.size());
for (int i = 0; i < team2.size(); i++) {
System.out.print(team2.get(i).index + " ");
}
System.out.println();
}
}
class Player implements Comparable<Player> {
int index;
int score;
@Override
public int compareTo(Player o) {
return score - o.score;
}
} | Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | 41550cf35c34dfc6c5ded9716cf6b20a | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;
public class Solution{
///////////////////////////////////////////////////////////////////////////
static class FastScanner{
BufferedReader s;
StringTokenizer st;
public FastScanner(InputStream InputStream){
st = new StringTokenizer("");
s = new BufferedReader(new InputStreamReader(InputStream));
}
public FastScanner(File f) throws FileNotFoundException{
st = new StringTokenizer("");
s = new BufferedReader (new FileReader(f));
}
public int nextInt() throws IOException{
if(st.hasMoreTokens())
return Integer.parseInt(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextInt();
}
}
/* public double nextDouble() throws IOException{
if(st.hasMoreTokens())
return Double.parseDouble(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextDouble();
}
}
*/
public long nextLong() throws IOException{
if(st.hasMoreTokens())
return Long.parseLong(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextLong();
}
}
public String nextString() throws IOException{
if(st.hasMoreTokens())
return st.nextToken();
else{
st = new StringTokenizer(s.readLine());
return nextString();
}
}
public String readLine() throws IOException{
return s.readLine();
}
public void close() throws IOException{
s.close();
}
}
////////////////////////////////////////////////////////////////////
// Number Theory
long pow(long a,long b,long mod){
long x = 1; long y = a;
while(b > 0){
if(b % 2 == 1){
x = (x*y);
x %= mod;
}
y = (y*y);
y %= mod;
b /= 2;
}
return x;
}
int divisor(long x,long[] a){
long limit = x;
int numberOfDivisors = 0;
for (int i=1; i < limit; ++i) {
if (x % i == 0) {
limit = x / i;
if (limit != i) {
numberOfDivisors++;
}
numberOfDivisors++;
}
}
return numberOfDivisors;
}
void findSubsets(int array[]){
long numOfSubsets = 1 << array.length;
for(int i = 0; i < numOfSubsets; i++){
int pos = array.length - 1;
int bitmask = i;
while(bitmask > 0){
if((bitmask & 1) == 1)
ww.print(array[pos]+" ");
bitmask >>= 1;
pos--;
}
ww.println();
}
}
public static int gcd(int a, int b){
return b == 0 ? a : gcd(b,a%b);
}
public static int lcm(int a,int b, int c){
return lcm(lcm(a,b),c);
}
public static int lcm(int a, int b){
return a*b/gcd(a,b);
}
////////////////////////////////////////////////////////////////////
// private static FastScanner s = new FastScanner(new File("input.txt"));
// private static PrintWriter ww = new PrintWriter(new FileWriter("output.txt"));
static InputStream inputStream = System.in;
static FastScanner s = new FastScanner(inputStream);
static OutputStream outputStream = System.out;
static PrintWriter ww = new PrintWriter(new OutputStreamWriter(outputStream));
// private static Scanner s = new Scanner(System.in);
@SuppressWarnings("unused")
private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} };
////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws IOException{
new Solution().solve();
s.close();
ww.close();
}
class Node implements Comparable<Node>{
int val;
int in;
Node(int val,int in){
this.val = val;
this.in = in;
}
@Override
public int compareTo(Node arg0) {
// TODO Auto-generated method stub
return Integer.compare(val, arg0.val);
}
}
////////////////////////////////////////////////////////////////////
void solve() throws IOException{
int n = s.nextInt();
Integer[] a = new Integer[n];
Node[] node = new Node[n];
for(int i=0;i<n;i++){
a[i] = s.nextInt();
node[i] = new Node(a[i],i+1);
}
Arrays.sort(node);
Stack<Node> one = new Stack<Node>();
Stack<Node> two = new Stack<Node>();
for(int i=0;i<n;i++){
if((i&1) == 0) one.add(node[i]);
else two.add(node[i]);
}
ww.println(one.size());
while(!one.isEmpty()) ww.print(one.pop().in+" ");
ww.println();
ww.println(two.size());
while(!two.isEmpty()) ww.print(two.pop().in+" ");
}
} | Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | d8ae410e253d2550822455b8cd88d927 | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
public class DivisionintoTeams {
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
int n = Integer.parseInt(reader.readLine());
Point a[] = new Point[n];
String st[] = reader.readLine().split(" ");
for (int i = 0; i < n; i++) {
a[i] = new Point(i, Integer.parseInt(st[i]));
}
Arrays.sort(a, new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
return o1.y - o2.y;
}
});
int f = 0;
StringBuilder sbf = new StringBuilder("");
int s = 0;
StringBuilder sbs = new StringBuilder("");
for (int i = 0; i < n; i++) {
if ((i & 1) == 0) {
sbf.append(" " + (a[i].x + 1));
f++;
} else {
sbs.append(" " + (a[i].x + 1));
s++;
}
}
System.out.println(f);
System.out.println(sbf.substring(1));
System.out.println(s);
System.out.println(sbs.substring(1));
}
}
| Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | a589ae3ab3b9cfb0b0e4c52472b957e7 | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.BigInteger;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main
{
static StringTokenizer st=new StringTokenizer("");
static BufferedReader br;
///////////////////////////////////////////////////////////////////////////////////
public static void main(String args[]) throws FileNotFoundException, IOException, Exception
{
//Scanner class
//Scanner in =new Scanner(new FileReader("input.txt"));
//Scanner in=new Scanner(System.in);
//PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//br=new BufferedReader(new FileReader("input.txt"));
br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
//StringTokenizer st;//=nedsw StringTokenizer(br.readLine());
//////////////////////////////////////////////////////////////////////////////////////
int n=ni();
pair p[]=new pair[n];
for(int i=0;i<n;i++)
p[i]=new pair(i,ni());
Arrays.sort(p);
long suma=0,sumb=0;
ArrayList<Integer> one=new ArrayList<Integer>();
ArrayList<Integer> two=new ArrayList<Integer>();
for(int i=0;i<n;i++)
{
if(suma<=sumb)
{
suma+=(long)p[i].second;
one.add(p[i].first+1);
}
else
{
sumb+=(long)p[i].second;
two.add(p[i].first+1);
}
}
out.println(one.size());
for(int k: one)
out.print(k+" ");
out.println();
out.println(two.size());
for(int k:two) out.print(k+" ");
//////////////////////////////////////////////////////////////////////////////////////
out.close();
}
///////////////////////////////////////////////////////////////////////////////
private static long gcd(long a,long b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
private static class pair implements Comparable<pair>
{
int first;
int second;
pair()
{
first=0;
second=0;
}
pair(int f,int s)
{
first=f;
second=s;
}
public int compareTo(pair o)
{
if(second > o.second)
return 1;
else if(second < o.second)
return -1;
else
return 0;
}
}
public static Integer ni() throws Exception
{
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());
}
public static BigInteger nb()throws Exception
{
if(!st.hasMoreElements())
st=new StringTokenizer(br.readLine());
return BigInteger.valueOf(Long.parseLong(st.nextToken()));
}
public static Long nl() throws Exception
{
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return Long.parseLong(st.nextToken());
}
public static Double nd()throws Exception
{
if(!st.hasMoreElements())
st=new StringTokenizer(br.readLine());
return Double.parseDouble(st.nextToken());
}
public static String ns()throws Exception
{
if(!st.hasMoreElements())
st=new StringTokenizer(br.readLine());
return st.nextToken();
}
} | Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | 479203f3a0bcba08439f6dca37b89d1f | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.util.*;
import java.io.*;
public class C149 implements Runnable {
class Person implements Comparable<Person>{
int id;
int p;
public Person(int id, int p){
this.id = id;
this.p = p;
}
public int compareTo(Person b){
return -(p - b.p);
}
}
public void solve() throws IOException {
int N = nextInt();
Person[] boys = new Person[N];
for(int i = 0; i < N; i++){
boys[i] = new Person(i + 1, nextInt());
}
Arrays.sort(boys);
int a = 0;
int b = 0;
List<Integer> teama = new ArrayList<>();
List<Integer> teamb = new ArrayList<>();
for(int i = 0; i < N / 2; i++){
Person first = boys[2 * i];
Person second = boys[2 * i + 1];
if(a < b){
teama.add(first.id);
teamb.add(second.id);
a += first.p;
b += second.p;
}
else{
teamb.add(first.id);
teama.add(second.id);
b += first.p;
a += second.p;
}
}
if(N % 2 != 0){
Person now = boys[N - 1];
if(a < b){
teama.add(now.id);
a += now.p;
}
else{
teamb.add(now.id);
b += now.p;
}
}
StringBuilder sb = new StringBuilder();
sb.append(teama.size() + "\n");
for(int i = 0; i < teama.size(); i++) sb.append(teama.get(i) + " ");
sb.append("\n");
sb.append(teamb.size() + "\n");
for(int j = 0; j < teamb.size(); j++) sb.append(teamb.get(j) + " ");
System.out.println(sb.toString());
}
//-----------------------------------------------------------
public static void main(String[] args) {
new C149().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tok = null;
solve();
in.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());
}
BufferedReader in;
StringTokenizer tok;
} | Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | 879c4cd72e07c795d348b379c6d28075 | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Division_into_Teams {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(b.readLine());
player[] p = new player[n];
StringTokenizer t = new StringTokenizer(b.readLine(), " ");
for (int i = 0; i < n; i++) {
p[i] = new player();
p[i].i = i + 1;
p[i].skl = Integer.parseInt(t.nextToken());
}
Arrays.sort(p);
int x = 0;
int y = 0;
StringBuilder xx = new StringBuilder(), yy = new StringBuilder();
boolean c = false;
for (int i = n - 1; i >= 0; i--) {
if (!c) {
c = true;
// // if (i == n - 1) {
// y++;
// yy.append(p[i].i);
// } else {
x++;
xx.append(p[i].i);
if (x > 0 && i > 1)
xx.append(" ");
// }
} else {
c = false;
y++;
yy.append(p[i].i);
if (y > 0 && i > 1)
yy.append(" ");
}
}
System.out.println(x);
System.out.println(xx);
System.out.println(y);
System.out.println(yy);
}
}
class player implements Comparable<player> {
int i, skl;
public player() {
i = 0;
skl = 0;
}
@Override
public int compareTo(player o) {
// TODO Auto-generated method stub
return skl - o.skl;
}
} | Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | d648e7b722a5bfae3e89d7c9f47dc825 | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main{
// split de array
public static int[] atoi(String cad) {
String read[] = cad.split(" ");
int res[] = new int[ read.length ];
for (int i = 0; i < read.length; i++) {
res[i] = Integer.parseInt(read[i]);
}
return res;
}
// split de String
public static String[] atos(String cad) {
return cad.split(" ");
}
// parsing de String a int
public static int parseo(String cad, int index) {
return Integer.parseInt(cad.split(" ")[index]);
}
// memory status
static String memoryStatus() {
return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/"
+ (Runtime.getRuntime().totalMemory() >> 20) + " MB";
}
// imprimir array
static void printArrayInt(int[] array) {
if (array == null || array.length == 0)
return;
for (int i = 0; i < array.length; i++) {
if (i > 0)
System.out.print(" ");
System.out.print(array[i]);
}
System.out.println();
}
// impresion de datos
static void print(Object... obj) {
for (int i = 0; i < obj.length; i++) {
if (i != 0)
System.out.print(" ");
System.out.print(obj[i]);
}
System.out.println();
}
public static int dif;
public static nums arr[];
public static class nums implements Comparable<nums> {
int num;
int index;
public nums(int num, int index) {
this.num = num;
this.index = index;
}
@Override
public int compareTo(nums o) {
if (this.num < o.num)
return -1;
else if (this.num > o.num)
return 1;
return 0;
}
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = in.readLine();
int n = Integer.parseInt(line);
arr = new nums[ n ];
String c[] = in.readLine().split(" ");
for (int i = 0; i < c.length; i++) {
arr[i] = new nums(Integer.parseInt(c[i]), i + 1);
}
Arrays.sort(arr);
StringBuilder br1 = new StringBuilder();
StringBuilder br2 = new StringBuilder();
br1.append(arr[arr.length - 2].index);
br2.append(arr[arr.length - 1].index);
int sum1 = 1;
int sum2 = 1;
for (int i = arr.length - 3; i >= 0; i--) {
if (sum2 <= sum1) {
br2.append(" " + arr[i].index);
sum2++;
} else {
br1.append(" " + arr[i].index + " ");
sum1++;
}
}
System.out.println(sum2);
System.out.println(br2);
System.out.println(sum1);
System.out.println(br1);
}
}
| Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | 909e6af7c9bfcc4e7110cb9c1d0ec399 | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.util.List;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nguyen Trung Hieu - [email protected]
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int[] skill = IOUtils.readIntArray(in, count);
Integer[] order = ListUtils.order(Array.wrap(skill));
int delta = 0;
List<Integer> first = new ArrayList<Integer>();
List<Integer> second = new ArrayList<Integer>();
for (int i = 0; i + 1 < count; i += 2){
if (delta >= 0){
first.add(order[i] + 1);
second.add(order[i + 1] + 1);
delta += skill[order[i]] - skill[order[i + 1]];
}
else {
first.add(order[i + 1] + 1);
second.add(order[i] + 1);
delta -= skill[order[i]] - skill[order[i + 1]];
}
}
if (count % 2 == 1) {
if (delta >= 0)
second.add(order[count - 1] + 1);
else
first.add(order[count - 1] + 1);
}
out.printLine(first.size());
out.printLine(first.toArray());
out.printLine(second.size());
out.printLine(second.toArray());
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
class ListUtils {
public static Integer[] order(final List<? extends Comparable<?>>...sequences) {
return ArrayUtils.order(sequences[0].size(), new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
for (List<? extends Comparable> sequence : sequences) {
//noinspection unchecked
int value = sequence.get(o1).compareTo(sequence.get(o2));
if (value != 0)
return value;
}
return 0;
}
});
}
}
abstract class Array<T> extends AbstractList<T> {
public static List<Integer> wrap(int...array) {
return new IntArray(array);
}
protected static class IntArray extends Array<Integer> {
protected final int[] array;
protected IntArray(int[] array) {
this.array = array;
}
public int size() {
return array.length;
}
public Integer get(int index) {
return array[index];
}
public Integer set(int index, Integer value) {
int result = array[index];
array[index] = value;
return result;
}
}
}
class ArrayUtils {
public static Integer[] order(int size, Comparator<Integer> comparator) {
Integer[] order = generateOrder(size);
Arrays.sort(order, comparator);
return order;
}
private static Integer[] generateOrder(int size) {
Integer[] order = new Integer[size];
for (int i = 0; i < size; i++)
order[i] = i;
return order;
}
}
| Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | 2e33669caad4a108a7f3f7669620e4da | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.awt.Point;
import java.util.*;
public class Main {
public static void main (String [] args){
Scanner in = new Scanner(System.in);
int n =in.nextInt();
Point sum1=new Point(0,0);
Point sum2=new Point(0,0);
Point array[]=new Point[n];
for(int i=0;i<n;i++){
array[i]=new Point (in.nextInt(),i+1);
}
Arrays.sort(array,new solver());
for(int i=n-1;i>=0;i--){
if(i%2==0){
sum1.y+=1;
sum1.x+=array[i].x;
}
if(i%2==1){
sum2.y+=1;
sum2.x+=array[i].x;
}
}
System.out.println(sum1.y);
for(int i=n-1;i>=0;i--){
if(i%2==0)
System.out.print(array[i].y + " ");
}
System.out.println();
System.out.println(sum2.y);
for(int i=n-1;i>=0;i--){
if(i%2==1)
System.out.print(array[i].y + " ");
}
}
static class solver implements Comparator<Point>{
public int compare(Point a,Point b){
return a.x-b.x;
}
}
} | Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | 4b2e141b6f1d4904a6da51ae06c88ae1 | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine().trim());
String[] val = reader.readLine().trim().split(" ");
Player[] players = new Player[n];
for (int i = 0; i < n; i++) {
players[i] = new Player(i + 1, Integer.parseInt(val[i]));
}
Arrays.sort(players);
int sumFirstTeam = 0;
int sumSecondTeam = 0;
List<Integer> firstTeam = new ArrayList<Integer>(n);
List<Integer> secondTeam = new ArrayList<Integer>(n);
int index = 0;
while (true) {
if (index == n) {
break;
}
Player current = players[index];
if (sumFirstTeam < sumSecondTeam) {
sumFirstTeam += current.getSkill();
firstTeam.add(current.getId());
index++;
if (index == n) {
break;
}
current = players[index];
sumSecondTeam += current.getSkill();
secondTeam.add(current.getId());
index++;
} else {
sumSecondTeam += current.getSkill();
secondTeam.add(current.getId());
index++;
if (index == n) {
break;
}
current = players[index];
sumFirstTeam += current.getSkill();
firstTeam.add(current.getId());
index++;
}
}
System.out.println(firstTeam.size());
System.out.println(toString(firstTeam));
System.out.println(secondTeam.size());
System.out.println(toString(secondTeam));
}
private static String toString(List<Integer> list) {
StringBuilder builder = new StringBuilder();
int size = list.size();
for (int i = 0; i < size; i++) {
builder.append(list.get(i));
if (i != (size - 1)) {
builder.append(" ");
}
}
return builder.toString();
}
public static class Player implements Comparable<Player> {
private int id;
private int skill;
public Player(int id, int skill) {
this.id = id;
this.skill = skill;
}
public int getId() {
return id;
}
public int getSkill() {
return skill;
}
@Override
public int compareTo(Player other) {
if (skill < other.getSkill()) {
return 1;
} else if (skill > other.getSkill()) {
return -1;
} else {
return id < other.getId() ? -1 : 1;
}
}
}
}
| Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | 7509c87416625da1f00e3f3a93f2d364 | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | //package acc;
import java.util.*;
public class ACC {
//************Main*****************//
public static void main(String[] args)
{
Scanner in=new Scanner (System.in);
int n=in.nextInt();
Pair[]arr=new Pair[n];
List<Integer> l1=new ArrayList<>();
List<Integer> l2=new ArrayList<>();
for(int i=1;i<=n;i++){
arr[i-1]=new Pair(in.nextInt(),i);
}
Arrays.sort(arr);
boolean a=true;
for(int i=0;i<n;i++){
if(a){
l1.add(arr[i].y);
a=false;
}
else {
l2.add(arr[i].y);
a=true;
}
}
System.out.println(l1.size());
for(int i=0;i<l1.size();i++){
if(i!=0) System.out.print(" ");
System.out.print(l1.get(i));
}
System.out.println();
System.out.println(l2.size());
for(int i=0;i<l2.size();i++){
if(i!=0) System.out.print(" ");
System.out.print(l2.get(i));
}
}
}
class Pair implements Comparable<Pair>{
int x,y;
public Pair(int X,int Y){
x=X;
y=Y;
}
@Override
public int compareTo(Pair p){
return x-p.x;
}
} | Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | a647a8fb7aa157ce1b24ba894025407b | train_000.jsonl | 1328886000 | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class hals {
static class node{
int val,ind;
public node(int x,int y){
ind = x;
val=y;
}
}
static class comparer implements Comparator<node>{
public int compare(node n1,node n2){
if(n1.val>n2.val)
return -1;
else if(n1.val<n2.val)
return 1;
return 0;
}
}
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Comparator<node> comp = new comparer();
PriorityQueue<node> q = new PriorityQueue<node>(n,comp);
String[] in = br.readLine().split(" ");
for(int i=0;i<n;i++){
q.add(new node(i+1,Integer.parseInt(in[i])));
}
ArrayList<Integer> team1 = new ArrayList<Integer>();
ArrayList<Integer> team2 = new ArrayList<Integer>();
int temp = 1;
while(!q.isEmpty()){
if(temp>0){
team1.add(q.poll().ind);
temp*=-1;
}
else{
team2.add(q.poll().ind);
temp*=-1;
}
}
System.out.println(team1.size());
for(int i=0;i<team1.size();i++)
System.out.print(team1.get(i)+" ");
System.out.println();
System.out.println(team2.size());
for(int i=0;i<team2.size();i++)
System.out.print(team2.get(i)+" ");
System.out.println();
}
} | Java | ["3\n1 2 1", "5\n2 3 3 1 1"] | 1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 0937a7e2f912fc094cc4275fd47cd457 | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | 1,500 | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | standard output | |
PASSED | 87f133d83eebc6baf6f04501e2f8f73c | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String number = in.readLine();
StringBuilder palNumber = new StringBuilder(number);
for (int i = number.length()-1 ; i >= 0; i--) {
palNumber.append(number.charAt(i));
}
System.out.println(palNumber);
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | fa031bc09946bfef5553375c7c3dedbc | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String n = in.readLine();
StringBuilder sb = new StringBuilder(n);
for (int i = n.length()-1 ; i >= 0; i--) {
sb.append(n.charAt(i));
}
System.out.println(sb);
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 2dccd31f9f5abf5355bfffe89adc60e5 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main (String [] args) throws IOException {
BufferedReader bf = new BufferedReader (new InputStreamReader(System.in));;
String str = bf.readLine() ;
StringBuilder N = new StringBuilder(str);
for (int i = str.length()-1 ; i >=0 ; i--) {
N.append(str.charAt(i));
}
System.out.println(N);
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 5f7fad02ff25f096be899ab095d620b8 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String number = in.readLine();
StringBuilder palNumber = new StringBuilder(number);
int i = number.length()-1;
for ( ; i >= 0; i--) {
palNumber.append(number.charAt(i));
}
System.out.println(palNumber);
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 620171a886de32511877e9ad01696ccb | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.Scanner;
public class ProbB {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String stuff = scan.nextLine();
stuff += new StringBuilder(stuff).reverse().toString();
System.out.println(stuff);
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 413222c09ce6de63de4beae3fba2fd0f | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.Scanner;
public class palindrome {
public static void main(String[] args) {
//
Scanner s = new Scanner(System.in);
String input = s.nextLine();
StringBuilder pal = new StringBuilder(input);
int i = 11;
System.out.println(pal.toString() + "" + pal.reverse());
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 2fc4799368b79354469ed5258fdcebd3 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.Scanner;
public class palindrome {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
StringBuilder pal = new StringBuilder(input);
int i = 11;
System.out.println(pal.toString() + "" + pal.reverse());
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 2879656ec4819e9c2457d73a9cd56435 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.*;
public class EffectiveApproach {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder(sc.next());
StringBuilder reversedString = new StringBuilder(stringBuilder);
reversedString.reverse();
stringBuilder.append(reversedString);
System.out.println(stringBuilder);
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | ac9c6d9e420ce98291e825bb262465e2 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
Scanner a =new Scanner(System.in);
String n = a.next();
System.out.print(n);
for (int i = n.length()-1; i >=0; i--) {
System.out.print(n.charAt(i));
}
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | e7015b37833f992717f4ba395bdde919 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String w = br.readLine();
if (w.length() == 1 && w.charAt(0) == 1) {
System.out.println(1);
} else {
StringBuilder bb = new StringBuilder();
bb.append(w);
bb.reverse();
bb.toString();
w = w + bb;
System.out.println(w);
}
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 1698fe7f09696f5b9b0594e03718f4dd | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
public class _360_B_ {
static String a;
public static void readData() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
a = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// char[] try1= a.toCharArray();
StringBuilder b = new StringBuilder();
b.append(a);
b=b.reverse();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
out.println(a+b);
out.close();
}
public static void main (String args[]) {
readData();
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 85eafcf5df79b858b3864babff6ed69e | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.Scanner;
public class Problem688B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String n = sc.next();
System.out.println(n + "" + new StringBuilder(n).reverse().toString());
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | d1ac8b70f2955c2f082c256f78bc2ba5 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.Scanner;
/*
<a href="https://codeforces.com/problemset/problem/688/B"/>
*/
public class Problem688B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder number = new StringBuilder(sc.next()); //because it's mutable and strings are immutable
System.out.println(number.toString()+""+number.reverse());
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 38c76f558070801be31a4e87dc3f6ddc | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
String s2 = new StringBuilder(s).reverse().toString();
System.out.print(s);
System.out.println(s2);
sc.close();
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 5d09468baa2a54430e301732ff87b208 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
String s2 = s + new StringBuilder(s).reverse().toString();
System.out.println(s2);
sc.close();
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 80cfd1d80e6ebf33b53d1ce4bf8d7251 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.*;
public class Main2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
String new1 = new StringBuilder(s).reverse().toString();
System.out.println(s + new1);
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 0985632516095b49c7703354be7dbdac | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class div360b
{
BufferedReader in;
PrintWriter ob;
StringTokenizer st;
public static void main(String[] args) throws IOException {
new div360b().run();
}
void run() throws IOException {
in=new BufferedReader(new InputStreamReader(System.in));
ob=new PrintWriter(System.out);
solve();
ob.flush();
}
void solve() throws IOException {
String s=ns();
StringBuffer sb=new StringBuffer(s);
sb=sb.reverse();
ob.println(s+sb.toString());
}
int ni() throws IOException {
return Integer.parseInt(nextToken());
}
long nl() throws IOException {
return Long.parseLong(nextToken());
}
String ns() throws IOException {
return nextToken();
}
String nextToken() throws IOException {
if(st==null || !st.hasMoreTokens())
st=new StringTokenizer(in.readLine());
return st.nextToken();
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 61a3248d62e870edb3fe3e6965b5d115 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.Scanner;
public class LovelyPalindromes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String n = input.next();
String Output=""+n;
StringBuilder sb=new StringBuilder(n);
sb.reverse();
Output+=sb.toString();
// for(int i=n.length()-1;i>=0;i--){
// Output+=n.charAt(i);
// }
System.out.println(Output);
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 0916ea3aae9ebc52b244b1a4bfbefb21 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes |
import java.util.Scanner;
/**
*
* @author Soroor
*/
public class JumpingBall {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String n=input.next();
String s=n+new StringBuilder(n).reverse().toString();
System.out.println(s);
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | fad270799a82ffadcf3d0b08a6d4bfea | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.*;
public class lovely_palindrom {
public static void main(String[]adasd) {
Scanner sc=new Scanner(System.in);
String s=sc.next();
System.out.print(s+""+new StringBuilder(s).reverse().toString());
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 6d5270eb356e9f316a8a63ef667ccd4f | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes |
import java.io.*;
import java.util.InputMismatchException;
public class CF688 {
static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test";
public static void main(String args[]) {
InputReader inputReader = Helper.readInput(Helper.Input.STD, filePath);
OutputWriter out = new OutputWriter(System.out);
String n = inputReader.readString();
StringBuilder stringBuilder = new StringBuilder();
StringBuilder reversed = new StringBuilder();
stringBuilder.append(n);
reversed.append(stringBuilder);
out.printLine(stringBuilder.append(reversed.reverse()));
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static class Helper {
static InputReader inputReader = null;
static OutputWriter out = null;
public static enum Input {
FILE, STD
}
public static class Pair<K, V> {
public K key;
public V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return "( " + key + " , " + value + ")";
}
}
public static InputReader readInput(Enum type, String filePath) {
if (type == Input.FILE) {
try {
inputReader = new InputReader(new FileInputStream(new File(filePath)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else
inputReader = new InputReader(System.in);
return inputReader;
}
public static boolean validIndices(int r, int c, int n, int m) {
if (r >= 0 && c >= 0 && r < n && c < m) return true;
else return false;
}
}
private 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 int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
private 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]);
}
writer.flush();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
writer.flush();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 3256f6cf1ec90b72932139c24486d366 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes |
import java.io.*;
import java.util.InputMismatchException;
public class CF688 {
static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test";
public static void main(String args[]) {
InputReader inputReader = Helper.readInput(Helper.Input.STD, filePath);
OutputWriter out = new OutputWriter(System.out);
char[] n = inputReader.readString().toCharArray();
StringBuilder stringBuilder = new StringBuilder();
StringBuilder reversed = new StringBuilder();
stringBuilder.append(n);
reversed.append(stringBuilder);
out.printLine(stringBuilder.append(reversed.reverse()));
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static class Helper {
static InputReader inputReader = null;
static OutputWriter out = null;
public static enum Input {
FILE, STD
}
public static class Pair<K, V> {
public K key;
public V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return "( " + key + " , " + value + ")";
}
}
public static InputReader readInput(Enum type, String filePath) {
if (type == Input.FILE) {
try {
inputReader = new InputReader(new FileInputStream(new File(filePath)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else
inputReader = new InputReader(System.in);
return inputReader;
}
public static boolean validIndices(int r, int c, int n, int m) {
if (r >= 0 && c >= 0 && r < n && c < m) return true;
else return false;
}
}
private 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 int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
private 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]);
}
writer.flush();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
writer.flush();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 8b7f7e5f6f150dcc482a65bb06427277 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes |
import java.io.*;
import java.util.InputMismatchException;
public class CF688 {
static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test";
public static void main(String args[]) {
InputReader inputReader = Helper.readInput(Helper.Input.STD, filePath);
OutputWriter out = new OutputWriter(System.out);
String n = inputReader.readString();
StringBuilder stringBuilder = new StringBuilder(n);
StringBuilder reversed = new StringBuilder(n);
stringBuilder.append(reversed.reverse());
out.printLine(stringBuilder);
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static class Helper {
static InputReader inputReader = null;
static OutputWriter out = null;
public static enum Input {
FILE, STD
}
public static class Pair<K, V> {
public K key;
public V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return "( " + key + " , " + value + ")";
}
}
public static InputReader readInput(Enum type, String filePath) {
if (type == Input.FILE) {
try {
inputReader = new InputReader(new FileInputStream(new File(filePath)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else
inputReader = new InputReader(System.in);
return inputReader;
}
public static boolean validIndices(int r, int c, int n, int m) {
if (r >= 0 && c >= 0 && r < n && c < m) return true;
else return false;
}
}
private 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 int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
private 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]);
}
writer.flush();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
writer.flush();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | fa8568667475ed4c9169ecb36e10c0c7 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.util.*;
import java.io.*;
public class Lovely_Palindrome
{
public static void main(String args[]) throws Exception
{
BufferedReader f=new BufferedReader(new InputStreamReader(System.in));
String input=f.readLine();
StringBuilder a=new StringBuilder(input);
System.out.println(input+a.reverse().toString());
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 44860fa99403c71360188fb3653e33ac | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class C1Problem21 {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String s = bf.readLine();
StringBuffer r = new StringBuffer(s);
r.reverse();
System.out.print(s+r);
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 8d9761444e079b45d8992c01fc85cc6b | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
StringBuilder x = new StringBuilder(sc.next());
System.out.println(x.toString() + x.reverse().toString());
sc.close();
}
} | Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | e9004d7a8b6212a8026ab1c01a1265c6 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes | import java.io.*;
import java.util.*;
public class cf{
public static void main(String args[])
{
Scanner m=new Scanner(System.in);
String n=m.next();
StringBuilder n2=new StringBuilder(n);
n=n+n2.reverse().toString();
System.out.println(n);
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output | |
PASSED | 2f397765060c1c373bd0bf1287e2de68 | train_000.jsonl | 1467219900 | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | 256 megabytes |
import java.util.Scanner;
public class LOVELY_POLINDROME {
public static void main(String[] args)
{
Scanner scn=new Scanner(System.in);
String number=scn.nextLine();
String ans="";
ans+=number;
//for(int i=number.length()-1;i>=0;i--)
//ans+=number.charAt(i);
StringBuilder input1=new StringBuilder();
input1.append(number);
input1=input1.reverse();
ans+=input1;
System.out.println(ans);
}
}
| Java | ["1", "10"] | 1 second | ["11", "1001"] | NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001. | Java 8 | standard input | [
"constructive algorithms",
"math"
] | bcf75978c9ef6202293773cf533afadf | The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000). | 1,000 | Print the n-th even-length palindrome number. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.