exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
listlengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED
|
96b3eb00354d02c9fee505c222a9ef8b
|
train_000.jsonl
|
1526395500
|
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.The elevator has two commands: Go up or down one floor. The movement takes 1 second. Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1.You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
|
256 megabytes
|
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
public class C {
static BufferedReader br;
static StringTokenizer st;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
int n = readInt();
ArrayList<Inside> in = new ArrayList<Inside>();
Map<Inside, Integer> rev = new HashMap<Inside, Integer>();
for(int a = -1; a <= 8; a++) {
for(int b = -1; b <= 8; b++) {
for(int c = -1; c <= 8; c++) {
for(int d = -1; d <= 8; d++) {
in.add(new Inside(a, b, c, d));
rev.put(new Inside(a, b, c, d), in.size()-1);
}
}
}
}
Map<State, Integer> dp = new HashMap<State, Integer>();
int[] lhs = new int[n];
int[] rhs = new int[n];
for(int i = 0; i < n; i++) {
lhs[i] = readInt()-1;
rhs[i] = readInt()-1;
}
LinkedList<State> q = new LinkedList<State>();
dp.put(new State(0, 0, 0), 0);
q.add(new State(0, 0, 0));
Inside now = new Inside(-1,-1,-1,-1);
for(int i = 0; i < 4 && i < n && lhs[i] == 0; i++) {
now.a = rhs[i];
now.sort();
dp.put(new State(1, 0, rev.get(now)), 0);
q.add(new State(1, 0, rev.get(now)));
}
while(!q.isEmpty()) {
State curr = q.removeFirst();
if(curr.idx == n && curr.mask == 0) {
pw.println(dp.get(curr) + 2*n);
break;
}
int nowDist = dp.get(curr);
for(int dir = -1; dir <= 1; dir += 2) {
int nextLoc = curr.loc + dir;
if(nextLoc < 0 || nextLoc >= 9) continue;
now = new Inside(in.get(curr.mask));
now.clean(nextLoc);
int nextIdx = curr.idx;
int nextMask = rev.get(now);
State key = new State(nextIdx, nextLoc, nextMask);
if(!dp.containsKey(key)) {
dp.put(key, 1 + nowDist);
q.add(key);
}
while(nextIdx < n && lhs[nextIdx] == nextLoc && now.a == -1) {
now.a = rhs[nextIdx];
nextIdx++;
now.sort();
nextMask = rev.get(now);
key = new State(nextIdx, nextLoc, nextMask);
if(!dp.containsKey(key)) {
dp.put(key, 1 + nowDist);
q.add(key);
}
}
}
}
}
pw.close();
}
static class Inside {
public int a, b, c, d;
public Inside(Inside i) {
this(i.a,i.b,i.c,i.d);
}
@Override
public String toString() {
return "Inside [a=" + a + ", b=" + b + ", c=" + c + ", d=" + d + "]";
}
public Inside(int a, int b, int c, int d) {
super();
this.a = a;
this.b = b;
this.c = c;
this.d = d;
sort();
}
public void clean(int idx) {
if(idx==a) a=-1;
if(idx==b) b=-1;
if(idx==c) c=-1;
if(idx==d) d=-1;
sort();
}
public void sort() {
if(d<c) {
d^=c;
c^=d;
d^=c;
}
if(c<b) {
c^=b;
b^=c;
c^=b;
}
if(b<a) {
b^=a;
a^=b;
b^=a;
}
if(d<c) {
d^=c;
c^=d;
d^=c;
}
if(c<b) {
c^=b;
b^=c;
c^=b;
}
if(b<a) {
b^=a;
a^=b;
b^=a;
}
if(d<c) {
d^=c;
c^=d;
d^=c;
}
if(c<b) {
c^=b;
b^=c;
c^=b;
}
if(b<a) {
b^=a;
a^=b;
b^=a;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + a;
result = prime * result + b;
result = prime * result + c;
result = prime * result + d;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Inside other = (Inside) obj;
if (a != other.a)
return false;
if (b != other.b)
return false;
if (c != other.c)
return false;
if (d != other.d)
return false;
return true;
}
}
static class State {
public int idx, loc, mask;
@Override
public String toString() {
return "State [idx=" + idx + ", loc=" + loc + ", mask=" + mask + "]";
}
public State(int idx, int loc, int mask) {
super();
this.idx = idx;
this.loc = loc;
this.mask = mask;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + idx;
result = prime * result + loc;
result = prime * result + mask;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
State other = (State) obj;
if (idx != other.idx)
return false;
if (loc != other.loc)
return false;
if (mask != other.mask)
return false;
return true;
}
}
public static void exitImmediately() {
pw.close();
System.exit(0);
}
public static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
public static String nextLine() throws IOException {
st = null;
if(!br.ready()) {
exitImmediately();
}
return br.readLine();
}
public static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
|
Java
|
["2\n3 5\n5 3", "2\n5 3\n3 5"]
|
3 seconds
|
["10", "12"]
|
Note Explaination for the first sample t = 0 t = 2 t = 3 t = 5 t = 6 t = 7 t = 9 t = 10
|
Java 8
|
standard input
|
[
"dp",
"graphs",
"shortest paths"
] |
f6be5319ad3733d07a8ffd089fc44c71
|
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees. The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator.
| 2,400 |
Print a single integer — the minimal possible time in seconds.
|
standard output
| |
PASSED
|
95f7c9d9dd9d99077e4adadd0a6062f3
|
train_000.jsonl
|
1526395500
|
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.The elevator has two commands: Go up or down one floor. The movement takes 1 second. Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1.You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.math.*;
public class C {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/c.in"))));
/**/
int n = sc.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
HashMap<Long, Integer> dp = new HashMap<Long, Integer>();
PriorityQueue<Long> pq = new PriorityQueue<>();
pq.add(1L<<16);
dp.put(1L<<16, 0);
while (!pq.isEmpty()) {
long rem = pq.poll();
int dist = (int)(rem>>>32);
if (dist != dp.get(rem<<32>>>32))
continue;
int emp = (int)(rem<<32>>>52);
int rest = (int)(rem<<44>>>44);
int floor = rest>>>16;
int[] dests = {rest<<16>>>28, rest<<20>>>28, rest<<24>>>28, rest<<28>>>28};
if (dests[0]==0&&emp<n) {
int[] nde = dests.clone();
for (int i = 0; i < 3; i++) {
if (nde[i]==a[emp])
nde[i] = 0;
}
int nemp = emp;
while (nde[0]==0&&nemp<n&&a[nemp]==a[emp]) {
nde[0] = b[nemp++];
Arrays.sort(nde);
}
int ndi = dist+Math.abs(a[emp]-floor);
long key = (long)(nemp<<20)+(a[emp]<<16)+(nde[0]<<12)+(nde[1]<<8)+(nde[2]<<4)+(nde[3]);
if (!dp.containsKey(key) || ndi < dp.get(key)) {
dp.put(key, ndi);
pq.add((((long)ndi)<<32)+key);
}
}
for (int i = 0; i < 4; i++) {
if (dests[i]==0)
continue;
int nfl = dests[i];
int[] nde = dests.clone();
for (int j = i; j < 4; j++) {
if (nde[i]==nfl)
nde[i] = 0;
else
break;
}
Arrays.sort(nde);
int ndi = dist+Math.abs(nfl-floor);
long key = (long)(emp<<20)+(nfl<<16)+(nde[0]<<12)+(nde[1]<<8)+(nde[2]<<4)+(nde[3]);
if (!dp.containsKey(key) || ndi < dp.get(key)) {
dp.put(key, ndi);
pq.add((((long)ndi)<<32)+key);
}
}
}
int min = Integer.MAX_VALUE;
for (int i = 1; i < 10; i++) {
if (dp.containsKey((long)(n<<20)+(i<<16)))
min = Math.min(min, dp.get((long)(n<<20)+(i<<16)));
}
System.out.println(min+2*n);
}
}
|
Java
|
["2\n3 5\n5 3", "2\n5 3\n3 5"]
|
3 seconds
|
["10", "12"]
|
Note Explaination for the first sample t = 0 t = 2 t = 3 t = 5 t = 6 t = 7 t = 9 t = 10
|
Java 8
|
standard input
|
[
"dp",
"graphs",
"shortest paths"
] |
f6be5319ad3733d07a8ffd089fc44c71
|
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees. The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator.
| 2,400 |
Print a single integer — the minimal possible time in seconds.
|
standard output
| |
PASSED
|
0c6beb762d6d35351276ca3c2b32dbfb
|
train_000.jsonl
|
1526395500
|
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.The elevator has two commands: Go up or down one floor. The movement takes 1 second. Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1.You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Egor Kulikov ([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);
CLift solver = new CLift();
solver.solve(1, in, out);
out.close();
}
static class CLift {
int[] a;
int[] b;
int[][][][][][] result;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
a = new int[n];
b = new int[n];
in.readIntArrays(a, b);
result = new int[9][n + 1][10][][][];
for (int i = 0; i < 9; i++) {
for (int j = 0; j <= n; j++) {
for (int k = 0; k < 10; k++) {
result[i][j][k] = new int[k + 1][][];
for (int l = 0; l <= k; l++) {
result[i][j][k][l] = new int[l + 1][];
for (int m = 0; m <= l; m++) {
result[i][j][k][l][m] = ArrayUtils.createArray(m + 1, -1);
}
}
}
}
}
out.printLine(go(0, 0, 0, 0, 0, 0) + 2 * n);
}
private int go(int floor, int id, int e1, int e2, int e3, int e4) {
if (result[floor][id][e1][e2][e3][e4] != -1) {
return result[floor][id][e1][e2][e3][e4];
}
if (id == a.length && e1 == 0) {
return result[floor][id][e1][e2][e3][e4] = 0;
}
result[floor][id][e1][e2][e3][e4] = Integer.MAX_VALUE;
if (e1 != 0) {
result[floor][id][e1][e2][e3][e4] = Math.min(result[floor][id][e1][e2][e3][e4], go(e1 - 1, id, e2, e3,
e4, 0) + Math.abs(floor + 1 - e1));
if (e2 != 0) {
result[floor][id][e1][e2][e3][e4] =
Math.min(result[floor][id][e1][e2][e3][e4], go(e2 - 1, id, e1, e3,
e4, 0) + Math.abs(floor + 1 - e2));
if (e3 != 0) {
result[floor][id][e1][e2][e3][e4] = Math.min(result[floor][id][e1][e2][e3][e4], go(e3 - 1, id,
e1, e2, e4, 0) + Math.abs(floor + 1 - e3));
if (e4 != 0) {
result[floor][id][e1][e2][e3][e4] =
Math.min(result[floor][id][e1][e2][e3][e4], go(e4 - 1, id,
e1, e2, e3, 0) + Math.abs(floor + 1 - e4));
}
}
}
}
if (id != a.length && e4 == 0) {
if (b[id] >= e1) {
result[floor][id][e1][e2][e3][e4] =
Math.min(result[floor][id][e1][e2][e3][e4], go(a[id] - 1, id + 1,
b[id], e1, e2, e3) + Math.abs(floor + 1 - a[id]));
} else if (b[id] >= e2) {
result[floor][id][e1][e2][e3][e4] =
Math.min(result[floor][id][e1][e2][e3][e4], go(a[id] - 1, id + 1,
e1, b[id], e2, e3) + Math.abs(floor + 1 - a[id]));
} else if (b[id] >= e3) {
result[floor][id][e1][e2][e3][e4] =
Math.min(result[floor][id][e1][e2][e3][e4], go(a[id] - 1, id + 1,
e1, e2, b[id], e3) + Math.abs(floor + 1 - a[id]));
} else {
result[floor][id][e1][e2][e3][e4] =
Math.min(result[floor][id][e1][e2][e3][e4], go(a[id] - 1, id + 1,
e1, e2, e3, b[id]) + Math.abs(floor + 1 - a[id]));
}
}
return result[floor][id][e1][e2][e3][e4];
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
static class ArrayUtils {
public static int[] createArray(int count, int value) {
int[] array = new int[count];
Arrays.fill(array, value);
return array;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["2\n3 5\n5 3", "2\n5 3\n3 5"]
|
3 seconds
|
["10", "12"]
|
Note Explaination for the first sample t = 0 t = 2 t = 3 t = 5 t = 6 t = 7 t = 9 t = 10
|
Java 8
|
standard input
|
[
"dp",
"graphs",
"shortest paths"
] |
f6be5319ad3733d07a8ffd089fc44c71
|
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees. The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator.
| 2,400 |
Print a single integer — the minimal possible time in seconds.
|
standard output
| |
PASSED
|
b2c71dc24170f8f377084a0dfcee7fc0
|
train_000.jsonl
|
1526395500
|
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.The elevator has two commands: Go up or down one floor. The movement takes 1 second. Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1.You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
|
256 megabytes
|
//package com.company;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("Test.in"));
PrintWriter pw = new PrintWriter(System.out);
// PrintWriter pw = new PrintWriter(new FileOutputStream("Test.out"));
// PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in"));
// pw.println(5000);
// for (int i = 0; i < 5000; i++) {
// pw.print(i + " ");
// }
// pw.println();
// pw.println(100000);
// for (int i = 0; i < 100000; i++) {
// pw.println(1 + " " + 5000);
// }
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
// System.out.println("Memory increased:" + (usedMemoryAfter-usedMemoryBefore) / 1000000 );
// System.out.println("Time used: " + (TIME_END - TIME_START) + ".");
}
public static class Task {
public class Config{
int[] toStop;
int time;
int in;
Config(){
toStop = new int[9];
time = 0;
in = 0;
}
Config copyOf(){
Config cp = new Config();
cp.time = time;
cp.in = in;
cp.toStop = Arrays.copyOf(toStop, 9);
return cp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Config)) return false;
Config config = (Config) o;
return Arrays.equals(toStop, config.toStop);
}
@Override
public int hashCode() {
return Arrays.hashCode(toStop);
}
}
public void unlabel(Config cf, int from, int to){
if (from > to) {
for (int i = from; i >= to; i--) {
cf.in -= cf.toStop[i];
cf.toStop[i] = 0;
}
cf.time += from - to;
} else {
for (int i = from; i <= to; i++) {
cf.in -= cf.toStop[i];
cf.toStop[i] = 0;
}
cf.time += to - from;
}
}
public int minNeed(Config cf, int at) {
if (cf.in == 0) return 0;
int minLevel = 10, maxLevel = 0;
for (int i = 0; i < 9; i++) {
if (cf.toStop[i] != 0) {
minLevel = Math.min(minLevel, i);
maxLevel = Math.max(maxLevel, i);
}
}
int moveDown = minLevel < at ? at - minLevel : 0;
int moveUp = maxLevel > at ? maxLevel - at: 0;
return Math.min(moveDown, moveUp) + moveDown + moveUp;
}
public void configure(int at, int next, Config config, Map<Config, Config> all) {
if (config.in < 4) {
Config init = config.copyOf();
unlabel(init, at, next);
if (all.containsKey(init)) {
all.get(init).time = Math.min(all.get(init).time, init.time);
} else {
all.put(init, init);
}
}
Config cofUp = config.copyOf();
for (int i = at; i < 9; i++) {
if (cofUp.toStop[i] != 0) {
cofUp.in -= cofUp.toStop[i];
cofUp.toStop[i] = 0;
Config toAdd = cofUp.copyOf();
unlabel(toAdd, i, next);
if (all.containsKey(toAdd)) {
all.get(toAdd).time = Math.min(all.get(toAdd).time, toAdd.time);
} else {
all.put(toAdd, toAdd);
}
}
cofUp.time++;
}
Config cofDown = config.copyOf();
for (int i = at; i >= 0; i--) {
if (cofDown.toStop[i] != 0) {
cofDown.in -= cofDown.toStop[i];
cofDown.toStop[i] = 0;
Config toAdd = cofDown.copyOf();
unlabel(toAdd, i, next);
if (all.containsKey(toAdd)) {
all.get(toAdd).time = Math.min(all.get(toAdd).time, toAdd.time);
} else {
all.put(toAdd, toAdd);
}
}
cofDown.time++;
}
return;
}
public void solve(Scanner sc, PrintWriter pw) throws IOException {
Map<Config, Config> all = new HashMap<>();
int n = sc.nextInt();
Config inital = new Config();
all.put(inital, inital);
int[] from = new int[n + 1];
int[] to = new int[n + 1];
for (int i = 0; i < n; i++) {
from[i] = sc.nextInt() - 1;
to[i] = sc.nextInt() - 1;
}
from[n] = from[n - 1];
to[n] = to[n - 1];
inital.time += from[0];
for (int i = 0; i < n - 1; i++) {
Map<Config, Config> next = new HashMap<>();
for(Config conf: all.keySet()) {
conf.toStop[to[i]]++;
conf.in++;
configure(from[i], from[i + 1], conf, next);
}
all = next;
}
int minTime = Integer.MAX_VALUE;
for(Config conf: all.keySet()) {
conf.toStop[to[n - 1]]++;
conf.in++;
int res = minNeed(conf, from[n - 1]) + conf.time;
minTime = Math.min(minTime, res);
}
pw.println(minTime + 2 * n);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader s) throws FileNotFoundException {br = new BufferedReader(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 { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
}
|
Java
|
["2\n3 5\n5 3", "2\n5 3\n3 5"]
|
3 seconds
|
["10", "12"]
|
Note Explaination for the first sample t = 0 t = 2 t = 3 t = 5 t = 6 t = 7 t = 9 t = 10
|
Java 8
|
standard input
|
[
"dp",
"graphs",
"shortest paths"
] |
f6be5319ad3733d07a8ffd089fc44c71
|
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees. The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator.
| 2,400 |
Print a single integer — the minimal possible time in seconds.
|
standard output
| |
PASSED
|
9be20536c808c745f13ebf002251cbef
|
train_000.jsonl
|
1526395500
|
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.The elevator has two commands: Go up or down one floor. The movement takes 1 second. Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1.You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
|
256 megabytes
|
import java.util.Scanner;
import java.util.Arrays;
public class Test7 {
int maxn = 3000;
//floors: 0 - 8
//9 - empty
//front: the next employee
//the importance of a: if a < 9 then the lift is full; else a - 9 means the floor the elevator is on
public static int hash(int front, int a, int b, int c, int d) {
if (a < 9) return (front * 2500 + d + (c * (c + 1)) / 2 + (b * (b + 1) * (b + 2)) / 6 + (a * (a + 1) * (a + 2) * (a + 3)) / 24);
return front * 2500 + d + (c * (c + 1)) / 2 + (b * (b + 1) * (b + 2)) / 6 + (9 * 10 * 11 * 12) / 24 + 1 + 221 * (a - 9);
}
public static void main(String Args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] st = new int[n];
int[] ed = new int[n];
for (int i = 0; i < n; i++) {
st[i] = sc.nextInt() - 1;
ed[i] = sc.nextInt() - 1;
}
int sz = 6000000;
int[] ans = new int[sz];
int inf = 10000000;
for (int i = 0; i < sz; i++) ans[i] = inf;
ans[hash(0, 9, 9, 9, 9)] = 0;
int[] ep = new int[4];
int tp = 0; //current floor
int ft = 0; //front
int rm = 0; //room in elevator
int t = 0;
int[] ord = new int[4];
for (int front = 0; front <= n; front++) {
for (int a = 0; a < 9; a++)
for (int b = 0; b <= Math.min(a, 9); b++)
for (int c = 0; c <= b; c++)
for (int d = 0; d <= c; d++) {
ft = front;
//current stop of lift
if (a < 9 && front > 0) {
tp = st[front - 1];
}
else tp = a - 9;
//conversion
t = ans[hash(front,a,b,c,d)];
if (t < inf) {
// System.out.print(front);
// System.out.print(a);
// System.out.print(b);
//
// System.out.print(c);
// System.out.print(d);
// System.out.println(t);
rm = 0;
if (a < 9) {
ep[0] = 9 + a; //goes to a
ord[rm] = 0;
rm++;
t += Math.abs(tp - a);
t++;
if (b == a) {
ep[1] = 9;
ord[rm] = 1;
rm++;
t++;
}
else ep[1] = b;
if (c == a) {
ep[2] = 9;
ord[rm] = 2;
rm++;
t++;
}
else ep[2] = c;
if (d == a) {
ep[3] = 9;
ord[rm] = 3;
rm++;
t++;
}
else ep[3] = d;
//people enter
while (rm > 0 && ft < n && st[ft] == a) {
rm--;
ep[ord[rm]] = ed[ft];
ft++;
t++;
}
Arrays.sort(ep);
ans[hash(ft, ep[3], ep[2], ep[1], ep[0])] = Math.min(ans[hash(ft, ep[3], ep[2], ep[1], ep[0])], t);
}
else if (front < n) {
//goes to next person
ord[0] = 0;
rm = 1;
if (b == 9) {
ord[rm] = 1;
rm++;
}
if (c == 9) {
ord[rm] = 2;
rm++;
}
if (d == 9) {
ord[rm] = 3;
rm++;
}
ep[0] = 9 + st[front];
if (b == st[front]) {
ord[rm] = 1;
rm++;
t++;
ep[1] = 9;
}
else ep[1] = b;
if (c == st[front]) {
ord[rm] = 2;
rm++;
t++;
ep[2] = 9;
}
else ep[2] = c;
if (d == st[front]) {
ord[rm] = 3;
rm++;
t++;
ep[3] = 9;
}
else ep[3] = d;
t+= Math.abs(tp - st[front]);
while (rm > 0 && ft < n && st[ft] == st[front]){
rm--;
ep[ord[rm]] = ed[ft];
ft++;
t++;
}
Arrays.sort(ep);
ans[hash(ft, ep[3], ep[2], ep[1], ep[0])] = Math.min(ans[hash(ft, ep[3], ep[2], ep[1], ep[0])], t);
}
ft = front;
t = ans[hash(front,a,b,c,d)];
rm = 0;
if (b < 9 && b != a) {
ep[0] = 9 + b; //goes to b
ord[rm] = 0;
rm++;
t += Math.abs(tp - b);
t++;
ep[1] = Math.min(a, 9);
if (a >= 9) {
ord[rm] = 1;
rm++;
}
if (c == b) {
ep[2] = 9;
ord[rm] = 2;
rm++;
t++;
}
else ep[2] = c;
if (d == b) {
ep[3] = 9;
ord[rm] = 3;
rm++;
t++;
}
else ep[3] = d;
//people enter
while (rm > 0 && ft < n && st[ft] == b) {
rm--;
ep[ord[rm]] = ed[ft];
ft++;
t++;
}
Arrays.sort(ep);
ans[hash(ft, ep[3], ep[2], ep[1], ep[0])] = Math.min(ans[hash(ft, ep[3], ep[2], ep[1], ep[0])], t);
}
ft = front;
t = ans[hash(front,a,b,c,d)];
rm = 0;
if (c < 9 && c != a && c != b) {
ep[0] = 9 + c; //goes to c
ord[rm] = 0;
rm++;
t += Math.abs(tp - c);
t++;
ep[1] = b;
if (b == 9) {
ord[rm] = 1;
rm++;
}
ep[2] = Math.min(a, 9);
if (a >= 9) {
ord[rm] = 2;
rm++;
}
if (d == c) {
ep[3] = 9;
ord[rm] = 3;
rm++;
t++;
}
else ep[3] = d;
//people enter
while (rm > 0 && ft < n && st[ft] == c) {
rm--;
ep[ord[rm]] = ed[ft];
ft++;
t++;
}
Arrays.sort(ep);
ans[hash(ft, ep[3], ep[2], ep[1], ep[0])] = Math.min(ans[hash(ft, ep[3], ep[2], ep[1], ep[0])], t);
}
ft = front;
t = ans[hash(front,a,b,c,d)];
rm = 0;
if (d < 9 && d != a && d != b && d != c) {
ord[rm] = 0;
rm++;
ep[0] = 9 + d; //goes to d
t += Math.abs(tp - d);
t++;
ep[1] = b;
ep[2] = c;
if (b == 9) {
ord[rm] = 1;
rm++;
}
if (c == 9) {
ord[rm] = 2;
rm++;
}
ep[3] = Math.min(a, 9);
if (a >= 9) {
ord[rm] = 3;
rm++;
}
//people enter
while (rm > 0 && ft < n && st[ft] == d) {
rm--;
ep[ord[rm]] = ed[ft];
ft++;
t++;
}
Arrays.sort(ep);
ans[hash(ft, ep[3], ep[2], ep[1], ep[0])] = Math.min(ans[hash(ft, ep[3], ep[2], ep[1], ep[0])], t);
}
}
}
for (int b = 0; b <= 9; b++)
for (int c = 0; c <= b; c++)
for (int d = 0; d <= c; d++)
for (int a = 9; a < 18; a++){
ft = front;
//current stop of lift
if (a < 9 && front > 0) {
tp = st[front - 1];
}
else tp = a - 9;
//conversion
t = ans[hash(front,a,b,c,d)];
if (t < inf) {
// System.out.print(front);
// System.out.print(a);
// System.out.print(b);
//
// System.out.print(c);
// System.out.print(d);
// System.out.println(t);
rm = 0;
if (a < 9) {
ep[0] = 9 + a; //goes to a
ord[rm] = 0;
rm++;
t += Math.abs(tp - a);
t++;
if (b == a) {
ep[1] = 9;
ord[rm] = 1;
rm++;
t++;
}
else ep[1] = b;
if (c == a) {
ep[2] = 9;
ord[rm] = 2;
rm++;
t++;
}
else ep[2] = c;
if (d == a) {
ep[3] = 9;
ord[rm] = 3;
rm++;
t++;
}
else ep[3] = d;
//people enter
while (rm > 0 && ft < n && st[ft] == a) {
rm--;
ep[ord[rm]] = ed[ft];
ft++;
t++;
}
Arrays.sort(ep);
ans[hash(ft, ep[3], ep[2], ep[1], ep[0])] = Math.min(ans[hash(ft, ep[3], ep[2], ep[1], ep[0])], t);
}
else if (front < n) {
//goes to next person
ord[0] = 0;
rm = 1;
if (b == 9) {
ord[rm] = 1;
rm++;
}
if (c == 9) {
ord[rm] = 2;
rm++;
}
if (d == 9) {
ord[rm] = 3;
rm++;
}
ep[0] = 9 + st[front];
if (b == st[front]) {
ord[rm] = 1;
rm++;
t++;
ep[1] = 9;
}
else ep[1] = b;
if (c == st[front]) {
ord[rm] = 2;
rm++;
t++;
ep[2] = 9;
}
else ep[2] = c;
if (d == st[front]) {
ord[rm] = 3;
rm++;
t++;
ep[3] = 9;
}
else ep[3] = d;
t+= Math.abs(tp - st[front]);
while (rm > 0 && ft < n && st[ft] == st[front]){
rm--;
ep[ord[rm]] = ed[ft];
ft++;
t++;
}
Arrays.sort(ep);
ans[hash(ft, ep[3], ep[2], ep[1], ep[0])] = Math.min(ans[hash(ft, ep[3], ep[2], ep[1], ep[0])], t);
}
ft = front;
t = ans[hash(front,a,b,c,d)];
rm = 0;
if (b < 9 && b != a) {
ep[0] = 9 + b; //goes to b
ord[rm] = 0;
rm++;
t += Math.abs(tp - b);
t++;
ep[1] = Math.min(a, 9);
if (a >= 9) {
ord[rm] = 1;
rm++;
}
if (c == b) {
ep[2] = 9;
ord[rm] = 2;
rm++;
t++;
}
else ep[2] = c;
if (d == b) {
ep[3] = 9;
ord[rm] = 3;
rm++;
t++;
}
else ep[3] = d;
//people enter
while (rm > 0 && ft < n && st[ft] == b) {
rm--;
ep[ord[rm]] = ed[ft];
ft++;
t++;
}
Arrays.sort(ep);
ans[hash(ft, ep[3], ep[2], ep[1], ep[0])] = Math.min(ans[hash(ft, ep[3], ep[2], ep[1], ep[0])], t);
}
ft = front;
t = ans[hash(front,a,b,c,d)];
rm = 0;
if (c < 9 && c != a && c != b) {
ep[0] = 9 + c; //goes to c
ord[rm] = 0;
rm++;
t += Math.abs(tp - c);
t++;
ep[1] = b;
if (b == 9) {
ord[rm] = 1;
rm++;
}
ep[2] = Math.min(a, 9);
if (a >= 9) {
ord[rm] = 2;
rm++;
}
if (d == c) {
ep[3] = 9;
ord[rm] = 3;
rm++;
t++;
}
else ep[3] = d;
//people enter
while (rm > 0 && ft < n && st[ft] == c) {
rm--;
ep[ord[rm]] = ed[ft];
ft++;
t++;
}
Arrays.sort(ep);
ans[hash(ft, ep[3], ep[2], ep[1], ep[0])] = Math.min(ans[hash(ft, ep[3], ep[2], ep[1], ep[0])], t);
}
ft = front;
t = ans[hash(front,a,b,c,d)];
rm = 0;
if (d < 9 && d != a && d != b && d != c) {
ord[rm] = 0;
rm++;
ep[0] = 9 + d; //goes to d
t += Math.abs(tp - d);
t++;
ep[1] = b;
ep[2] = c;
if (b == 9) {
ord[rm] = 1;
rm++;
}
if (c == 9) {
ord[rm] = 2;
rm++;
}
ep[3] = Math.min(a, 9);
if (a >= 9) {
ord[rm] = 3;
rm++;
}
//people enter
while (rm > 0 && ft < n && st[ft] == d) {
rm--;
ep[ord[rm]] = ed[ft];
ft++;
t++;
}
Arrays.sort(ep);
ans[hash(ft, ep[3], ep[2], ep[1], ep[0])] = Math.min(ans[hash(ft, ep[3], ep[2], ep[1], ep[0])], t);
}
}
}
}
int ansmin = inf;
for (int j = 9; j < 18; j++) {
if (ans[hash(n, j, 9, 9, 9)] < ansmin) ansmin = ans[hash(n, j, 9, 9, 9)];
}
System.out.println(ansmin);
}
}
|
Java
|
["2\n3 5\n5 3", "2\n5 3\n3 5"]
|
3 seconds
|
["10", "12"]
|
Note Explaination for the first sample t = 0 t = 2 t = 3 t = 5 t = 6 t = 7 t = 9 t = 10
|
Java 8
|
standard input
|
[
"dp",
"graphs",
"shortest paths"
] |
f6be5319ad3733d07a8ffd089fc44c71
|
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees. The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator.
| 2,400 |
Print a single integer — the minimal possible time in seconds.
|
standard output
| |
PASSED
|
6c18cc2e21fb010c22c4fc18eea426ff
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Codeforces
{
public static void main(String args[])throws Exception
{
BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
String s[]=bu.readLine().split(" ");
int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]),i;
long a[]=new long[n];
for(i=0;i<n;i++)
{
s=bu.readLine().split(" ");
int ci=Integer.parseInt(s[0]),ti=Integer.parseInt(s[1]);
ci*=ti;
if(i!=0) a[i]=a[i-1]+ci;
else a[i]=ci;
}
int j=0;
s=bu.readLine().split(" ");
for(i=0;i<m;i++)
{
long v=Long.parseLong(s[i]);
for(;j<n;j++)
if(a[j]>=v) break;
sb.append(Math.min(j+1,n)+"\n");
}
System.out.print(sb);
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
38a74fccece57034182a94f02be49ca9
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.*;
import java.util.StringTokenizer;
public class TaskD {
static int n;
static int[] sum;
public static void main(String[] args) {
FastReader fs = new FastReader(System.in);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
n = fs.nextInt();
int m = fs.nextInt();
int[] c = new int[n];
int[] t = new int[n];
sum = new int[n];
int summ = 0;
for (int i = 0; i < n; i++) {
c[i] = fs.nextInt();
t[i] = fs.nextInt();
summ += c[i] * t[i];
sum[i] = summ;
}
int q=0;
int ans;
for (int i = 0; i < m; i++) {
q = fs.nextInt();
ans = search(q);
System.out.println(ans);
}
// fs.close();
}
private static int search(int q) {
int left = 0;
int right = n-1;
while (left < right) {
int mid = (right + left) >> 1;
if (sum[mid] < q) {
left = ++mid ;
} else {
right = mid;
}
}
return ++left;
}
static class FastReader {
BufferedReader reader;
StringTokenizer st;
FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
st = null;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
String nextLine() {
String s = null;
try {
s = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return next().charAt(0);
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
int i = 0;
while (i < n) {
arr[i++] = nextInt();
}
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
int i = 0;
while (i < n) {
arr[i++] = nextLong();
}
return arr;
}
int[] nextIntArrayOneBased(int n) {
int[] arr = new int[n + 1];
int i = 1;
while (i <= n) {
arr[i++] = nextInt();
}
return arr;
}
long[] nextLongArrayOneBased(int n) {
long[] arr = new long[n + 1];
int i = 1;
while (i <= n) {
arr[i++] = nextLong();
}
return arr;
}
void close() {
try {
reader.close();
} catch (IOException e) {
System.err.println("There's been an error trying closing the reader ");
e.printStackTrace();
}
}
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
d7391b20cb6105a68a70a89614f61dd6
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class TaskD2 {
static class Interval {
int start, end;
public Interval(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public String toString() {
return "Interval{" +
"start=" + start +
", end=" + end +
'}';
}
}
public static void solve(FastReader fs, PrintWriter pw) {
int n = fs.nextInt(), m = fs.nextInt();
int s = 1;
Interval[] intervals = new Interval[n];
for (int i = 0; i < n; i++) {
int a = fs.nextInt(), b = fs.nextInt();
intervals[i] = new Interval(s, s + a * b);
s += a * b;
}
for (int i = 0; i < m; i++) {
int moment = fs.nextInt();
int lo = 0, hi = n - 1;
int ans = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (moment >= intervals[mid].start && moment < intervals[mid].end) {
ans = mid;
break;
}
if (moment >= intervals[mid].end) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
pw.println(ans + 1);
}
}
public static void main(String[] args) throws Exception {
FastReader fs = new FastReader(System.in);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
solve(fs, pw);
fs.close();
pw.close();
}
static class FastReader {
BufferedReader reader;
StringTokenizer st;
FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
st = null;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
String nextLine() {
String s = null;
try {
s = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return next().charAt(0);
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
int i = 0;
while (i < n) {
arr[i++] = nextInt();
}
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
int i = 0;
while (i < n) {
arr[i++] = nextLong();
}
return arr;
}
int[] nextIntArrayOneBased(int n) {
int[] arr = new int[n + 1];
int i = 1;
while (i <= n) {
arr[i++] = nextInt();
}
return arr;
}
long[] nextLongArrayOneBased(int n) {
long[] arr = new long[n + 1];
int i = 1;
while (i <= n) {
arr[i++] = nextLong();
}
return arr;
}
void close() {
try {
reader.close();
} catch (IOException e) {
System.err.println("There's been an error trying closing the reader ");
e.printStackTrace();
}
}
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
bf6d5d54d37413289a7d5f28ef9a7279
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CF302B extends PrintWriter {
CF302B() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF302B o = new CF302B(); o.main(); o.flush();
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int[] aa = new int[n];
for (int i = 0; i < n; i++) {
int c = sc.nextInt();
int t = sc.nextInt();
aa[i] = c * t;
}
int a = 0;
for (int i = 0, j = 0; j < m; j++) {
int b = sc.nextInt();
while (i < n && a + aa[i] < b)
a += aa[i++];
println(i + 1);
}
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
caf0058977e73b45d5fa4001b7a2a91e
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
/**
* Author: Rohan Arora(codiinggeek)
*/
import java.io.*;
import java.util.*;
public class chad {
static long mod = (long) Math.pow(10, 9) + 7;
public static long binary(long val, ArrayList<Long> list){
long ans = -1;
int low = 0;
int high = list.size()-1;
while(low<=high){
int mid = low+(high-low)/2;
if(list.get(mid)>=val){
ans = mid;
high = mid-1;
}else{
low = mid+1;
}
}
return ans+1;
}
public static void main(String[] args) {
try {
FastReader s = new FastReader();
int n = s.nextInt();
int m = s.nextInt();
StringBuilder sb = new StringBuilder();
ArrayList<Long> list = new ArrayList<>();
long prev = 0;
while(n-->0){
long c = s.nextLong();
long t = s.nextLong();
prev += c*t;
list.add(prev);
}
while(m-->0){
long a = s.nextLong();
long ans = binary(a, list);
sb.append(ans+"\n");
}
System.out.println(sb);
} catch (Exception e) {
System.out.println(e);
return;
}
}
/**POWER CALCULATION FOR LARGE VALUES*/
static long expo(long b, long ex) {
long t = 1L;
while (ex > 0) {
if (ex % 2 != 0)
t = (t * b) % mod;
b = (b * b) % mod;
ex /= 2;
}
return t % mod;
}
/**Pair class */
class Pair<U, V> {
U first;
V second;
Pair(U a, V b) {
first = a;
second = b;
}
}
/**---------------------------------------------------------------------------------*/
/** FAST I/O */
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
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
d7892ebc3736a4e3852c63c5af43af9d
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.*;
import java.lang.*;
public class Main{
public static void main (String...args) throws IOException {
Scanner in = new Scanner(System.in);
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
int n = in.nextInt(), m= in.nextInt(); int[] song = new int[n]; int len =0;
for(int i = 0; i<n; i++){
int c = in.nextInt(), t = in.nextInt();
song[i] = c*t;
}
for(int i =0, j=0; j<m;j++) {
int time = in.nextInt();
while (i < n && time > len + song[i]) len += song[i++];
int ans = i+1;
log.write(ans + "\n");
}
log.close();
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
799e190047f7e6bc3109e56918687ee6
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CF302B extends PrintWriter {
CF302B() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF302B o = new CF302B(); o.main(); o.flush();
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int[] aa = new int[n];
for (int i = 0; i < n; i++) {
int c = sc.nextInt();
int t = sc.nextInt();
aa[i] = c * t;
}
int a = 0;
for (int i = 0, j = 0; j < m; j++) {
int b = sc.nextInt();
while (i < n && a + aa[i] < b)
a += aa[i++];
println(i + 1);
}
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
b5ec44a6802365dc1017bce5c581302b
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import org.w3c.dom.ls.LSOutput;
import java.util.*;
import java.lang.*;
import java.io.*;
public class RPS {
public static void main(String[] args) throws java.lang.Exception {
BufferedReader br = new BufferedReader(new InputStreamReader((System.in)));
StringTokenizer s = new StringTokenizer(br.readLine());
int n = Integer.parseInt(s.nextToken());
int m = Integer.parseInt(s.nextToken());
long[][] songs = new long[n+1][2];
for (int i = 1; i <= n; i++) {
s = new StringTokenizer(br.readLine());
songs[i][0] = Long.parseLong(s.nextToken());
songs[i][1] = Long.parseLong(s.nextToken());
}
s = new StringTokenizer(br.readLine());
long timePassed = 0;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
for (int i = 1, currentSong = 1; i <= m; i++) {
long moment = Long.parseLong(s.nextToken());
while (currentSong <= n && moment > songs[currentSong][1] * songs[currentSong][0] + timePassed) {
timePassed += (songs[currentSong][0] * songs[currentSong][1]);
currentSong++;
}
bw.write(currentSong + "\n");
}
bw.close();
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
38d6a82de23d9e0d06fe686b34ee2300
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Letters {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[] time = new int[n+1];
for(int i =1;i<=n;i++) {
st = new StringTokenizer(br.readLine());
time[i]=time[i-1]+(Integer.parseInt(st.nextToken())*Integer.parseInt(st.nextToken()));
}
int count =1;
st = new StringTokenizer(br.readLine());
for(int i=0;i<m;i++) {
int k = Integer.parseInt(st.nextToken());
if(k<=time[count])
System.out.println(count);
else {
while(k>time[count])
count++;
System.out.println(count);
}
}
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
86544c634897f1668519ae55cf42fac8
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.util.*;
public class Solution{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
long arr[] = new long[n];
for(int i=0; i<n;i++){
int c = sc.nextInt();
int t = sc.nextInt();
if(i==0){
arr[0] = c * t;
}else{arr[i] = c * t + arr[i-1];}
}
int var[] = new int[m];
int ans[] = new int[m];
for(int i=0;i<m;i++){
var[i] = sc.nextInt();
ans[i] = Arrays.binarySearch(arr,var[i]);
if(ans[i]<0){
ans[i] *= -1;
}else{
ans[i] +=1;
}
}
for(long xx : ans)
System.out.print(xx+" ");
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
85767dca7f092e663509304025036dc1
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
int n = sc.nextInt();
int m = sc.nextInt();
int[] trackDuration = new int[n];
for (int i = 0; i < n; i++) {
trackDuration[i] = sc.nextInt() * sc.nextInt();
}
int globalTime = 0;
int currentTrackIndex = 0;
for (int i = 0; i < m; i++) {
final int timeMoment = sc.nextInt();
while (currentTrackIndex < n && timeMoment > globalTime + trackDuration[currentTrackIndex]) {
globalTime += trackDuration[currentTrackIndex];
currentTrackIndex++;
}
writer.write(currentTrackIndex + 1 + "\n");
}
writer.close();
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
6a7f80a733bd973355979d1bec80481c
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.*;
import java.util.*;
/**
* User :- sudhakar
* Date :- 26/06/20
* Time :- 5:50 PM
*/
public class EugenyAndPlayList {
private static final Reader r = new Reader();
static final int MOD = 1000000007, SEIVE_SIZE = 10000000;
static final int MAX = Integer.MAX_VALUE;
static final int MIN = Integer.MIN_VALUE;
static int[] spf;
// CODE STARTS HERE
public static void main(String[] args) throws IOException {
int n = ni();
int m = ni();
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
int c = ni();
int t = ni();
a[i] = a[i - 1] + c * t;
}
//input v
int[] v = nextIntArr(m);
int res = 0;
for (int i = 1; i <= m; i++) {
int x = v[i];
int low = 0;
int high = n;
while (low < high) {
int mid = low + (high - low) / 2;
if (x <= a[mid])
high = mid;
else low = mid;
if (low + 1 == high || low == high) {
res = high;
break;
}
}
System.out.println(res);
}
}
// SOLUTION ENDS HERE
/*Inner class for fast input*/
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public String nextString() throws IOException {
byte c = read();
while (Character.isWhitespace(c)) {
c = read();
}
StringBuilder builder = new StringBuilder();
builder.append((char) c);
c = read();
while (!Character.isWhitespace(c)) {
builder.append((char) c);
c = read();
}
return builder.toString();
}
public char nextChar() throws IOException {
byte c = read();
while (Character.isWhitespace(c)) {
c = read();
}
return (char) c;
}
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;
}
public int[] nextIntArray(Reader r, int size) throws IOException {
int[] arr = new int[size + 1];
for (int i = 1; i <= size; i++)
arr[i] = r.nextInt();
return arr;
}
public long[] nextLongArray(Reader r, int size) throws IOException {
long[] arr = new long[size + 1];
for (int i = 1; i <= size; i++)
arr[i] = r.nextLong();
return arr;
}
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();
}
}
private static int ni() throws IOException {
return r.nextInt();
}
private static long nl() throws IOException {
return r.nextLong();
}
private static char nc() throws IOException {
return r.nextChar();
}
private static double nd() throws IOException {
return r.nextDouble();
}
private static String ns() throws IOException {
return r.nextString();
}
private static int[] nextIntArr(int size) throws IOException {
return r.nextIntArray(r, size);
}
private static long[] nextLongArr(int size) throws IOException {
return r.nextLongArray(r, size);
}
private static boolean isPrime(int n) {
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}
private static boolean isPowerOfTwo(long c) {
return (c & (c - 1)) == 0;
}
public static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static void sieve() {
spf = new int[SEIVE_SIZE + 1];
spf[1] = 1;
for (int i = 1; i <= SEIVE_SIZE; i += 2)
spf[i] = i;
for (int i = 2; i <= SEIVE_SIZE; i += 2)
spf[i] = 2;
for (int i = 3; i * i <= SEIVE_SIZE; i++) {
// checking if i is prime
if (spf[i] == i) {
// marking SPF for all numbers divisible by i
for (int j = i * i; j < SEIVE_SIZE; j += i)
// marking spf[j] if it is not
// previously marked
if (spf[j] == j)
spf[j] = i;
}
}
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
3ef727fd381e7f2a32fb4d02419ffdf3
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class MainPlaylist {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int songsCount = sc.nextInt();
int timeCount = sc.nextInt();
int[] songsLengths = new int[songsCount + 1];
int times = sc.nextInt();
int length = sc.nextInt();
songsLengths[0] = times * length;
for (int i = 1; i < songsCount; i++) {
times = sc.nextInt();
length = sc.nextInt();
songsLengths[i] = songsLengths[i - 1] + times * length;
}
int time, k, l, r, m;
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
for (int i = 0; i < timeCount; i++) {
time = sc.nextInt();
k = 1;
if (time >= songsLengths[0]) {
l = 0;
r = songsCount - 1;
while (l + 1 < r) {
m = (l + r) >> 1;
if (songsLengths[l] == time || songsLengths[r] == time) break;
if (songsLengths[m] > time) {
r = m;
} else {
l = m;
if (songsLengths[m] == time) break;
}
}
if (songsLengths[l] == time) {
k = l + 1;
} else {
k = r + 1;
}
}
log.write(k + "\n");
}
log.close();
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
c6b2359f49959a635f24e6427448c10b
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.*;
import java.lang.*;
public class Main {
public static void main (String[] args) throws IOException {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int[] pair = new int[n];
int currentT = input.nextInt() * input.nextInt();
int a;
int currentN = 1;
for (int i = 1; i < n; i++) {
pair[i] = input.nextInt() * input.nextInt();
}
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
for (int i = 0; i < m; i++) {
a = input.nextInt();
while (true) {
if (a <= currentT) {
log.write(currentN + "\n");
break;
} else {
currentT += pair[currentN++];
}
}
}
log.close();
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
050cb0170c60a66bc07547ec1354cb5d
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
/* -------> Bismillahir Rahmanir Rahim <------*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class A {
private static final FastScanner in = new FastScanner();
// private static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int n = in.nextInt();
int m = in.nextInt();
long[] a = new long[n + 1];
for (int i = 1; i <= n; ++i) {
int x = in.nextInt();
int y = in.nextInt();
a[i] = y * x + a[i - 1];
}
while (m-- != 0) {
int x = in.nextInt();
int pos = binarySearch(1, n, a, x);
if (a[pos] < x) {
System.out.println(pos + 1);
} else {
System.out.println(pos);
}
}
}
static int binarySearch(int l, int r, long[] a, int x) {
while (r > l) {
if (a[(l + r) / 2] == x) {
return (l + r) / 2;
} else if (a[(l + r) / 2] > x) {
r = (l + r) / 2;
} else {
l = (l + r) / 2 + 1;
}
}
return l;
}
static long check(long n) {
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
// static void sort(a) {
// ArrayList<Integer> l = new ArrayList<>();
// for (int i : a) l.add(i);
// Collections.sort(l);
// for (int i = 0; i < a.length; i++) a[i] = l.get(i);
// }
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
//
//class pair {
// private int val;
// private int index;
//
// public pair(int val, int index) {
// this.val = val;
// this.index = index;
// }
//
// public int getVal() {
// return val;
// }
//
// public int getIndex() {
// return index;
// }
//}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
ab966f93f76434351099bda429933f5d
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int[] mas = new int[n];
int curT = input.nextInt() * input.nextInt();
int a;
int curN = 1;
for (int i = 1; i < n; i++) {
mas[i] = input.nextInt() * input.nextInt();
}
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
for (int i = 0; i < m; i++) {
a = input.nextInt();
while (true) {
if (a <= curT) {
log.write(curN + "\n");
break;
} else {
curT += mas[curN++];
}
}
}
log.close();
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
b656b0b04466aefeaccd0e83e117a262
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), m = in.nextInt();
int[] range = new int[n];
int beg = 0;
for (int i = 0; i < n; i++) {
beg += in.nextInt() * in.nextInt();
range[i] = beg;
}
int j = 0;
for (int i = 0; i < m; i++) {
int time = in.nextInt();
while (time > range[j])
j++;
System.out.print(j + 1 + "\n");
}
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
be805b264b38c692e523f32b277547e4
|
train_000.jsonl
|
1367769900
|
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
|
256 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
int n = sc.nextInt();
int m = sc.nextInt();
int[] trackDuration = new int[n];
for (int i = 0; i < n; i++) {
trackDuration[i] = sc.nextInt() * sc.nextInt();
}
int globalTime = 0;
int currentTrackIndex = 0;
for (int i = 0; i < m; i++) {
final int timeMoment = sc.nextInt();
while (currentTrackIndex < n && timeMoment > globalTime + trackDuration[currentTrackIndex]) {
globalTime += trackDuration[currentTrackIndex];
currentTrackIndex++;
}
writer.write(currentTrackIndex + 1 + "\n");
}
writer.close();
}
}
|
Java
|
["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"]
|
2 seconds
|
["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"binary search",
"implementation"
] |
c4398a9f342a23baf1d7ebc9f4e9577d
|
The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
| 1,200 |
Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
|
standard output
| |
PASSED
|
d6568822151e2a913650d43ef0530ed1
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
/*int a=sc.nextInt();
int b=sc.nextInt();
System.out.println(a^b);*/
int n = sc.nextInt();
BigInteger[] mas = new BigInteger[n];
for(int i=0;i<n;i++)
{
mas[i]=sc.nextBigInteger();
}
BigInteger max = BigInteger.ZERO;
for(int i=0;i<n;i++)
{
BigInteger t = BigInteger.ZERO;
for(int j=i;j<n;j++)
{
t=t.xor(mas[j]);
if(t.compareTo(max)==1)
{
max=BigInteger.ONE.multiply(t);
}
}
}
System.out.println(max);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
3c805a7dfab2405a9d53737876bc6b50
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.Scanner;
public class P252A
{
static Scanner in;
public static void main (String[] args)
{
in = new Scanner(System.in);
int n = in.nextInt();
int[] array = new int[n];
for (int i=0; i<n; i++)
array[i] = in.nextInt();
int result=0;
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{int xor=0;
for (int k=i; k<=j; k++)
xor ^= array[k];
result = Math.max(xor, result);
}
}
System.out.println(result);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
a31ebed5ad86ce7aa3d403353f18cfdc
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
private IO io;
private int ioMode = -1;
private String problemName = "";
private final String mjArgument = "master_j";
public static void main(String programArguments[]) throws IOException{
if(programArguments != null && programArguments.length > 0)
new Main().run(programArguments[0]);
else
new Main().run(null);
}
private void run(String programArgument) throws IOException {
// _______________________________________________ _________
// | Input Mode | Output Mode | mode | comment |
// |------------------|---------------------|----- |---------|
// | input.txt | System.out | 0 | mj |
// | System.in | System.out | 1 | T / CF |
// |<problemName>.in | <problemName>.out | 2 | |
// | input.txt | output.txt | 3 | C |
// |__________________|_____________________|______|_________|
long nanoTime = 0;
if(programArgument != null && programArgument.equals(mjArgument)) // mj
ioMode = 0;
else if(System.getProperty("ONLINE_JUDGE") != null) // T / CF
ioMode = 1;
else
ioMode = 2;
switch(ioMode){
case -1:
try{
throw new Exception("<ioMode> init failure") ;
}catch (Exception e){
e.printStackTrace();
}
return;
case 0:
break;
case 1:
break;
case 2:
if(problemName.length() == 0){
try{
throw new Exception("<problemName> init failure");
}catch (Exception e){
e.printStackTrace();
}
return;
}
case 3:
break;
}
io = new IO(ioMode, problemName);
if(ioMode == 0){
System.out.println("File output : \n<start>");
System.out.flush();
nanoTime = System.nanoTime();
}
solve();
io.flush();
if(ioMode == 0){
System.out.println("</start>");
long t = System.nanoTime() - nanoTime;
int d3 = 1000000000, d2 = 1000000, d1 = 1000000;
if(t>=d3)
System.out.println(t/d3 + "." + t%d3 + " seconds");
else if(t>=d2)
System.out.println(t/d2 + "." + t%d2 + " millis");
else if(t>=d1)
System.out.println(t/d1 + "." + t%d1 + " millis");
System.out.flush();
}
}
private void solve() throws IOException {
int n = io.nI(), a[] = new int[n], max = Integer.MIN_VALUE;
for(int i = 0; i<n; i++)
a[i] = io.nI();
for(int i = 0; i < n; i++){
int t = 0;
for(int j = i; j < n; j++){
t ^= a[j];
max = Math.max(max, t);
}
}
io.wln(max);
}//2.2250738585072012e-308
/**
* Input-output class
* @author master_j
* @version 0.2.4
*/
@SuppressWarnings("unused")
private class IO{
private boolean alwaysFlush;
StreamTokenizer in; PrintWriter out; BufferedReader br; Reader reader; Writer writer;
public IO(int ioMode, String problemName) throws IOException{
Locale.setDefault(Locale.US);
// _______________________________________________ _________
// | Input Mode | Output Mode | mode | comment |
// |------------------|---------------------|----- |---------|
// | input.txt | System.out | 0 | mj |
// | System.in | System.out | 1 | T / CF |
// |<problemName>.in | <problemName>.out | 2 | |
// | input.txt | output.txt | 3 | C |
// |__________________|_____________________|______|_________|
switch(ioMode){
case 0:
reader = new FileReader("input.txt");
writer = new OutputStreamWriter(System.out);
break;
case 1:
reader = new InputStreamReader(System.in);
writer = new OutputStreamWriter(System.out);
break;
case 2:
reader = new FileReader(problemName + ".in");
writer = new FileWriter(problemName + ".out");
break;
case 3:
reader = new FileReader("input.txt");
writer = new FileWriter("output.txt");
break;
}
br = new BufferedReader(reader);
in = new StreamTokenizer(br);
out = new PrintWriter(writer);
alwaysFlush = false;
}
public void setAlwaysFlush(boolean arg){alwaysFlush = arg;}
public void wln(){out.println(); if(alwaysFlush)flush();}
public void wln(int arg){out.println(arg); if(alwaysFlush)flush();}
public void wln(long arg){out.println(arg); if(alwaysFlush)flush();}
public void wln(double arg){out.println(arg); if(alwaysFlush)flush();}
public void wln(String arg){out.println(arg); if(alwaysFlush)flush();}
public void wln(boolean arg){out.println(arg); if(alwaysFlush)flush();}
public void wln(char arg){out.println(arg); if(alwaysFlush)flush();}
public void wln(float arg){out.println(arg); if(alwaysFlush)flush();}
public void wln(Object arg){out.println(arg); if(alwaysFlush)flush();}
public void w(int arg){out.print(arg); if(alwaysFlush)flush();}
public void w(long arg){out.print(arg); if(alwaysFlush)flush();}
public void w(double arg){out.print(arg); if(alwaysFlush)flush();}
public void w(String arg){out.print(arg); if(alwaysFlush)flush();}
public void w(boolean arg){out.print(arg); if(alwaysFlush)flush();}
public void w(char arg){out.print(arg); if(alwaysFlush)flush();}
public void w(float arg){out.print(arg); if(alwaysFlush)flush();}
public void w(Object arg){out.print(arg); if(alwaysFlush)flush();}
public void wf(String format, Object...args){out.printf(format, args); if(alwaysFlush)flush();}
public void flush(){out.flush();}
public int nI() throws IOException {in.nextToken(); return(int)in.nval;}
public long nL() throws IOException {in.nextToken(); return(long)in.nval;}
public String nS() throws IOException {in.nextToken(); return in.sval;}
public double nD() throws IOException {in.nextToken(); return in.nval;}
public float nF() throws IOException {in.nextToken(); return (float)in.nval;}
public char nC() throws IOException {return (char)br.read();}
public void wc(char...arg){for(char c : arg){in.ordinaryChar(c);in.wordChars(c, c);}}
public void wc(String arg){wc(arg.toCharArray());}
public void wc(char arg0, char arg1){in.ordinaryChars(arg0, arg1); in.wordChars(arg0, arg1);}
public boolean eof(){return in.ttype == StreamTokenizer.TT_EOF;}
public boolean eol(){return in.ttype == StreamTokenizer.TT_EOL;}
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
874c656107c161948c68765e3dc0effe
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A_252 {
FastScanner in;
PrintWriter out;
public void run() {
try {
in = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void solve() throws IOException {
int n = in.nextInt();
int [] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = in.nextInt();
}
int x = 0;
int mx = 0;
for (int i=0; i<n; i++) {
/*x = a[i];
if (x > mx) {
mx = x;
}*/
x = 0;
for (int j=i; j<n; j++) {
x ^= a[j];
if (x > mx) {
mx = x;
}
}
}
out.println(mx);
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader in) {
br = new BufferedReader(in);
}
String nextLine() {
String str = null;
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] arg) {
A_252 o = new A_252();
o.run();
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
c4051ed5d441b41154770504094a9620
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A_252 {
FastScanner in;
PrintWriter out;
public void run() {
try {
in = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void solve() throws IOException {
int n = in.nextInt();
int [] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = in.nextInt();
}
int x = 0;
int mx = 0;
for (int i=0; i<n; i++) {
for (int j=i; j<n; j++) {
x = a[i];
for (int k=i+1; k<=j; k++) {
x ^= a[k];
}
if (x > mx) {
mx = x;
}
}
}
out.println(mx);
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader in) {
br = new BufferedReader(in);
}
String nextLine() {
String str = null;
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] arg) {
A_252 o = new A_252();
o.run();
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
b7136dde7f2f956ca5ed5373d623b278
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A_252 {
FastScanner in;
PrintWriter out;
public void run() {
try {
in = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void solve() throws IOException {
int n = in.nextInt();
int [] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = in.nextInt();
}
int x = 0;
int mx = 0;
for (int i=0; i<n; i++) {
x = a[i];
if (x > mx) {
mx = x;
}
for (int j=i+1; j<n; j++) {
x ^= a[j];
if (x > mx) {
mx = x;
}
}
}
out.println(mx);
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader in) {
br = new BufferedReader(in);
}
String nextLine() {
String str = null;
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] arg) {
A_252 o = new A_252();
o.run();
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
2a10872b4b5de724418fc014654494ca
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(in, out);
out.close();
}
}
class TaskA {
public void solve(InputReader in, OutputWriter out) {
int n = in.nextInt();
int tab[] = new int[n];
for (int i = 0; i < n; i++) {
tab[i] = in.nextInt();
}
int max = 0;
for (int i = 0; i < n; i++) {
int val = tab[i];
if(val > max) max = val;
for (int j = i+1; j < n; j++) {
val = val ^ tab[j];
if(val > max) max = val;
}
}
System.out.println(max);
}
}
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());
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
8b1e22be9e11412bd9243b044d1c4bd8
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author koval
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
BigInteger[] a = new BigInteger[n];
for (int i = 0; i < n; i++) {
a[i] = new BigInteger(st.nextToken());
}
BigInteger d = BigInteger.ZERO;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
BigInteger x = BigInteger.ZERO;
for (int k = i; k <= j; k++) {
x = x.xor(a[k]);
}
if (x.compareTo(d) == 1) {
d = x;
}
}
}
System.out.println(d.toString());
br.close();
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
d27b183d69a6b955157abcd9e47feddd
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.*;
import java.util.StringTokenizer;
/**
* User: andrey
* Date: 06.12.12
*/
public class Codeforces {
private static BufferedReader in;
private static PrintWriter out;
private StringTokenizer st;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
new Codeforces().run();
out.flush();
}
private void run() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
}
int r = 0;
for (int i = 0; i < n; ++i) {
int x = 0;
for (int j = i; j < n; ++j) {
x ^= a[j];
r = Math.max(r, x);
}
}
out.print(r);
}
private String nextToken() throws IOException {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
33c1999e9bb078e2344e284a569e71ec
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.*;
import java.util.StringTokenizer;
/**
* User: andrey
* Date: 06.12.12
*/
public class Codeforces {
private static BufferedReader in;
private static PrintWriter out;
private StringTokenizer st;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
new Codeforces().run();
out.flush();
}
private void run() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
}
int r = 0;
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
int x = 0;
for (int k = i; k <= j; ++k) {
x ^= a[k];
}
r = Math.max(r, x);
}
}
out.print(r);
}
private String nextToken() throws IOException {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
c72c1b96cd9ea991d406ffdb3557fa36
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.*;
public class A{
public static void main(String [] args){
Scanner s = new Scanner(System.in);
final int n = s.nextInt();
int [] x = new int[n];
for (int i = 0; i < n; ++i){
x[i] = s.nextInt();
}
int [] xor = new int[n + 1];
for (int i = 1; i <= n; ++i){
xor[i] ^= x[i - 1]^xor[i - 1];
}
int max = 0;
for (int i = 0; i < n; ++i){
for (int j = i; j <= n; ++j){
max = Math.max(max, xor[j]^xor[i]);
}
}
System.out.println(max);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
48b55c8b490a5c39b3bd2d971872a2ae
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.*;
public class A{
public static void main(String[] args){
Scanner s = new Scanner (System.in);
final int n = s.nextInt();
int [] a = new int[n];
for (int i = 0; i < n; ++i){
a[i] = s.nextInt();
}
int res = a[0];
for (int i = 0; i < n; ++i){
for (int j = i; j < n; ++j){
int xor = 0;
for (int k = i; k <= j; ++k){
xor ^= a[k];
}
res = Math.max(res, xor);
}
}
System.out.println(res);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
71fbb82e9aacb93fb16f5ca424a98fa2
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.Scanner;
public class Registers {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
final int n = sc.nextInt();
int [] a = new int[n];
for (int i = 0; i < n; ++i){
a[i] = sc.nextInt();
}
int res = -1;
for(int i = 0; i < n; i++){
int xor = 0;
for(int j = i; j < n; j++){
xor ^= a[j];
res = Math.max(res, xor);
}
}
System.out.println(res);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
e7019b86407cbf2be26586a3d25ddb79
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int mex = 0;
int n= sc.nextInt();
int sa[] = new int[n];
for(int i = 0;i<n;i++){
sa[i]=sc.nextInt();
}
for(int i = 0;i<n;i++){
int thingy = sa[i];
mex=Math.max(thingy,mex);
for(int j = i+1;j<n;j++){
thingy=thingy^sa[j];
mex=Math.max(thingy,mex);
}
}
System.out.println(mex);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
822c6b71c12d472915f741704a57f3dc
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class PashmakandGarden {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
String a[] = in.readLine().split(" ");
int num[] = new int[n];
for (int i = 0; i < num.length; i++) {
num[i] = Integer.parseInt(a[i]);
}
long max = 0;
long xor = 0;
for (int i = 0; i < num.length; i++) {
xor = num[i];
max = Math.max(max, xor);
for (int j = i+1; j < num.length; j++) {
xor = xor ^ num[j];
max = Math.max(max, xor);
}
}
out.println(max);
out.close();
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
a5df7d96abb4d5a7b197064d2bbf0c26
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.*;
import java.io.PrintWriter;
import java.math.*;
public class Main {
void run(int nT) {
int n = cin.nextInt();
int[] num = new int[n];
int[] xor = new int[n];
for (int i = 0; i < n; ++i) {
num[i] = cin.nextInt();
xor[i] = num[i];
if (i != 0) xor[i] ^= xor[i - 1];
}
int result = 0;
for (int i = 0; i < n; ++i) {
result = Math.max(result, xor[i]);
for (int j = 0; j < i; ++j) {
result = Math.max(result, xor[i] ^ xor[j]);
}
}
out.println(result);
}
public static void main(String[] argv) {
Main solved = new Main();
int T = 1;
//T = solved.cin.nextInt();
for (int nT = 1; nT <= T; ++nT) {
solved.run(nT);
}
solved.out.close();
}
Scanner cin = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
f0b3516fa03b896cb6202d5f835ca5b3
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
public class P252A {
@SuppressWarnings("unchecked")
public void run() throws Exception {
int [] a = readInt(nextInt());
int mXor = 0;
for (int i = 0; i < a.length; i++) {
int xor = 0;
for (int j = i; j < a.length; j++) {
xor ^= a[j];
mXor = Math.max(mXor, xor);
}
}
println(mXor);
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P252A().run();
br.close();
pw.close();
}
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(""); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
8c80f4af7488d7fce91f5cffa9ea25cb
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int a[] = in.parseInt1D(n);
int max = 0;
for(int i = 0;i <n;i++) {
int v = a[i];
max = Math.max(v,max);
for(int j = i + 1;j < n;j++) {
v = v^a[j];
max = Math.max(max,v);
}
}
out.println(max);
}
}
class InputReader {
private BufferedReader br;
private StringTokenizer st;
public InputReader(InputStream in) {
br=new BufferedReader(new InputStreamReader(in));
try {
st=new StringTokenizer(br.readLine());
} catch (IOException ignored) {
}
}
public void readLine() {
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
return;
}
}
public int nextInt(){
return Integer.parseInt(st.nextToken());
}
/**
* Parse 1D array from current StringTokenizer
*/
public int[] parseInt1D(int n){
readLine();
int r[]=new int[n];
for(int i=0;i<n;i++){
r[i]=nextInt();
}
return r;
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
908df0d41ba909890a47b519f5d1c6bf
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author alex
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
int[] a = IOUtils.readIntArray(in, n);
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
int x = 0;
for (int k = i; k <= j; ++k)
x ^= a[k];
if (x > ans) ans = x;
}
}
out.println(ans);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public 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 static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int n) {
int[] ret = new int[n];
for (int i = 0; i < n; ++i) ret[i] = in.readInt();
return ret;
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
6a99b1ff2f28c0451f7b7fb7332aaf6e
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Lokesh Khandelwal aka (codeKNIGHT | phantom11)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
long max=-1;
int i,j;
int n=in.nextInt();
int a[]=new int[n];
for(i=0;i<n;i++)
a[i]=in.nextInt();
for(int len=1;len<=n;len++)
{
for(i=0;i<=n-len;i++)
{
long xor=0;
for(j=i;j<i+len;j++)
xor^=a[j];
if(xor>max)
max=xor;
}
}
out.printLine(max);
}
}
class InputReader
{
BufferedReader in;
StringTokenizer tokenizer=null;
public InputReader(InputStream inputStream)
{
in=new BufferedReader(new InputStreamReader(inputStream));
}
public String next()
{
try{
while (tokenizer==null||!tokenizer.hasMoreTokens())
{
tokenizer=new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
catch (IOException e)
{
return null;
}
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
8e4509779f85a24d0148f2159b7d4235
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
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.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Scanner;
import java.util.TreeMap;
public class Solution{
///////////////////////////////////////////////////////////////////////////
static class FastScanner{
BufferedReader s;
StringTokenizer st;
public FastScanner(){
st = new StringTokenizer("");
s = new BufferedReader(new InputStreamReader(System.in));
}
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
public static int divisor(int x){
int 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;
}
public static long gcd(long a, long b){
return b == 0 ? a : gcd(b,a%b);
}
public static long lcm(long a,long b, long c){
return lcm(lcm(a,b),c);
}
public static long lcm(long a, long 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"));
private static FastScanner s = new FastScanner();
private static PrintWriter ww = new PrintWriter(new OutputStreamWriter(System.out));
// private static Scanner s = new Scanner(System.in);
@SuppressWarnings("unused")
private static Map<Integer,Integer> mm = new HashMap<Integer,Integer>();
@SuppressWarnings("unused")
private static Map<Integer,node> mn = new HashMap<Integer,node>();
@SuppressWarnings("unused")
private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} };
////////////////////////////////////////////////////////////////////
static class node implements Comparable<node>{
int to;
long cost;
public node(int x, long y){
this.to = x;
this.cost = y;
}
@Override
public int compareTo(node arg0) {
// TODO Auto-generated method stub
return Long.compare(cost, arg0.cost);
}
}
public static void main(String[] args) throws IOException{
Solution so = new Solution();
so.solve();
}
////////////////////////////////////////////////////////////////////
void solve() throws IOException{
int n = s.nextInt();
int[] a = new int[n];
int max = 0;
int ans = 0;
for(int i=0;i<n;i++) a[i] = s.nextInt();
for(int i=0;i<n;i++){
max = 0;
for(int j=i;j<n;j++){
max ^= a[j];
ans = Math.max(ans, max);
}
}
ww.println(ans);
s.close();
ww.close();
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
016077890f7294b62b8757bc4fcef238
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.Scanner;
/*
* M(i, j) = XOR value for elements i to j
* M(i, j) where i > j = 0;
* M(i, j) where i = j = E(i)
* M(i, j) = M(i, j - 1) ^ E(j) otherwise
*
* O(n^2)
*/
public class LittleXOR {
public static int findMax(int[] elements) {
int[][] memo = new int[elements.length][elements.length];
int max = 0;
for (int i = 0; i < elements.length; i++) {
memo[i][i] = elements[i];
if (memo[i][i] > max) {max = memo[i][i];}
for (int j = i + 1; j < elements.length; j++) {
memo[i][j] = memo[i][j-1] ^ elements[j];
if (memo[i][j] > max) {max = memo[i][j];}
}
}
return max;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] elements = new int[n];
for (int i = 0; i < n; i++) {
elements[i] = in.nextInt();
}
System.out.println(findMax(elements));
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
95f2f4cd6c97bd63cd8211b09f96ee3d
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.Scanner;
public class A252A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int maxxor = 0;
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
int xor = 0;
for (int k = i; k < n; k++) {
if (k == i)
xor = arr[k];
else
xor ^= arr[k];
if (maxxor < xor)
maxxor = xor;
}
}
System.out.println(maxxor);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
70ea51aa04185dce45af390f2005903e
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] data = br.readLine().split(" ");
long mayor = 0;
for (int i = 0; i < data.length; i++) {
mayor = Math.max(Long.parseLong(data[i]), mayor);
}
int f = 0;
while(f != data.length){
long temp = 0;
for (int i = f++; i < data.length; i++) {
temp = temp^Long.parseLong(data[i]);
mayor = Math.max(temp,mayor);
}
}
System.out.println(mayor);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
ac9f88604081fdbc2b95a7538d7c0c96
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.Scanner;
public class R4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] array = new int[n];
int maxor;
int xor;
for (int i = 0; i < array.length; i++) {
array[i] = in.nextInt();
}
maxor = 0;
for (int i = 0; i < array.length - 1; i++) {
xor = array[i];
for (int j = i + 1; j < array.length; j++) {
xor ^= array[j];
if (xor > maxor) {
maxor = xor;
}
}
}
for (int i = 0; i < array.length; i++) {
if (array[i] > maxor)
maxor = array[i];
}
System.out.println(maxor);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
485c8c2dce5ad71be45948ebabd793bf
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
public class MainProblemA {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
Jam solver = new Jam();
int testCount = 1;
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
}
class Jam
{
public void solve(int testNumber, InputReader in, OutputWriter out)
{
int N = in.readInt();
int[] arr = IOUtils.readIntArray(in, N);
int ans=0,temp=0;
for (int i = 0; i < N; i++)
{
temp=0;
for(int j=i;j<N;j++)
{
temp=temp^arr[j];
if(temp>ans)
ans=temp;
}
}
out.printLine(ans);
}
}
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();
StringBuffer res = new StringBuffer();
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);
}
}
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;
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
a0a2668e3c7b2378620cf804444b98d4
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.*;
import java.math.*;
import java.io.*;
public class Main {
public static StringTokenizer st;
public static BufferedReader scan;
public static PrintWriter out;
public class Pair {
public int x, y;
public Pair(int x, int y){
this.x = x;
this.y = y;
}
}
public static void main(String[] args) throws IOException{
scan = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int[] a = new int[n];
int max = -1;
for(int i = 0; i < n; i++){
a[i] = nextInt();
}
for(int i = 0; i < n; i++){
int t = a[i], maxh = a[i];
for(int j = i + 1; j < n; j++){
t ^= a[j];
if(t > maxh)maxh = t;
}
if(maxh > max)max = maxh;
}
out.println(max);
scan.close();
out.close();
}
public static BigDecimal nextBigDecimal() throws IOException {
return new BigDecimal(next());
}
public static BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static String next() throws IOException {
while(st == null || !st.hasMoreTokens()){
st = new StringTokenizer(scan.readLine());
}
return st.nextToken();
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
8ebe9313ffdf84241fd7a0c8981546ef
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int max = -1;
Integer nums[] = new Integer[N];
for(int i=0; i<N; i++)
{
nums[i] = scanner.nextInt();
}
for(int i=0; i<N; i++)
{
for(int j=i; j<N; j++)
{
int xor = nums[i];
for(int k=i+1; k<=j; k++)
xor ^= nums[k];
if(xor > max)
max = xor;
}
}
System.out.println(max);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
cce18c8891c879e2b3df8e76f2664761
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// Scanner scan = new Scanner(System.in);
// PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(bf.readLine());
StringTokenizer st = new StringTokenizer(bf.readLine()); int[] a = new int[n];
for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
int max = -1;
for(int i=1; i<=n; i++) {
for(int j=0; j<=n-i; j++) {
int x = 0;
for(int k=j; k<j+i; k++)
x ^= a[k];
if(x > max)
max = x;
}
}
System.out.println(max);
// int n = scan.nextInt();
// out.close(); System.exit(0);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
b103849d1680680aef67ea242e013579
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.awt.Point;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args) {
new Thread(null, new Solution(), "", 256 * (1L << 20)).start();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
if (System.getProperty("ONLINE_JUDGE") != null) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter("output.txt");
out = new PrintWriter(System.out);
}
Locale.setDefault(Locale.US);
solve();
in.close();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Throwable t) {
t.printStackTrace(System.err);
System.exit(-1);
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
// solution
void solve() throws IOException {
int n = readInt();
int []mas = new int[n];
for(int i = 0; i<n; i++)
mas[i] = readInt();
int answer = mas[0];
for(int i = 0; i<n; i++)
for(int j = i; j<n; j++)
{
int xor = 0;
for(int k = i; k<=j; k++)
xor ^= mas[k];
answer = Math.max(answer, xor);
}
out.println(answer);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
7847087743d674eddd14efc945e8abc9
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class j
{
public static void main(String a[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int t=0,k=0,p=0,j=0,m=0,i=0;
long n=0,e=0;
m=Integer.parseInt(b.readLine());
int d[]=new int[m];
int f[]=new int[m];
String s;
s=b.readLine();
StringTokenizer c=new StringTokenizer(s);
for(i=0;i<m;i++)
{
d[i]=Integer.parseInt(c.nextToken());
f[i]=d[i];
}
Arrays.sort(f);
n=f[m-1];
for(i=0;i<m-1;i++)
{
for(j=i+1;j<m;j++)
{
e=d[i];
for(k=i+1;k<=j;k++)
e=(e^d[k]);
if(e>n)
n=e;
}
}
System.out.print(n);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
dc898b83a1c76b542529c5bb8c0b3269
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static Scanner scan = new Scanner(System.in);
public static boolean bg = false;
public static void main(String[] args) throws Exception {
int n1 = Integer.parseInt(scan.next());
int[][] l1 = new int[n1+1][n1+1];
int max = Integer.MIN_VALUE;
for (int i=0;i<n1;i++){
l1[i][i+1] = Integer.parseInt(scan.next());
if (l1[i][i+1]>max) max = l1[i][i+1];
}
if (bg){
for (int[] e: l1){
System.out.println(Arrays.toString(e));
}
System.out.println();
}
for (int i=1;i<n1;i++){
for (int j=0;j<n1-i;j++){
l1[j][j+i+1]=l1[j][j+i]^l1[j+i][j+i+1];
if (l1[j][j+i+1]>max) max = l1[j][j+i+1];
}
if (bg){
for (int[] e: l1){
System.out.println(Arrays.toString(e));
}
System.out.println();
}
}
System.out.println(max);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
0c5fc65ca403ac5475b724914ee358f6
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
//Date: Oct 14, 2013
//Time: 12:27:25 PM
import java.util.*;
import java.io.*;
public class A252 implements Runnable {
public void solve() throws IOException {
int N = nextInt();
int[] a = new int[N];
for(int i = 0; i < N; i++){
a[i] = nextInt();
}
int ans = 0;
for(int i = 0; i < N; i++){
for(int j = i; j < N; j++){
int now = 0;
for(int k = i; k <= j; k++) now = now ^ a[k];
ans = Math.max(ans, now);
}
}
System.out.println(ans);
}
//-----------------------------------------------------------
public static void main(String[] args) {
new A252().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;
}
/**
public class A252 {
}
*/
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
04813e0c00767e3e024cbaf1c8468945
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in=new InputReader(inputStream);
PrintWriter out=new PrintWriter(outputStream);
Name Solver = new Name();
Solver.solver(in,out);
out.close();
}
}
class InputReader{
public BufferedReader bufferedReader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream){
bufferedReader=new BufferedReader(new InputStreamReader(stream));
tokenizer=null;
}
public String next(){
while(tokenizer==null||!tokenizer.hasMoreTokens()){
try {
tokenizer=new StringTokenizer(bufferedReader.readLine());
}catch (IOException e){
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
}
class Name{
public long min(long a,long b){
if(a>b){
return b;
}
return a;
}
public long max(long a,long b){
if(a>b){
return a;
}
return b;
}
public void solver(InputReader in,PrintWriter out){
int n=in.nextInt();
int[] a=new int[n];
for (int i=0;i<n;i++){
a[i]=in.nextInt();
}
long max_xor=0;
long xor;
ArrayList<Long> arrayList=new ArrayList<Long>();
for (int i=0;i<n;i++){
xor=0;
for (int j=i;j<n;j++){
xor^=a[j];
arrayList.add(xor);
}
}
for (int i=0;i<arrayList.size();i++){
if(max_xor<arrayList.get(i)){
max_xor=arrayList.get(i);
}
}
out.print(max_xor);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
e9adf6f8cc8573055616dfb5a9e5c692
|
train_000.jsonl
|
1354807800
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class LittleXor {
static int max;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(rd.readLine());
int[] arr = new int[n];
String str = rd.readLine();
StringTokenizer tk = new StringTokenizer(str);
max = 0;
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(tk.nextToken());
if(max<arr[i])max = arr[i];
}
for (int i = 0; i < arr.length; i++) {
int max1 = 0;
int prev = arr[i];
for (int j = i+1; j < arr.length; j++) {
max1 = Math.max(max1, prev^arr[j]);
prev = prev^arr[j];
}
max = Math.max(max, max1);
}
System.out.println(max);
}
}
|
Java
|
["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"]
|
2 seconds
|
["3", "7", "14"]
|
NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
|
Java 7
|
standard input
|
[
"implementation",
"brute force"
] |
a33991c9d7fdb4a4e00c0d0e6902bee1
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
| 1,100 |
Print a single integer — the required maximal xor of a segment of consecutive elements.
|
standard output
| |
PASSED
|
9918468984879341df30901409afe594
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
public class R345Div2C {
static final long MAXN=1000000000;
static class Pair{
long x,y;
String z;
public Pair(long x,long y){
this.x=x;
this.y=y;
this.z=x+"/"+y;
}
}
public static void main(String[] args) {
FastScanner in=new FastScanner();
int n=in.nextInt();
Pair[] a=new Pair[n];
for(int i=0;i<n;i++)
a[i]=new Pair(in.nextLong(),in.nextLong());
HashMap<Long,Integer> x=new HashMap<Long,Integer>();
HashMap<Long,Integer> y=new HashMap<Long,Integer>();
HashMap<String,Integer> z=new HashMap<String,Integer>();
for(int i=0;i<n;i++){
x.put(a[i].x,x.containsKey(a[i].x)?x.get(a[i].x)+1:1);
y.put(a[i].y,y.containsKey(a[i].y)?y.get(a[i].y)+1:1);
z.put(a[i].z,z.containsKey(a[i].z)?z.get(a[i].z)+1:1);
}
long ans=0;
for(long k:x.keySet()){
if(x.get(k)>1){
ans+=x.get(k)*(x.get(k)-1L)/2;
}
}
for(long k:y.keySet()){
if(y.get(k)>1){
ans+=y.get(k)*(y.get(k)-1L)/2;
}
}
for(String k:z.keySet()){
if(z.get(k)>1){
ans-=z.get(k)*(z.get(k)-1L)/2;
}
}
System.out.println(ans);
}
static class FastScanner{
BufferedReader br;
StringTokenizer st;
public FastScanner(){br=new BufferedReader(new InputStreamReader(System.in));}
String nextToken(){
while(st==null||!st.hasMoreElements())
try{st=new StringTokenizer(br.readLine());}catch(Exception e){}
return st.nextToken();
}
int nextInt(){return Integer.parseInt(nextToken());}
long nextLong(){return Long.parseLong(nextToken());}
double nextDouble(){return Double.parseDouble(nextToken());}
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
4f2784d8fa03741216da07043f285d15
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.Pattern;
public class Solution {
private static class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Point)) {
return false;
}
Point other = (Point) o;
return other.x == x && other.y == y;
}
@Override
public int hashCode() {
int hash = 17;
hash = hash * 31 + x;
hash = hash * 31 + y;
return hash;
}
}
private static long binomial(int value) {
return ((long)value * value - value) / 2;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Map<Point, Integer> freqPoint = new HashMap<>();
Map<Integer, Integer> freqX = new HashMap<>();
Map<Integer, Integer> freqY = new HashMap<>();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
if (!freqX.containsKey(x)) {
freqX.put(x, 0);
}
freqX.put(x, freqX.get(x) + 1);
if (!freqY.containsKey(y)) {
freqY.put(y, 0);
}
freqY.put(y, freqY.get(y) + 1);
Point p = new Point(x, y);
if (!freqPoint.containsKey(p)) {
freqPoint.put(p, 0);
}
freqPoint.put(p, freqPoint.get(p) + 1);
}
long pairs = 0l;
for (Integer value : freqX.values()) {
pairs += binomial(value);
}
for (Integer value : freqY.values()) {
pairs += binomial(value);
}
for (Integer value : freqPoint.values()) {
pairs -= binomial(value);
}
System.out.println(pairs);
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
f37b7d9d46c6655938f4a304efc0ae2a
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class CF651C{
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
private static class Point{
int x;
int y;
Point(int a, int b){
x=a;y=b;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point key = (Point) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
private static void soln(){
int n = nextInt();
HashMap<Integer, Integer> ma1 = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> ma2 = new HashMap<Integer, Integer>();
HashMap<Point, Integer> ma3 = new HashMap<Point, Integer>();
for (int i=0; i<n; i++) {
int x = nextInt();
int y = nextInt();
if(ma1.isEmpty()){
ma1.put(x,1);
ma2.put(y,1);
}
else{
if(ma1.containsKey(x)){
ma1.put(x,ma1.get(x)+1);
}
else{
ma1.put(x,1);
}
if(ma2.containsKey(y)){
ma2.put(y,ma2.get(y)+1);
}
else{
ma2.put(y,1);
}
}
if(ma3.containsKey(new Point(x,y))){
ma3.put(new Point(x,y),ma3.get(new Point(x,y))+1);
}
else{
ma3.put(new Point(x,y),1);
}
}
long ans = 0 ;
for(int x:ma1.keySet()){
ans+=((long)ma1.get(x)*(ma1.get(x)-1))/2;
}
for(int y:ma2.keySet()){
ans+=((long)ma2.get(y)*(ma2.get(y)-1))/2;
}
for(Point p:ma3.keySet()){
ans-=((long)ma3.get(p)*(ma3.get(p)-1))/2;
}
pw.println(ans);
pw.close();
}
public static void main(String[] args){
InputReader(System.in);
pw = new PrintWriter(System.out);
soln();
pw.close();
}
// To Get Input
// Some Buffer Methods
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static 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++];
}
private static 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 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;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static 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();
}
private static int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private static long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private static void pArray(int[] arr){
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static void pArray(long[] arr){
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
e97d2776389eec061999b47eb0ace0e3
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.awt.Point;
import java.awt.geom.Line2D;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.GuardedObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.io.InputStream;
import java.math.BigInteger;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in;
PrintWriter out;
in=new FastScanner(System.in);
out=new PrintWriter(System.out);
//in=new FastScanner(new FileInputStream(new File("C://Users//KANDARP//Desktop//coding_contest_creation (1).txt")));
TaskC solver = new TaskC();
long var=System.currentTimeMillis();
solver.solve(1, in, out);
/*if(System.getProperty("ONLINE_JUDGE")==null){
out.println("["+(double)(System.currentTimeMillis()-var)/1000+"]");
}*/
out.close();
}
}
class Pair {
long x,y,index;
long r1,r2;
HashMap<Double,Long> map=new HashMap<>();
Pair(long x,long y,int index){
this.x=x;
this.y=y;
this.index=index;
}
public String toString(){
return this.x+" "+this.y+" ";
}
}
class tupple{
long x,y,z;
ArrayList<String> list=new ArrayList<>();
tupple(long x,long y,long z){
this.x=x;
this.y=y;
this.z=z;
}
tupple(tupple cl){
this.x=cl.x;
this.y=cl.y;
this.z=cl.z;
this.list=cl.list;
}
}
class Edge implements Comparable<Edge>{
int u;
int v;
int time;
long cost;
long wcost;
public Edge(int u,int v,long cost,long wcost){
this.u=u;
this.v=v;
this.cost=cost;
this.wcost=wcost;
time=Integer.MAX_VALUE;
}
public int other(int x){
if(u==x)return v;
return u;
}
@Override
public int compareTo(Edge o) {
// TODO Auto-generated method stub
return Long.compare(cost, o.cost);
}
}
class Ss{
Integer a[]=new Integer[3];
Ss(Integer a[]){
this.a=a;
}
public int hashCode(){
return a[0].hashCode()+a[1].hashCode()+a[2].hashCode();
}
public boolean equals(Object o){
Ss x=(Ss)o;
for(int i=0;i<3;i++){
if(x.a[i]!=this.a[i]){
return false;
}
}
return true;
}
}
class queary{
int type;
int l;
int r;
int index;
queary(int type,int l,int r){
this.type=type;
this.l=l;
this.r=r;
}
}
class boat implements Comparable<boat>{
int capacity;
int index;
boat(int capacity,int index)
{
this.capacity=capacity;
this.index=index;
}
@Override
public int compareTo(boat o) {
// TODO Auto-generated method stub
return this.capacity-o.capacity;
}
}
class angle{
double x,y,angle;
int index;
angle(int x,int y,double angle){
this.x=x;
this.y=y;
this.angle=angle;
}
}
class TaskC {
static long mod=1000000007;
// SegTree tree;
// int min[];
/* static int prime_len=1000010;
static int prime[]=new int[prime_len];
static long n_prime[]=new long[prime_len];
static ArrayList<Integer> primes=new ArrayList<>();
static{
for(int i=2;i<=Math.sqrt(prime.length);i++){
for(int j=i*i;j<prime.length;j+=i){
prime[j]=i;
}
}
for(int i=2;i<prime.length;i++){
n_prime[i]=n_prime[i-1];
if(prime[i]==0){
n_prime[i]++;
}
}
// System.out.println("end");
// prime[0]=true;
// prime[1]=1;
}
/*
* long pp[]=new long[10000001];
pp[0]=0;
pp[1]=1;
for(int i=2;i<pp.length;i++){
if(prime[i]!=0){
int gcd=(int)greatestCommonDivisor(i/prime[i], prime[i]);
pp[i]=(pp[i/prime[i]]*pp[prime[i]]*gcd)/pp[(int)gcd];
}
else
pp[i]=i-1;
}
}
* */
class Rmq {
int[] logTable;
int[][] rmq;
int[] a;
public Rmq(int[] a) {
this.a = a;
int n = a.length;
logTable = new int[n + 1];
for (int i = 2; i <= n; i++)
logTable[i] = logTable[i >> 1] + 1;
rmq = new int[logTable[n] + 1][n];
for (int i = 0; i < n; ++i)
rmq[0][i] = i;
for (int k = 1; (1 << k) < n; ++k) {
for (int i = 0; i + (1 << k) <= n; i++) {
int x = rmq[k - 1][i];
int y = rmq[k - 1][i + (1 << k - 1)];
rmq[k][i] = a[x] <= a[y] ? x : y;
}
}
}
public int minPos(int i, int j) {
int k = logTable[j - i];
int x = rmq[k][i];
int y = rmq[k][j - (1 << k) + 1];
return a[x] <= a[y] ? a[x] : a[y];
}
}
public void solve(int testNumber, FastScanner in, PrintWriter out) throws IOException {
int n=in.nextInt();
Pair p[]=new Pair[n];
for(int i=0;i<n;i++){
int x=in.nextInt();
int y=in.nextInt();
p[i]=new Pair(x, y, i);
}
Arrays.sort(p,new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
// TODO Auto-generated method stub
if(o1.x!=o2.x)
return Long.compare(o1.x,o2.x);
else
return Long.compare(o1.y, o2.y);
}
});
//out.println(Arrays.toString(p));
long xsim=0;
long bsim=0;
long temp=1;
long temp1=1;
for(int i=0;i<n-1;i++){
if(p[i].x==p[i+1].x){
temp++;
if(p[i].y==p[i+1].y){
temp1++;
}
else{
// out.println(temp1+ " "+i);
bsim+=(temp1*(temp1-1))/2;
temp1=1;
}
}
else{
xsim+=(temp*(temp-1))/2;
temp=1;
bsim+=(temp1*(temp1-1))/2;
temp1=1;
}
}
// out.println(bsim);
bsim+=(temp1*(temp1-1))/2;
xsim+=(temp*(temp-1))/2;
//out.println(bsim);
Arrays.sort(p,new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
// TODO Auto-generated method stub
if(o1.y!=o2.y)
return Long.compare(o1.y,o2.y);
else
return Long.compare(o1.x, o2.x);
}
});
//out.println(Arrays.toString(p));
long ysim=0;
temp=1;
for(int i=0;i<n-1;i++){
if(p[i].y==p[i+1].y){
temp++;
}
else{
ysim+=(temp*(temp-1))/2;
temp=1;
}
}
ysim+=(temp*(temp-1))/2;
//out.println(xsim+" " +ysim+" "+bsim);;
out.println(ysim+xsim-bsim);;
}
static long greatestCommonDivisor (long m, long n){
long x;
long y;
while(m%n != 0){
x = n;
y = m%n;
m = x;
n = y;
}
return n;
}
}
/*
* long res[]=new long[m];
int cl=1;
int cr=0;
for(int i=0;i<m;i++){
int l=(int)q[i].x;
int r=(int)q[i].y;
while(cl>l){
cl--;
ans+=add(cl);
}
while(cl<l){
ans-=remove(cl);
cl++;
}
while(cr>r){
ans-=remove(cr);
cr--;
}
while(cr<r){
cr++;
ans+=add(cr);
}
res[(int)q[i].index]=ans;
}
for(int i=0;i<m;i++)
out.println(res[i]);
*/
class SegmentTree2D {
public long max(int[][] t, int x1, int y1, int x2, int y2) {
int n = t.length >> 1;
x1 += n;
x2 += n;
int m = t[0].length >> 1;
y1 += m;
y2 += m;
long res = 0;
for (int lx = x1, rx = x2; lx <= rx; lx = (lx + 1) >> 1, rx = (rx - 1) >> 1)
for (int ly = y1, ry = y2; ly <= ry; ly = (ly + 1) >> 1, ry = (ry - 1) >> 1) {
if ((lx & 1) != 0 && (ly & 1) != 0) res = (res+ t[lx][ly]);
if ((lx & 1) != 0 && (ry & 1) == 0) res = (res+ t[lx][ry]);
if ((rx & 1) == 0 && (ly & 1) != 0) res =(res+t[rx][ly]);
if ((rx & 1) == 0 && (ry & 1) == 0) res = (res+ t[rx][ry]);
}
return res;
}
public void add(int[][] t, int x, int y, int value) {
x += t.length >> 1;
y += t[0].length >> 1;
t[x][y] += value;
for (int tx = x; tx > 0; tx >>= 1)
for (int ty = y; ty > 0; ty >>= 1) {
if (tx > 1) t[tx >> 1][ty] = (t[tx][ty]+t[tx ^ 1][ty]);
if (ty > 1) t[tx][ty >> 1] = (t[tx][ty]+ t[tx][ty ^ 1]);
}
// for (int ty = y; ty > 1; ty >>= 1)
// t[x][ty >> 1] = Math.max(t[x][ty], t[x][ty ^ 1]);
// for (int tx = x; tx > 1; tx >>= 1)
// for (int ty = y; ty > 0; ty >>= 1)
// t[tx >> 1][ty] = Math.max(t[tx][ty], t[tx ^ 1][ty]);
// for (int lx=x; lx> 0; lx >>= 1) {
// if (lx > 1)
// t[lx >> 1][y] = Math.max(t[lx][y], t[lx ^ 1][y]);
// for (int ly = y; ly > 1; ly >>= 1)
// t[lx][ly >> 1] = Math.max(t[lx][ly], t[lx][ly ^ 1]);
// }
}
}
class SegmentTree {
// Modify the following 5 methods to implement your custom operations on the tree.
// This example implements Add/Max operations. Operations like Add/Sum, Set/Max can also be implemented.
long modifyOperation(long x, long y) {
return y;
}
// query (or combine) operation
long queryOperation(long leftValue, long rightValue) {
return (leftValue| rightValue);
}
long deltaEffectOnSegment(long delta, long segmentLength) {
// Here you must write a fast equivalent of following slow code:
// int result = delta;
// for (int i = 1; i < segmentLength; i++) result = queryOperation(result, delta);
// return result;
return delta;
}
int getNeutralDelta() {
return 0;
}
int getInitValue() {
return 0;
}
// generic code
int n;
long[] value;
long[] delta; // delta[i] affects value[i], delta[2*i+1] and delta[2*i+2]
long joinValueWithDelta(long value, long delta) {
if (delta == getNeutralDelta()) return value;
return modifyOperation(value, delta);
}
long joinDeltas(long delta1, long delta2) {
if (delta1 == getNeutralDelta()) return delta2;
if (delta2 == getNeutralDelta()) return delta1;
return modifyOperation(delta1, delta2);
}
void pushDelta(int root, int left, int right) {
value[root] = joinValueWithDelta(value[root], deltaEffectOnSegment(delta[root], right - left + 1));
delta[2 * root + 1] = joinDeltas(delta[2 * root + 1], delta[root]);
delta[2 * root + 2] = joinDeltas(delta[2 * root + 2], delta[root]);
delta[root] = getNeutralDelta();
}
public SegmentTree(int n) {
this.n = n;
value = new long[4 * n];
delta = new long[4 * n];
init(0, 0, n - 1);
}
void init(int root, int left, int right) {
if (left == right) {
value[root] = getInitValue();
delta[root] = getNeutralDelta();
} else {
int mid = (left + right) >> 1;
init(2 * root + 1, left, mid);
init(2 * root + 2, mid + 1, right);
value[root] = queryOperation(value[2 * root + 1], value[2 * root + 2]);
delta[root] = getNeutralDelta();
}
}
public long query(int from, int to) {
return query(from, to, 0, 0, n - 1);
}
long query(int from, int to, int root, int left, int right) {
if (from == left && to == right)
return joinValueWithDelta(value[root], deltaEffectOnSegment(delta[root], right - left + 1));
pushDelta(root, left, right);
int mid = (left + right) >> 1;
if (from <= mid && to > mid)
return queryOperation(
query(from, Math.min(to, mid), root * 2 + 1, left, mid),
query(Math.max(from, mid + 1), to, root * 2 + 2, mid + 1, right));
else if (from <= mid)
return query(from, Math.min(to, mid), root * 2 + 1, left, mid);
else if (to > mid)
return query(Math.max(from, mid + 1), to, root * 2 + 2, mid + 1, right);
else
throw new RuntimeException("Incorrect query from " + from + " to " + to);
}
public void modify(int from, int to, long delta) {
modify(from, to, delta, 0, 0, n - 1);
}
void modify(int from, int to, long delta, int root, int left, int right) {
if (from == left && to == right) {
this.delta[root] = joinDeltas(this.delta[root], delta);
return;
}
pushDelta(root, left, right);
int mid = (left + right) >> 1;
if (from <= mid)
modify(from, Math.min(to, mid), delta, 2 * root + 1, left, mid);
if (to > mid)
modify(Math.max(from, mid + 1), to, delta, 2 * root + 2, mid + 1, right);
value[root] = queryOperation(
joinValueWithDelta(value[2 * root + 1], deltaEffectOnSegment(this.delta[2 * root + 1], mid - left + 1)),
joinValueWithDelta(value[2 * root + 2], deltaEffectOnSegment(this.delta[2 * root + 2], right - mid)));
}
}
class LcaSparseTable {
int len;
int[][] up;
int[][] max;
int[] tin;
int[] tout;
int time;
int []lvel;
void dfs(List<Integer>[] tree, int u, int p) {
tin[u] = time++;
lvel[u]=lvel[p]+1;
up[0][u] = p;
if(u!=p)
//max[0][u]=weight(u,p);
for (int i = 1; i < len; i++)
{
up[i][u] = up[i - 1][up[i - 1][u]];
max[i][u]=Math.max(max[i-1][u],max[i-1][up[i-1][u]]);
}
for (int v : tree[u])
if (v != p)
dfs(tree, v, u);
tout[u] = time++;
}
public LcaSparseTable(List<Integer>[] tree, int root) {
int n = tree.length;
len = 1;
while ((1 << len) <= n) ++len;
up = new int[len][n];
max=new int[len][n];
tin = new int[n];
tout = new int[n];
lvel=new int[n];
lvel[root]=0;
dfs(tree, root, root);
}
boolean isParent(int parent, int child) {
return tin[parent] <= tin[child] && tout[child] <= tout[parent];
}
public int lca(int a, int b) {
if (isParent(a, b))
return a;
if (isParent(b, a))
return b;
for (int i = len - 1; i >= 0; i--)
if (!isParent(up[i][a], b))
a = up[i][a];
return up[0][a];
}
public long max(int a,int b){
int lca=lca(a,b);
// System.out.println("LCA "+lca);
long ans=0;
int h=lvel[a]-lvel[lca];
// System.out.println("Height "+h);
int index=0;
while(h!=0){
if(h%2==1){
ans=Math.max(ans,max[index][a]);
a=up[index][a];
}
h/=2;
index++;
}
h=lvel[b]-lvel[lca];
// System.out.println("Height "+h);
index=0;
while(h!=0){
if(h%2==1){
ans=Math.max(ans,max[index][b]);
b=up[index][b];
}
h/=2;
index++;
}
return ans;
}
static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> res, int u,int parent,List<Integer> collection) {
used[u] = true;
Integer uu=new Integer(u);
collection.add(uu);
for (int v : graph[u]){
if (!used[v]){
dfs(graph, used, res, v,u,collection);
}
else if(collection.contains(v)){
System.out.println("Impossible");
System.exit(0);
}
}
collection.remove(uu);
res.add(u);
}
public static List<Integer> topologicalSort(List<Integer>[] graph) {
int n = graph.length;
boolean[] used = new boolean[n];
List<Integer> res = new ArrayList<>();
for (int i = 0; i < n; i++)
if (!used[i])
dfs(graph, used, res, i,-1,new ArrayList<Integer>());
Collections.reverse(res);
return res;
}
static class pairs{
String company,color;
String type;
boolean visit=false;
pairs(String company,String color,String type){
this.company=company;
this.color=color;
this.type=type;
}
}
static void dfs1(List<Integer>[] graph, boolean[] used, List<Integer> res, int u) {
used[u] = true;
for (int v : graph[u])
if (!used[v])
dfs1(graph, used, res, v);
res.add(u);
}
public static List<Integer> topologicalSort1(List<Integer>[] graph) {
int n = graph.length;
boolean[] used = new boolean[n];
List<Integer> res = new ArrayList<>();
for (int i = n-1; i >0; i--)
if (!used[i])
dfs1(graph, used, res, i);
Collections.reverse(res);
return res;
}
public static long[][] mulmatrix(long m1[][],long m2[][],long mod){
long ans[][]=new long[m1.length][m2[0].length];
for(int i=0;i<m1.length;i++){
for(int j=0;j<m2[0].length;j++){
for(int k=0;k<m1.length;k++){
ans[i][j]+=(m1[i][k]*m2[k][j]);
ans[i][j]%=mod;
}
}
}
return ans;
}
public static long[][] matrixexpo(long m[][],String n,long mod){
if(n.equals("1")){
return m.clone();
}
if(n.equals("10")){
return mulmatrix(m, m , mod);
}
else{
long temp [][]=matrixexpo(m,n.substring(0,n.length()-1),mod);
temp=mulmatrix(temp, temp, mod);
if(n.charAt(n.length()-1)=='0')return temp;
else return mulmatrix(temp, m,mod);
}
}
public static boolean isCompatible(long x[],long y[]){
for(int i=0;i<x.length-1;i++){
if(x[i]==y[i] && x[i+1]==y[i+1] && x[i]==x[i+1] && y[i]==y[i+1]){
return false;
}
}
return true;
}
int phi(int n) {
int res = n;
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
while (n % i == 0) {
n /= i;
}
res -= res / i;
}
}
if (n != 1) {
res -= res / n;
}
return res;
}
long pow(long x,long y,long mod){
if(y<=0){
return 1;
}
if(y==1){
return x%mod;
}
long temp=pow(x,y/2,mod);
if(y%2==0){
return (temp*temp)%mod;
}
else{
return (((temp*temp)%mod)*x)%mod;
}
}
/* long DP(int id,int mask){
//System.out.println("hi"+dp[id][mask]+" "+id+" "+Integer.toBinaryString(mask));
if(id==0 && mask==0){
dp[0][mask]=1;
return 1;
}
else if(id==0){
dp[0][mask]=0;
return 0;
}
if(dp[id][mask]!=-1){
return dp[id][mask];
}
long ans=0;
for(int i=0;i<n;i++){
if((mask & (1<<i))!=0 && c[i][id]>=1){
ans+=DP(id-1,mask ^ (1 << i));
ans%=mod;
}
}
ans+=DP(id-1,mask);
ans%=mod;
dp[id][mask]=ans;
return ans;
}*/
long no_of_primes(long m,long n,long k){
long count=0,i,j;
int primes []=new int[(int)(n-m+2)];
if(m==1) primes[0] = 1;
for(i=2; i<=Math.sqrt(n); i++)
{
j = (m/i); j *= i;
if(j<m)
j+=i;
for(; j<=n; j+=i)
{
if(j!=i)
primes[(int)(j-m)] = 1;
}
}
for(i=0; i<=n-m; i++)
if(primes[(int)i]==0 && (i-1)%k==0)
count++;
return count;
}
}
class SegTree {
int n;
long t[];
long mod=(long)(1000000007);
SegTree(int n,long t[]){
this.n=n;
this.t=t;
build();
}
void build() { // build the tree
for (int i = n - 1; i > 0; --i)
t[i]=(t[i<<1]|t[i<<1|1]);
}
void modify(int p, long value) { // set value at position p
for (t[p += n]+=value; p > 1; p >>= 1) t[p>>1] = (t[p]|t[p^1]);
}
long query(int l, int r) { // sum on interval [l, r)
long res=0;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if ((l&1)!=0) res=Math.max(res,t[l++]);
if ((r&1)!=0) res=Math.max(res,t[--r]);
}
return res;
}
//
//
//
}
class FastScanner
{
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private SpaceCharFilter filter;
public FastScanner(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public 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 UF {
private int[] parent; // parent[i] = parent of i
private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31)
private int count; // number of components
public UF(int N) {
if (N < 0) throw new IllegalArgumentException();
count = N;
parent = new int[N];
rank = new byte[N];
for (int i = 0; i < N; i++) {
parent[i] = i;
rank[i] = 0;
}
}
public int find(int p) {
if (p < 0 || p >= parent.length) throw new IndexOutOfBoundsException();
while (p != parent[p]) {
parent[p] = parent[parent[p]]; // path compression by halving
p = parent[p];
}
return p;
}
public int count() {
return count;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public boolean union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return false;
// make root of smaller rank point to root of larger rank
if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
return true;
}
}
class MyArrayList {
private int[] myStore;
private int actSize = 0;
public MyArrayList(){
myStore = new int[2];
}
public int get(int index){
if(index < actSize)
return myStore[index];
else
throw new ArrayIndexOutOfBoundsException();
}
public void add(int obj){
if(myStore.length-actSize <= 1)
increaseListSize();
myStore[actSize++] = obj;
}
public int size(){
return actSize;
}
private void increaseListSize(){
myStore = Arrays.copyOf(myStore, myStore.length*2);
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
8983eb9e69321f65f239bbea22ef45c3
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Created by peacefrog on 3/3/16.
* 10:56 PM
*/
public class Task_C {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
PrintWriter out;
long timeBegin, timeEnd;
public void runIO() throws IOException {
timeBegin = System.currentTimeMillis();
InputStream inputStream;
OutputStream outputStream;
if (ONLINE_JUDGE) {
inputStream = System.in;
Reader.init(inputStream);
outputStream = System.out;
out = new PrintWriter(outputStream);
} else {
inputStream = new FileInputStream("/home/peacefrog/Dropbox/IdeaProjects/Problem Solving/input");
Reader.init(inputStream);
out = new PrintWriter(System.out);
}
solve();
out.flush();
out.close();
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
/*
* Start Solution Here
*/
long nCr(long n, long r) {
if(n < r )return 0;
if (r > n / 2) r = n - r; // because nCr(n, r) == nCr(n, n - r)
long ans = 1;
long i;
for (i = 1; i <= r; i++) {
ans *= n - r + i;
ans /= i;
}
return ans;
}
private void solve() throws IOException {
int n = Reader.nextInt();
Map<Integer , int[] > X = new HashMap<>();
Map<Integer , int[] > Y = new HashMap<>();
Map<Pair , int[] > P = new HashMap<>();
long cx = 0, cy= 0 , cp = 0 ;
for (int i = 0; i < n; i++) {
int x = Reader.nextInt() , y = Reader.nextInt();
Pair pair = new Pair(x, y);
if(X.containsKey(x)) X.get(x)[0]++;
else {
X.put(x , new int[1]);
X.get(x)[0]++;
}
if(Y.containsKey(y)) Y.get(y)[0]++;
else {
Y.put(y , new int[1]);
Y.get(y)[0]++;
}
if(P.containsKey(pair)) P.get(pair)[0]++;
else {
P.put(pair, new int[1]);
P.get(pair)[0]++;
}
}
long result = 0 ;
for (int key : X.keySet()){
cx+=nCr(X.get(key)[0], 2);
}
for (int key : Y.keySet()){
cy+= nCr(Y.get(key)[0], 2);
}
for (Pair p : P.keySet()){
cp+= nCr(P.get(p)[0], 2) ;
}
result = cx+cy - cp;
out.println(result);
}
public class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
public static void main(String[] args) throws IOException {
new Task_C().runIO();
}
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/**
* call this method to initialize reader for InputStream
*/
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/**
* get next word
*/
static String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
static String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
static int nextChar() throws IOException {
return reader.read();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
static int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
c4cfd33eb4b324b4b361e938688dacc9
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Codef{
public static void main(String[] args) throws IOException{
BufferedReader vod=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(vod.readLine());
HashMap<Integer,Integer> mapX=new HashMap<Integer,Integer>();
HashMap<Integer,Integer> mapY=new HashMap<Integer,Integer>();
mas[] pair=new mas[n+1];
StringTokenizer s;
int x=0,y=0;
for(int i=0; i<n; i++){
s=new StringTokenizer(vod.readLine());
x=Integer.parseInt(s.nextToken());
y=Integer.parseInt(s.nextToken());
if (!mapX.containsKey(x))
mapX.put(x, 1);
else
mapX.put(x, mapX.get(x)+1);
if (!mapY.containsKey(y))
mapY.put(y, 1);
else
mapY.put(y,mapY.get(y)+1);
pair[i]=new mas(x,y);
}
pair[n]=new mas(2000000001,2000000001);
Arrays.sort(pair);
int dl=0;
long ans=0;
for(int i=0; i<n; i++){
if (pair[i].x==pair[i+1].x&pair[i].y==pair[i+1].y) dl++;
else{
ans-=(long)dl*(dl+1)/2;
dl=0;
}
}
for(int t:mapX.values())
ans+=(long)t*(t-1)/2;
for(int t:mapY.values())
ans+=(long)t*(t-1)/2;
System.out.print(ans);
}
static class mas implements Comparable<mas>{
int x;
int y;
mas(int x,int y){
this.x=x;
this.y=y;
}
@Override
public int compareTo(mas o) {
return (this.x!=o.x)? this.x-o.x:this.y-o.y;
}
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
dc989e8362f93bc4afc897bb7d9dfe1d
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class C {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long res = 0;
Integer n = Integer.parseInt(br.readLine());
Map<Long, Long> fPerX = new HashMap<Long, Long>();
Map<Long, Long> fPerY = new HashMap<Long, Long>();
Map<String, Long> f = new HashMap<String, Long>();
for (int i = 0; i < n; i++) {
String[] data = br.readLine().split(" ");
Long x = Long.parseLong(data[0]);
Long y = Long.parseLong(data[1]);
addToFrequencyMap(f, x+""+y);
addToFrequencyMap(fPerX, x);
addToFrequencyMap(fPerY, y);
}
for (Entry<Long, Long> entry: fPerX.entrySet()) {
res += entry.getValue() * (entry.getValue()-1) / 2;
}
for (Entry<Long, Long> entry: fPerY.entrySet()) {
res += entry.getValue() * (entry.getValue()-1) / 2;
}
for (Entry<String, Long> entry: f.entrySet()) {
res -= entry.getValue() * (entry.getValue()-1) / 2;
}
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
}
public static <K> void addToFrequencyMap(Map<K, Long> map, K key) {
if (map.containsKey(key)) {
map.put(key, map.get(key) + 1);
} else {
map.put(key, 1l);
}
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
5b016778d94d70d0646a0f28cbc60a19
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
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 Main2
{
static StringTokenizer st=new StringTokenizer("");
static BufferedReader br;
///////////////////////////////////////////////////////////////////////////////////
public static void main(String args[]) throws FileNotFoundException, IOException, Exception
{
//Scanner in =new Scanner(new FileReader("input.txt"));
//PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//Scanner in=new Scanner(System.in);
br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
//StringTokenizer st;//=new StringTokenizer(br.readLine());
//////////////////////////////////////////////////////////////////////////////////////
int n=ni();
TreeMap<String,Integer> map=new TreeMap<String,Integer>();
TreeMap<Integer,Integer> xmap=new TreeMap<Integer,Integer>();
TreeMap<Integer,Integer> ymap=new TreeMap<Integer,Integer>();
for(int i=0;i<n;i++)
{
int x=ni(),y=ni();
String s=x+" "+y;
if(map.containsKey(s)) map.put(s,map.get(s)+1);
else map.put(s,1);
if(xmap.containsKey(x)) xmap.put(x,xmap.get(x)+1);
else xmap.put(x,1);
if(ymap.containsKey(y)) ymap.put(y,ymap.get(y)+1);
else ymap.put(y,1);
}
long ans=0;
for(int k: xmap.keySet())
{
if(xmap.get(k)>1)
{
int temp=xmap.get(k);
ans+=((long)(temp)*(temp-1))/2l;
}
}
for(int k: ymap.keySet())
{
if(ymap.get(k)>1)
{
int temp=ymap.get(k);
ans+=((long)(temp) * (temp-1))/2l;
}
}
for(String k: map.keySet())
{
if(map.get(k)>1)
{
int temp=map.get(k);
ans-=((long)(temp)*(temp-1))/2l;
}
}
out.print(ans);
//////////////////////////////////////////////////////////////////////////////////////
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(first+second > o.first+o.second)
return 1;
else if(first+second < o.first+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 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
056d633e211336d68a82952db8f89929
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.util.*;
public class C{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Hashtable<Long, Long> xfreq = new Hashtable<Long, Long>();
Hashtable<Long, Long> yfreq = new Hashtable<Long, Long>();
Hashtable<String, Long> seenPoints = new Hashtable<String, Long>();
long dupes = 0;
long n = in.nextLong();
for(long i = 0 ; i < n; i++){
long x = in.nextLong();
long y = in.nextLong();
if (xfreq.containsKey(x)){
xfreq.put(x, xfreq.get(x) + 1L);
}else{
xfreq.put(x, 1L);
}
if (yfreq.containsKey(y)){
yfreq.put(y, yfreq.get(y) + 1L);
}else{
yfreq.put(y, 1L);
}
String line = new String(x + " " + y);
if (seenPoints.containsKey(line)){
seenPoints.put(line, seenPoints.get(line) + 1L);
}else{
seenPoints.put(line, 1L);
}
}
long result = 0;
for (Long key : xfreq.keySet()){
result += choose2(xfreq.get(key));
}
for (Long key : yfreq.keySet()){
result += choose2(yfreq.get(key));
}
for (Long val: seenPoints.values()){
dupes += choose2(val);
}
// System.out.println(dupes);
// System.out.println(choose2(dupes));
// System.out.println(result);
result -= dupes;
System.out.println(result);
}
public static long choose2(long n){
return (n*(n-1))/2;
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
e401b670ad004154cf79d23e7f6c5f94
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
/**
*
*/
/**
* 2016��3��7�� ����6:39:02
* PrjName:cf345-03
* @ Semprathlon
*/
import java.io.*;
import java.util.*;
public class Main {
static Map<Integer, Integer> h=new HashMap<Integer, Integer>();
static Map<Integer, Integer> v=new HashMap<Integer, Integer>();
static Map<Long, Integer> p=new HashMap<Long, Integer>();
static long hash(long x,long y){
return x*1000000000L+y;
}
public static void main(String[] args) throws IOException{
InputReader in=new InputReader(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=in.nextInt();
h.clear();v.clear();p.clear();
for(int i=1;i<=n;i++){
int x=in.nextInt();
int y=in.nextInt();
int hh=(h.get(x)==null)?0:h.get(x);
int vv=(v.get(y)==null)?0:v.get(y);
int pp=(p.get(hash(x, y))==null)?0:p.get(hash(x, y));
h.put(x, hh+1);
v.put(y, vv+1);
p.put(hash(x, y), pp+1);
}
long ans=0;
for(Iterator<Map.Entry<Integer, Integer>> it=h.entrySet().iterator();it.hasNext();){
Map.Entry<Integer, Integer> en=it.next();
ans+=((long)en.getValue()*(long)(en.getValue()-1))>>1;
}
for(Iterator<Map.Entry<Integer, Integer>> it=v.entrySet().iterator();it.hasNext();){
Map.Entry<Integer, Integer> en=it.next();
ans+=((long)en.getValue()*(long)(en.getValue()-1))>>1;
}
for(Iterator<Map.Entry<Long, Integer>> it=p.entrySet().iterator();it.hasNext();){
Map.Entry<Long, Integer> en=it.next();
ans-=((long)en.getValue()*(long)(en.getValue()-1))>>1;
}
out.println(ans);
out.flush();
out.close();
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String nextLine() {
String tmp = null;
try {
tmp = reader.readLine();
tokenizer = new StringTokenizer(tmp);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (NullPointerException e) {
return null;
}
return tmp;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
d8a01de11a36678f8445fb5031f05d36
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.awt.Point;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigDecimal;
/**
*
* @author Mojtaba
*/
public class Main {
public static void main(String[] args) throws IOException, Exception {
MyScanner in = new MyScanner(System.in);
//Scanner in = new Scanner(System.in);
//Scanner in = new Scanner(new File("input.txt"));
PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out));
StringBuilder sb = new StringBuilder("");
int n = in.nextInt();
HashMap<Integer, MyData> X = new HashMap<>();
HashMap<Integer, MyData> Y = new HashMap<>();
HashMap<Point, MyData> points = new HashMap<>();
for (int i = 0, x, y; i < n; i++) {
x = in.nextInt();
y = in.nextInt();
if (!points.containsKey(new Point(x, y))) {
points.put(new Point(x, y), new MyData(1));
} else {
points.get(new Point(x, y)).data++;
}
if (!X.containsKey(x)) {
X.put(x, new MyData(1));
} else {
X.get(x).data++;
}
if (!Y.containsKey(y)) {
Y.put(y, new MyData(1));
} else {
Y.get(y).data++;
}
}
long ans = 0L;
for (Map.Entry<Integer, MyData> e : X.entrySet()) {
ans += (e.getValue().data * (e.getValue().data - 1)) / 2;
}
for (Map.Entry<Integer, MyData> e : Y.entrySet()) {
ans += (e.getValue().data * (e.getValue().data - 1)) / 2;
}
for (Map.Entry<Point, MyData> e : points.entrySet()) {
ans -= (e.getValue().data * (e.getValue().data - 1)) / 2;
}
sb.append(ans);
writer.println(sb.toString().trim());
writer.flush();
in.close();
}
}
class MyData {
public long data;
public MyData(long data) {
this.data = data;
}
}
class MyScanner {
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntegerArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextLong();
}
return a;
}
public int nextInt(int radix) throws IOException {
return Integer.parseInt(next(), radix);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public long nextLong(int radix) throws IOException {
return Long.parseLong(next(), radix);
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
public BigInteger nextBigInteger(int radix) throws IOException {
return new BigInteger(next(), radix);
}
public String next() throws IOException {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
return this.next();
}
return tokenizer.nextToken();
}
public void close() throws IOException {
this.reader.close();
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
0e81d0cd933dcc25d65697e8cb258713
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.awt.Point;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigDecimal;
/**
*
* @author Mojtaba
*/
public class Main {
public static void main(String[] args) throws IOException, Exception {
MyScanner in = new MyScanner(System.in);
//Scanner in = new Scanner(System.in);
//Scanner in = new Scanner(new File("input.txt"));
PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out));
StringBuilder sb = new StringBuilder("");
int n = in.nextInt();
HashMap<Integer, MyData> X = new HashMap<>();
HashMap<Integer, MyData> Y = new HashMap<>();
HashMap<Point, MyData> points = new HashMap<>();
for (int i = 0, x, y; i < n; i++) {
x = in.nextInt();
y = in.nextInt();
if (!points.containsKey(new Point(x, y))) {
points.put(new Point(x, y), new MyData(1));
} else {
points.get(new Point(x, y)).data++;
}
if (!X.containsKey(x)) {
X.put(x, new MyData(1));
} else {
X.get(x).data++;
}
if (!Y.containsKey(y)) {
Y.put(y, new MyData(1));
} else {
Y.get(y).data++;
}
}
long ans = 0L;
for (Map.Entry<Integer, MyData> e : X.entrySet()) {
if (e.getValue().data > 1) {
ans += (e.getValue().data * (e.getValue().data - 1)) / 2;
}
}
for (Map.Entry<Integer, MyData> e : Y.entrySet()) {
if (e.getValue().data > 1) {
ans += (e.getValue().data * (e.getValue().data - 1)) / 2;
}
}
for (Map.Entry<Point, MyData> e : points.entrySet()) {
if (e.getValue().data > 1) {
ans -= (e.getValue().data * (e.getValue().data - 1)) / 2;
}
}
sb.append(ans);
writer.println(sb.toString().trim());
writer.flush();
in.close();
}
}
class MyData {
public long data;
public MyData(long data) {
this.data = data;
}
}
class MyScanner {
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntegerArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextLong();
}
return a;
}
public int nextInt(int radix) throws IOException {
return Integer.parseInt(next(), radix);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public long nextLong(int radix) throws IOException {
return Long.parseLong(next(), radix);
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
public BigInteger nextBigInteger(int radix) throws IOException {
return new BigInteger(next(), radix);
}
public String next() throws IOException {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
return this.next();
}
return tokenizer.nextToken();
}
public void close() throws IOException {
this.reader.close();
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
32ccc62549c762efa421ffeb34020d00
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.awt.Point;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigDecimal;
/**
*
* @author Mojtaba
*/
public class Main {
public static void main(String[] args) throws IOException, Exception {
MyScanner in = new MyScanner(System.in);
//Scanner in = new Scanner(System.in);
//Scanner in = new Scanner(new File("input.txt"));
PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out));
StringBuilder sb = new StringBuilder("");
int n = in.nextInt();
HashMap<Integer, MyData> X = new HashMap<>();
HashMap<Integer, MyData> Y = new HashMap<>();
HashMap<Point, MyData> points = new HashMap<>();
for (int i = 0, x, y; i < n; i++) {
x = in.nextInt();
y = in.nextInt();
if (!points.containsKey(new Point(x, y))) {
points.put(new Point(x, y), new MyData(1));
} else {
points.get(new Point(x, y)).data++;
}
if (!X.containsKey(x)) {
X.put(x, new MyData(1));
} else {
X.get(x).data++;
}
if (!Y.containsKey(y)) {
Y.put(y, new MyData(1));
} else {
Y.get(y).data++;
}
}
long ans = 0L;
for (Map.Entry<Integer, MyData> e : X.entrySet()) {
ans += (e.getValue().data * (e.getValue().data - 1)) >> 1;
}
for (Map.Entry<Integer, MyData> e : Y.entrySet()) {
ans += (e.getValue().data * (e.getValue().data - 1)) >> 1;
}
for (Map.Entry<Point, MyData> e : points.entrySet()) {
ans -= (e.getValue().data * (e.getValue().data - 1)) >> 1;
}
sb.append(ans);
writer.println(sb.toString().trim());
writer.flush();
in.close();
}
}
class MyData {
public long data;
public MyData(long data) {
this.data = data;
}
}
class MyScanner {
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntegerArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextLong();
}
return a;
}
public int nextInt(int radix) throws IOException {
return Integer.parseInt(next(), radix);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public long nextLong(int radix) throws IOException {
return Long.parseLong(next(), radix);
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
public BigInteger nextBigInteger(int radix) throws IOException {
return new BigInteger(next(), radix);
}
public String next() throws IOException {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
return this.next();
}
return tokenizer.nextToken();
}
public void close() throws IOException {
this.reader.close();
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
9d38c314ba14bca617e7533eaf6f6bab
|
train_000.jsonl
|
1457342700
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class C651 {
public static void main(String[] args) throws IOException {
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt();
long[] xs = new long[n], ys = new long[n];
for(int i = 0; i<n; i++)
{
xs[i] = input.nextLong();
ys[i] = input.nextLong();
}
long res = 0;
HashMap<Long, Integer> xmap = new HashMap<Long, Integer>();
HashMap<Long, Integer> ymap = new HashMap<Long, Integer>();
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
for(int i = 0; i<n; i++)
{
int getX = xmap.containsKey(xs[i]) ? xmap.get(xs[i]) : 0;
int getY = ymap.containsKey(ys[i]) ? ymap.get(ys[i]) : 0;
long kk = xs[i] * (long)(2e9+7) + ys[i];
int tot = map.containsKey(kk) ? map.get(kk) : 0;
res += getX + getY - tot;
map.put(kk, tot+1);
xmap.put(xs[i], getX+1);
ymap.put(ys[i], getY+1);
}
out.println(res);
out.close();
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
|
Java
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
3 seconds
|
["2", "11"]
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Java 7
|
standard input
|
[
"data structures",
"geometry",
"implementation",
"sortings"
] |
bd7b85c0204f6b36dc07f8a96fc36161
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
| 1,400 |
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
standard output
| |
PASSED
|
93ae15778c84b579d8c22c03748422c1
|
train_000.jsonl
|
1422894600
|
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: These k dots are different: if i ≠ j then di is different from dj. k is at least 4. All dots belong to the same color. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Solution{
static int n,m;
static boolean visited[][];
static boolean status=false;
public static void dfs(String[] game,int x,int y,int px,int py)
{
if(visited[x][y])
{
//System.out.println(x+" "+y);
status=true;
return;
}
//System.out.println("( "+px+","+py+") --> "+"( "+x+","+y+")");
visited[x][y]=true;
char clor=game[x].charAt(y);
if( x+1<n && !(x+1==px && y==py) && game[x+1].charAt(y)==clor)
dfs(game,x+1,y,x,y);
if( y+1<m && !(x==px && y+1==py) && game[x].charAt(y+1)==clor)
dfs(game,x,y+1,x,y);
if( x-1>=0 && !(x-1==px && y==py) && game[x-1].charAt(y)==clor)
dfs(game,x-1,y,x,y);
if( y-1>=0 && !(x==px && y-1==py) && game[x].charAt(y-1)==clor)
dfs(game,x,y-1,x,y);
}
public static void main(String arg[])throws IOException
{
BufferedReader io =new BufferedReader(new InputStreamReader(System.in));
String[] input1 = io.readLine().trim().split(" ");
n = Integer.parseInt(input1[0]);
m = Integer.parseInt(input1[1]);
String game[]= new String[n];
for(int i=0;i<n;i++)
game[i]=io.readLine().trim();
visited =new boolean[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(!visited[i][j])
dfs(game,i,j,-1,-1);
if(status)
System.out.println("Yes");
else
System.out.println("No");
return ;
}
}
|
Java
|
["3 4\nAAAA\nABCA\nAAAA", "3 4\nAAAA\nABCA\nAADA", "4 4\nYYYR\nBYBY\nBBBY\nBBBY", "7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB", "2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ"]
|
2 seconds
|
["Yes", "No", "Yes", "Yes", "No"]
|
NoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
|
Java 11
|
standard input
|
[
"dfs and similar"
] |
73930603e440eef854da4ba51253a5a7
|
The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.
| 1,500 |
Output "Yes" if there exists a cycle, and "No" otherwise.
|
standard output
| |
PASSED
|
4e18de8494dd1236e97c40e0739c74bb
|
train_000.jsonl
|
1422894600
|
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: These k dots are different: if i ≠ j then di is different from dj. k is at least 4. All dots belong to the same color. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.
|
256 megabytes
|
import java.util.*;
public class FoxAndTwoDots {
public static boolean findCycle=false;
public static int[] dx= {1,-1,0,0};
public static int[] dy= {0,0,1,-1};
public static void dfs(int x,int y,int fromx,int fromy, char colour,int n,int m,String[] arr,boolean[][] visited) {
if(x<0 || y<0 || x>=n || y>=m) {
return;
}
if(arr[x].charAt(y)!=colour) {
return;
}
if(visited[x][y]) {
findCycle=true;
return;
}
visited[x][y]=true;
for(int i=0;i<4;i++) {
int nextx=x+dx[i];
int nexty=y+dy[i];
if(nextx==fromx && nexty==fromy) {
continue;
}
dfs(nextx,nexty,x,y,colour,n,m,arr,visited);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int m=input.nextInt();
String[] arr= new String[n];
for(int i=0;i<n;i++) {
String a=input.next();
arr[i]=a;
}
boolean[][] visited=new boolean[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
visited[i][j]=false;
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(!visited[i][j]) {
dfs(i,j,-1,-1,arr[i].charAt(j),n,m,arr,visited);
}
}
}
if(findCycle) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
|
Java
|
["3 4\nAAAA\nABCA\nAAAA", "3 4\nAAAA\nABCA\nAADA", "4 4\nYYYR\nBYBY\nBBBY\nBBBY", "7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB", "2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ"]
|
2 seconds
|
["Yes", "No", "Yes", "Yes", "No"]
|
NoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
|
Java 11
|
standard input
|
[
"dfs and similar"
] |
73930603e440eef854da4ba51253a5a7
|
The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.
| 1,500 |
Output "Yes" if there exists a cycle, and "No" otherwise.
|
standard output
| |
PASSED
|
9b488b3a18420591fa10c43f5c95776c
|
train_000.jsonl
|
1422894600
|
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: These k dots are different: if i ≠ j then di is different from dj. k is at least 4. All dots belong to the same color. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.
|
256 megabytes
|
import java.util.*;
public class Main {
public static void union(Node A,Node B,int rank[]) {
Node x=find(A);
Node y=find(B);
if(x.val==y.val)return;
else if(rank[x.val]<rank[y.val]) {x.par=y;}
else if(rank[x.val]>rank[y.val]) {y.par=x;}
else if(rank[x.val]==rank[y.val]) {x.par=y;rank[y.val]++;}
}
static Node find(Node A) {
if(A.par==null)return A;
Node par=find(A.par);
A.par=par;
return par;
}
static boolean isSame(Node A,Node B) {
Node x=find(A);
Node y=find(B);
if(x.val==y.val)return true;
else return false;
}
public static void main(String...args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
Node c[][]=new Node[n][m];
int rank[]=new int[n*m];
for(int i=0;i<n;i++) {
String s=sc.next();
for(int j=0;j<m;j++) {
c[i][j]=new Node(s.charAt(j),i*m+j);
}
}
//boolean cycle=true;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
Node x=c[i][j];
Node y=null,z=null;
if(j+1<m) y=c[i][j+1];
if(i+1<n) z=c[i+1][j];
if(y!=null&&x.z==y.z) {
//System.out.println(isSame(x,y));
if(isSame(x,y)) {System.out.println("Yes");return;}
else union(x,y,rank);
}
if(z!=null&&z.z==x.z) {
if(isSame(x,z)) {System.out.println("Yes");return;}
else union(x,z,rank);
}
}
}
System.out.println("No");
}
}
class Node{
int val;Node par=null;char z;
Node(char z,int val){this.val=val;this.z=z;}
}
|
Java
|
["3 4\nAAAA\nABCA\nAAAA", "3 4\nAAAA\nABCA\nAADA", "4 4\nYYYR\nBYBY\nBBBY\nBBBY", "7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB", "2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ"]
|
2 seconds
|
["Yes", "No", "Yes", "Yes", "No"]
|
NoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
|
Java 11
|
standard input
|
[
"dfs and similar"
] |
73930603e440eef854da4ba51253a5a7
|
The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.
| 1,500 |
Output "Yes" if there exists a cycle, and "No" otherwise.
|
standard output
| |
PASSED
|
3b8fa70a42728722bfb299a92271cc26
|
train_000.jsonl
|
1422894600
|
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: These k dots are different: if i ≠ j then di is different from dj. k is at least 4. All dots belong to the same color. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static class Pair{
int r, c;
public Pair(int r, int c){
this.r = r;
this.c = c;
}
}
static boolean isValid(int i, int j, int n, int m, char c, char arr[][]){
return !(i < 0 || j < 0 || i >= n || j >= m || c != arr[i][j]);
}
static boolean bfs(int i, int j, char arr[][], int n, int m, boolean visited[][]){
Queue<Pair> q = new LinkedList<>();
Pair pp = new Pair(i, j);
q.add(pp);
visited[i][j] = true;
char ch = arr[i][j];
HashSet<String> edge = new HashSet<>(), node = new HashSet<>();
node.add(i+" "+j);
int nr, nc, r, c;
while(!q.isEmpty()){
pp = q.poll();
r = pp.r;
c = pp.c;
for(int k = 0; k < 4; k++){
nr = r + x_coord[k];
nc = c + y_coord[k];
if(!isValid(nr, nc, n, m, ch, arr))
continue;
if(!edge.contains(r+" "+c+" "+nr+" "+nc) &&
!edge.contains(nr+" "+nc+" "+r+" "+c))
edge.add(r+" "+c+" "+nr+" "+nc);
if(!node.contains(nr+" "+nc))
node.add(nr+" "+nc);
if(!visited[nr][nc]){
visited[nr][nc] = true;
q.add(new Pair(nr, nc));
}
}
}
return node.size() - 1 != edge.size();
}
public static void process(int test_number)throws IOException
{
int n = ni(), m = ni();
char arr[][] = new char[n][];
for(int i = 0; i < n; i++)
arr[i] = nln().toCharArray();
boolean visited[][] = new boolean[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(visited[i][j])
continue;
if(bfs(i, j, arr, n, m, visited)){
pn("Yes");
return ;
}
}
}
pn("No");
}
static final long mod = (long)1e9+7l;
static final int x_coord[] = {1, 0, -1, 0}, y_coord[] = {0, 1, 0, -1};
static FastReader sc;
static PrintWriter out;
public static void main(String[]args)throws IOException
{
out = new PrintWriter(System.out);
sc = new FastReader();
long s = System.currentTimeMillis();
int t = 1;
//t = ni();
for(int i = 1; i <= t; i++)
process(i);
out.flush();
System.err.println(System.currentTimeMillis()-s+"ms");
}
static void trace(Object... o){ System.err.println(Arrays.deepToString(o)); };
static void pn(Object o){ out.println(o); }
static void p(Object o){ out.print(o); }
static int ni()throws IOException{ return Integer.parseInt(sc.next()); }
static long nl()throws IOException{ return Long.parseLong(sc.next()); }
static double nd()throws IOException{ return Double.parseDouble(sc.next()); }
static String nln()throws IOException{ return sc.nextLine(); }
static long gcd(long a, long b)throws IOException{ return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{ return (b==0)?a:gcd(b,a%b); }
static int bit(long n)throws IOException{ return (n==0)?0:(1+bit(n&(n-1))); }
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); }
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
}
|
Java
|
["3 4\nAAAA\nABCA\nAAAA", "3 4\nAAAA\nABCA\nAADA", "4 4\nYYYR\nBYBY\nBBBY\nBBBY", "7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB", "2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ"]
|
2 seconds
|
["Yes", "No", "Yes", "Yes", "No"]
|
NoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
|
Java 11
|
standard input
|
[
"dfs and similar"
] |
73930603e440eef854da4ba51253a5a7
|
The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.
| 1,500 |
Output "Yes" if there exists a cycle, and "No" otherwise.
|
standard output
| |
PASSED
|
563853fd6ad298a8a7c40477e355fb84
|
train_000.jsonl
|
1422894600
|
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: These k dots are different: if i ≠ j then di is different from dj. k is at least 4. All dots belong to the same color. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
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;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BFoxAndTwoDots solver = new BFoxAndTwoDots();
solver.solve(1, in, out);
out.close();
}
static class BFoxAndTwoDots {
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<Integer>[] adjL = new ArrayList[n * m + 1];
for (int i = 0; i < adjL.length; i++)
adjL[i] = new ArrayList<>();
char[][] grid = new char[n][m];
for (int i = 0; i < n; i++)
grid[i] = sc.next().toCharArray();
int[] dx = {0, 1, -1, 0}, dy = {1, 0, 0, -1};
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
for (int z = 0; z < 4; z++) {
if (i + dx[z] < n && i + dx[z] >= 0 &&
j + dy[z] < m && j + dy[z] >= 0 && grid[i][j] == grid[i + dx[z]][j + dy[z]])
adjL[i * m + j].add((i + dx[z]) * m + j + dy[z]);
}
}
for (int i = 0; i < n * m; i++) {
boolean[] vis = new boolean[n * m + 1];
if (dfs(i, vis, adjL, 1, i)) {
pw.println("Yes");
return;
}
}
pw.println("No");
}
private boolean dfs(int u, boolean[] vis, ArrayList<Integer>[] adjL, int length, int start) {
vis[u] = true;
for (int v : adjL[u]) {
if (v == start && length >= 4)
return true;
if (!vis[v] && dfs(v, vis, adjL, length + 1, start))
return true;
}
return false;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["3 4\nAAAA\nABCA\nAAAA", "3 4\nAAAA\nABCA\nAADA", "4 4\nYYYR\nBYBY\nBBBY\nBBBY", "7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB", "2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ"]
|
2 seconds
|
["Yes", "No", "Yes", "Yes", "No"]
|
NoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
|
Java 11
|
standard input
|
[
"dfs and similar"
] |
73930603e440eef854da4ba51253a5a7
|
The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.
| 1,500 |
Output "Yes" if there exists a cycle, and "No" otherwise.
|
standard output
| |
PASSED
|
ff0adae3f5a1c41cc864d4a516d92043
|
train_000.jsonl
|
1422894600
|
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: These k dots are different: if i ≠ j then di is different from dj. k is at least 4. All dots belong to the same color. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class ladders510b {
static BufferedReader __in;
static PrintWriter __out;
static StringTokenizer input;
static char[][] b;
static Set<P> visited = new HashSet<>();
static int n, m, dir4[][] = {{0, -1}, {-1, 0}, {1, 0}, {0, 1}};
public static void main(String[] args) throws IOException {
__in = new BufferedReader(new InputStreamReader(System.in));
__out = new PrintWriter(new OutputStreamWriter(System.out));
read();
n = nextInt();
m = nextInt();
b = new char[n][m];
for(int i = 0; i < n; ++i) {
char[] l = readLine().toCharArray();
for(int j = 0; j < m; ++j) {
b[i][j] = l[j];
}
}
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
if(!visited.contains(new P(i, j))) {
if(dfs(b[i][j], i, j, -1, -1)) {
printy();
close();
return;
}
}
}
}
printn();
close();
}
static boolean dfs(char c, int i, int j, int parI, int parJ) {
if(visited.contains(new P(i, j))) {
return true;
}
// println(c + ": " + new P(i, j));
visited.add(new P(i, j));
for(int[] dir : dir4) {
int x = i + dir[0], y = j + dir[1];
if(x >= 0 && x < n && y >= 0 && y < m && b[x][y] == c && (x != parI || y != parJ)) {
if(dfs(c, x, y, i, j)) {
return true;
}
}
}
return false;
}
static class P {
int a, b;
P(int a_, int b_) {
a = a_;
b = b_;
}
@Override
public String toString() {
return "Pair{" + "a = " + a + ", b = " + b + '}';
}
public boolean equalsUnchecked(Object o) {
P p = (P)o;
return a == p.a && b == p.b;
}
@Override
public boolean equals(Object o) {
if(this == o) return true;
if(o == null || getClass() != o.getClass()) return false;
P p = (P)o;
return a == p.a && b == p.b;
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
}
static final int IBIG = 100000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
static void read() throws IOException {input = new StringTokenizer(__in.readLine());}
static String readLine() throws IOException {return __in.readLine();}
static int nextInt() {return Integer.parseInt(input.nextToken());}
static int readInt() throws IOException {return Integer.parseInt(__in.readLine());}
static void print(String s) {__out.print(s);}
static void println(String s) {__out.println(s);}
static void print(Object o) {__out.print(o);}
static void println(Object o) {__out.println(o);}
static void printy() {__out.println("Yes");}
static void printn() {__out.println("No");}
static void printyn(boolean b) {__out.println(b ? "Yes" : "No");}
static void println(int[] a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), i++); __out.println(a[a.length - 1]);}
static void println() {__out.println();}
static void close() {__out.close();}
}
|
Java
|
["3 4\nAAAA\nABCA\nAAAA", "3 4\nAAAA\nABCA\nAADA", "4 4\nYYYR\nBYBY\nBBBY\nBBBY", "7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB", "2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ"]
|
2 seconds
|
["Yes", "No", "Yes", "Yes", "No"]
|
NoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
|
Java 11
|
standard input
|
[
"dfs and similar"
] |
73930603e440eef854da4ba51253a5a7
|
The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.
| 1,500 |
Output "Yes" if there exists a cycle, and "No" otherwise.
|
standard output
| |
PASSED
|
edcc6f960b274af24cac5c53d596671c
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main
{
static InputReader in;
static OutputWriter out;
static final boolean OJ = System.getProperty("ONLINE_JUDGE") != null;
public static void main(String[] args) throws IOException
{
in = new InputReader(OJ ? System.in : new FileInputStream("in.txt"));
out = new OutputWriter(OJ ? System.out : new FileOutputStream("out.txt"));
run();
out.close();
System.exit(0);
}
private static void run() throws IOException
{
int N = (int) (1e5)+3;
boolean[] primes = sieve(N);
int[] distance = calculate(primes, N);
int n = in.getInt(), m = in.getInt();
int[][] matrix = in.getIntTable(n, m);
int min = Integer.MAX_VALUE;
for (int r = 0; r < n; r++)
{
int amount = 0;
for (int c = 0; c < m; c++)
{
int a = matrix[r][c];
if (!primes[a]) amount += distance[a];
}
if(amount < min) min =amount;
}
for (int col = 0; col < m; col++)
{
int amount = 0;
for (int row = 0; row < n; row++)
{
int a = matrix[row][col];
if (!primes[a]) amount += distance[a];
}
if(amount < min) min =amount;
}
out.println(min);
}
private static int[] calculate(boolean[] primes, int n)
{
int[] table = new int[n + 1];
Arrays.fill(table, Integer.MAX_VALUE);
table[0] = 2;
table[1] = 1;
for (int i = 2; i <= n; i++) table[i] = getAmount(i, primes);
return table;
}
private static int getAmount(int a, boolean[] primes)
{
if (a == 1) return 1;
for (int go = 0; a < primes.length; a++)
{
if (primes[a]) return go;
go++;
}
return Integer.MAX_VALUE;
}
private static boolean[] sieve(int n)
{
boolean[] table = new boolean[n + 1];
table[2] = true;
int i;
for (i = 3; i <= n; i += 2) table[i] = true;
for (i = 3; i * i <= n; i += 2)
{
if (table[i])
{
for (int j = i * i; j <= n; j += i) table[j] = false;
}
}
return table;
}
private static boolean digitsDistinct(int year)
{
boolean[] table = new boolean[10];
while (year > 0)
{
int r = year % 10;
if (table[r]) return false;
table[r] = true;
year /= 10;
}
return true;
}
}
class InputReader
{
private BufferedReader reader;
private StringTokenizer st;
public InputReader(InputStream stream)
{
reader = new BufferedReader(new InputStreamReader(stream), 1024);
}
public String getString() throws IOException
{
while (st == null || !st.hasMoreTokens())
{
String line = reader.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
public String getLine() throws IOException
{
return reader.readLine();
}
public int getInt() throws IOException
{
return Integer.parseInt(getString());
}
public long getLong() throws IOException
{
return Long.parseLong(getString());
}
public double getDouble() throws IOException
{
return Double.parseDouble(getString());
}
public boolean ready() throws IOException
{
return reader.ready();
}
public int[][] getIntTable(int rowCount, int columnCount) throws IOException
{
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) table[i] = getIntArray(columnCount);
return table;
}
public int[] getIntArray(int len) throws IOException
{
int[] table = new int[len];
for (int i = 0; i < len; i++) table[i] = getInt();
return table;
}
}
class OutputWriter
{
private PrintWriter writer;
public OutputWriter(OutputStream stream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0) writer.print(' ');
writer.print(objects[i].toString());
}
}
public void print(String s, Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0) writer.print(s);
writer.print(objects[i].toString());
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void printf(String format, Object... objects)
{
writer.printf(format, objects);
}
public void close()
{
writer.close();
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
6de6cbb48480ada7207da60d81d24b5a
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main
{
static InputReader in;
static OutputWriter out;
static final boolean OJ = System.getProperty("ONLINE_JUDGE") != null;
public static void main(String[] args) throws IOException
{
in = new InputReader(OJ ? System.in : new FileInputStream("in.txt"));
out = new OutputWriter(OJ ? System.out : new FileOutputStream("out.txt"));
run();
out.close();
System.exit(0);
}
private static void run() throws IOException
{
int N = (int) (1e5)+3;
boolean[] primes = sieve(N);
int[] distance = calculate(primes, N);
int n = in.getInt(), m = in.getInt();
int[][] matrix = in.getIntTable(n, m);
int min = Integer.MAX_VALUE;
for (int r = 0; r < n; r++)
{
int amount = 0;
for (int c = 0; c < m; c++)
{
int a = matrix[r][c];
if (!primes[a]) amount += distance[a];
}
if(amount < min) min =amount;
}
for (int col = 0; col < m; col++)
{
int amount = 0;
for (int row = 0; row < n; row++)
{
int a = matrix[row][col];
if (!primes[a]) amount += distance[a];
}
if(amount < min) min =amount;
}
out.println(min);
}
private static int[] calculate(boolean[] primes, int n)
{
int[] table = new int[n + 1];
Arrays.fill(table, Integer.MAX_VALUE);
table[0] = 2;
table[1] = 1;
for (int i = 2; i <= n; i++) table[i] = getAmount(i, primes);
return table;
}
private static int getAmount(int a, boolean[] primes)
{
if (a == 1) return 1;
for (int go = 0; a < primes.length; a++)
{
if (primes[a]) return go;
go++;
}
return Integer.MAX_VALUE;
}
public static boolean[] sieve(int N)
{
boolean[] table = new boolean[N + 1];
int squareRoot = (int) Math.sqrt(N);
int xStepsize = 3, y_limit = 0, n = 0;
int temp = ((int) Math.sqrt((N - 1) / 3));
for (int i = 0; i < 12 * temp; i += 24)
{
xStepsize += i;
y_limit = (12 * (int) Math.sqrt(N - xStepsize)) - 36;
n = xStepsize + 16;
for (int j = -12; j < y_limit + 1; j += 72)
{
n += j; table[n] = !table[n];
}
n = xStepsize + 4;
for (int j = 12; j < y_limit + 1; j += 72)
{
n += j; table[n] = !table[n];
}
}
xStepsize = 0;
temp = 8 * (int) (Math.sqrt((N - 1) / 4)) + 4;
for (int i = 4; i < temp; i += 8)
{
xStepsize += i;
n = xStepsize + 1;
if (xStepsize % 3 != 0)
{
int tempTwo = 4 * ((int) Math.sqrt(N - xStepsize)) - 3;
for (int j = 0; j < tempTwo; j += 8)
{
n += j; table[n] = !table[n];
}
}
else
{
y_limit = 12 * (int) Math.sqrt(N - xStepsize) - 36;
n = xStepsize + 25;
for (int j = -24; j < y_limit + 1; j += 72)
{
n += j; table[n] = !table[n];
}
n = xStepsize + 1;
for (int j = 24; j < y_limit + 1; j += 72)
{
n += j; table[n] = !table[n];
}
}
}
xStepsize = 1;
temp = (int) Math.sqrt(N / 2) + 1;
for (int i = 3; i < temp; i += 2)
{
xStepsize += 4 * i - 4;
n = 3 * xStepsize;
int s = 4;
if (n > N)
{
int min_y = (((int) (Math.sqrt(n - N)) >> 2) << 2);
int yy = min_y * min_y;
n -= yy;
s = 4 * min_y + 4;
}
else s = 4;
for (int j = s; j < 4 * i; j += 8)
{
n -= j;
if (n <= N && n % 12 == 11) table[n] = !table[n];
}
}
xStepsize = 0;
for (int i = 2; i < temp; i += 2)
{
xStepsize += 4 * i - 4;
n = 3 * xStepsize;
int s = 0;
if (n > N)
{
int min_y = (((int) (Math.sqrt(n - N)) >> 2) << 2) - 1;
int yy = min_y * min_y;
n -= yy;
s = 4 * min_y + 4;
}
else
{
n -= 1; s = 0;
}
for (int j = s; j < 4 * i; j += 8)
{
n -= j;
if (n <= N && n % 12 == 11) table[n] = !table[n];
}
}
for (int i = 5; i < squareRoot + 1; i += 2)
if (table[i] == true)
{
int k = i * i;
for (int z = k; z < N; z += k) table[z] = false;
}
table[2] = table[3] = true;
return table;
}
}
class InputReader
{
private BufferedReader reader;
private StringTokenizer st;
public InputReader(InputStream stream)
{
reader = new BufferedReader(new InputStreamReader(stream), 1024);
}
public String getString() throws IOException
{
while (st == null || !st.hasMoreTokens())
{
String line = reader.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
public String getLine() throws IOException
{
return reader.readLine();
}
public int getInt() throws IOException
{
return Integer.parseInt(getString());
}
public long getLong() throws IOException
{
return Long.parseLong(getString());
}
public double getDouble() throws IOException
{
return Double.parseDouble(getString());
}
public boolean ready() throws IOException
{
return reader.ready();
}
public int[][] getIntTable(int rowCount, int columnCount) throws IOException
{
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) table[i] = getIntArray(columnCount);
return table;
}
public int[] getIntArray(int len) throws IOException
{
int[] table = new int[len];
for (int i = 0; i < len; i++) table[i] = getInt();
return table;
}
}
class OutputWriter
{
private PrintWriter writer;
public OutputWriter(OutputStream stream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0) writer.print(' ');
writer.print(objects[i].toString());
}
}
public void print(String s, Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0) writer.print(s);
writer.print(objects[i].toString());
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void printf(String format, Object... objects)
{
writer.printf(format, objects);
}
public void close()
{
writer.close();
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
4c68bbe0dcc0433b5919e2c9e6dd0d97
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class PrimeMatrix{
static int primeCount = 0;
static int prime[] = new int[100000];
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int inp[][] = new int[n][m];
int minCountX = 100000;
int minCountY = 100000;
genPrime();
for(int i = 0; i<n; i++){
st = new StringTokenizer(br.readLine());
int count = 0;
for(int j = 0; j<m; j++){
inp[i][j] = Integer.parseInt(st.nextToken());
count += (nextPrime(inp[i][j]) - inp[i][j]);
}
minCountX = Math.min(minCountX, count);
}
for(int j = 0; j<m; j++){
int count = 0;
for(int i = 0; i<n; i++){
count += (nextPrime(inp[i][j]) - inp[i][j]);
}
minCountY = Math.min(minCountY, count);
}
System.out.println(Math.min(minCountX, minCountY));
}
public static void genPrime(){
int n = 100100;
boolean arr[] = new boolean[n];
Arrays.fill(arr,true);
arr[0] = false;
for(int i = 1; i<n; i++){
if(arr[i]){
prime[primeCount++] = i+1;
markMultiplePrime(arr,i+1,n);
}
}
}
public static void markMultiplePrime(boolean[] arr, int num, int n){
int i = 2;
while ( (i*num <= n)){
arr[(i*num) - 1] = false;
i++;
}
}
public static int nextPrime(int num){
int high = primeCount, low = 0, mid = (high+low)/2;
while(high - low != 1){
if(prime[mid] == num){return prime[mid];}
else if(num < prime[mid]){high = mid; mid = (high+low)/2;}
else{low = mid; mid = (high + low)/2;}
}
if(prime[mid] < num)
return prime[mid+1];
else
return prime[mid];
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
a5e55f15a0d7efd210b056618a6ca8e3
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class B {
static int len = 100005;
static boolean[] isprime = new boolean[len];
static int[] primes;
static void seive() {
int i, j, index;
index = 0;
for (i = 0; i < len; i++) {
isprime[i] = true;
}
isprime[0] = false;
isprime[1] = false;
for (i = 2; i < len; i++)
if (isprime[i]) {
index++;
for (j = i + i; j < len; j += i)
isprime[j] = false;
}
primes = new int[index + 1];
index = 0;
for (int k = 0; k < len; k++) {
if (isprime[k]) {
primes[index] = k;
index++;
}
}
}
public static void main(String[] args) {
seive();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int[][] array = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
array[i][j] = scan.nextInt();
HashMap<Integer, Integer> h = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (isprime[array[i][j]] && !h.containsKey(array[i][j])) {
h.put(array[i][j], 0);
} else {
if (!h.containsKey(array[i][j])) {
int a = getnextprime(array[i][j]);
h.put(array[i][j], a - array[i][j]);
}
}
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = 0; j < m; j++)
sum += h.get(array[i][j]);
min = Math.min(sum, min);
}
for (int i = 0; i < m; i++) {
int sum = 0;
for (int j = 0; j < n; j++)
sum += h.get(array[j][i]);
min = Math.min(sum, min);
}
System.out.println(min);
}
private static int getnextprime(int n) {
for (int i = 0; i < primes.length; i++) {
if (primes[i] > n)
return primes[i];
}
return 0;
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
7956361bf377537ee4be7890d313571a
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.util.Scanner;
import java.util.ArrayList;
public class PrimeMatrix
{
public static int TimesOfIncrese(ArrayList<Integer> primes, int num)
{
int low = 0;
int high = primes.size() - 1;
int mid;
int temp;
while (low <= high)
{
mid = (low + high) / 2;
temp = primes.get(mid);
if (temp == num)
{
low = mid;
break;
}
else if (temp < num)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return primes.get(low) - num;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
matrix[i][j] = input.nextInt();
}
}
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(2);
int min;
int idx = 0;
boolean flag = true;
for (int i = 3; ; i += 2)
{
idx = 0;
min = (int)Math.sqrt(i);
flag = true;
while (idx < primes.size())
{
if (primes.get(idx) > min)
{
break;
}
if (i % primes.get(idx) == 0)
{
flag = false;
break;
}
else
{
++idx;
}
}
if (flag)
{
primes.add(i);
if (i > 100000)
{
break;
}
}
}
int[][] res = new int[n][m];
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
res[i][j] = TimesOfIncrese(primes, matrix[i][j]);
}
}
long max = -1;
long sum = 0;
for (int i = 0; i < n; ++i)
{
sum = 0;
for (int j = 0; j < m; ++j)
{
sum += res[i][j];
}
if (sum < max || max == -1)
{
max = sum;
}
}
for (int i = 0; i < m; ++i)
{
sum = 0;
for (int j = 0; j < n; ++j)
{
sum += res[j][i];
}
if (sum < max || max == -1)
{
max = sum;
}
}
System.out.println(max);
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
ce97b9a79ef54f605869048a5b355ba3
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.util.*;
public class B271 {
public static void main(String[] args){
Scanner br = new Scanner(System.in);
int max = 2000000;
boolean[] isPrime = new boolean[max];
Arrays.fill(isPrime, true);
TreeSet<Integer> ps = new TreeSet<Integer>();
for(int i = 2;i<max;i++){
if(isPrime[i]){
ps.add(i);
for(long j = (long)i*i;j<max;j+=i){
isPrime[(int)j] = false;
}
}
}
int r = br.nextInt();
int c = br.nextInt();
int[][] board = new int[r][c];
for(int i = 0;i<r;i++){
for(int j = 0;j<c;j++){
board[i][j] = br.nextInt();
}
}
int best = 1000000000;
for(int i = 0;i<r;i++){
int count = 0;
for(int j = 0;j<c;j++){
int p = ps.ceiling(board[i][j]);
count+=(p-board[i][j]);
}
best = Math.min(best, count);
}
for(int i = 0;i<c;i++){
int count = 0;
for(int j = 0;j<r;j++){
int p = ps.ceiling(board[j][i]);
count+=(p-board[j][i]);
}
best = Math.min(best, count);
}
System.out.println(best);
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
c90c7fcd81224e6207deba9c09a07d38
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class TC
{
static ArrayList<Integer> prime;
static int list[];
static int[][] arr;
static int N,M;
static void sieve()
{
int MAX=100004;
boolean[] isPrime=new boolean[MAX];
Arrays.fill( isPrime, true );
prime=new ArrayList();
for( int i=2; i<MAX; i++ )
{
if( !isPrime[i])
continue;
prime.add(i);
int mul=i;
while( (long)mul*i < MAX)
{
isPrime[mul*i]=false;
mul++;
}
}
}
static int findNext( int x )
{
int ind=Arrays.binarySearch(list, x);
if( ind >= 0 )
return x;
else
{
int loc=-(ind+1);
return list[loc];
}
}
static void solve()
{
sieve();
list=new int[prime.size() ];
for( int i=0; i<prime.size(); i++ )
list[i]=prime.get(i);
int[] rc=new int[N];
int[] cc=new int[M];
Arrays.fill( rc, 0 );
Arrays.fill( cc, 0 );
for( int i=0; i<N; i++ )
{
for( int j=0; j<M; j++ )
{
int nextPrime=findNext( arr[i][j]);
int moves=nextPrime-arr[i][j];
rc[i]+=moves;
cc[j]+=moves;
}
}
long MIN=Long.MAX_VALUE;
for( int x:rc )
MIN=Math.min( MIN, x );
for( int x:cc )
MIN=Math.min( MIN, x );
System.out.println( MIN );
}
public static void main( String[] args ) throws IOException
{
BufferedReader br=new BufferedReader( new InputStreamReader( System.in ) );
String s=br.readLine();
StringTokenizer tok=new StringTokenizer( s );
N=Integer.parseInt( tok.nextToken() );
M=Integer.parseInt( tok.nextToken() );
arr=new int[N][M];
for( int i=0; i<N; i++ )
{
s=br.readLine();
tok=new StringTokenizer( s );
for( int j=0; j<M; j++ )
{
arr[i][j]=Integer.parseInt( tok.nextToken() );
}
}
solve();
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
510c69333cd4fa8f34f1902f6108d47a
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.util.*;
import java.math.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
BufferedReader c=new BufferedReader(new InputStreamReader(System.in));
String S[]=c.readLine().split(" ");
int N=Integer.parseInt(S[0]);
int M=Integer.parseInt(S[1]);
int A[][]=new int[N][M];
for(int i=0;i<N;i++)
A[i]=parseArray(c.readLine(),M);
boolean IsPrime[]=new IntegerUtils().sieve(1000000);
int min=Integer.MAX_VALUE;
//rows
for(int i=0;i<N;i++)
{
int ans=0;
for(int j=0;j<M;j++)
{
int num=A[i][j];
while(!IsPrime[num])
{
num++;
ans++;
}
}
//System.out.println("row "+i+" "+ans);
min=Math.min(min,ans);
}
//cols
for(int j=0;j<M;j++)
{
int ans=0;
for(int i=0;i<N;i++)
{
int num=A[i][j];
while(!IsPrime[num])
{
num++;
ans++;
}
}
min=Math.min(min,ans);
//System.out.println("col "+j+" "+ans);
}
System.out.println(min);
}
// Parse an integer array of size N from a string s
public static int[] parseArray(String s,int N)
{
int A[]=new int[N];
StringTokenizer st=new StringTokenizer(s);
for(int i=0;i<N;i++)
A[i]=Integer.parseInt(st.nextToken());
return A;
}
}
class Factor
{
int number;
int occurences;
public Factor(int number,int occurences)
{
this.number=number;
this.occurences=occurences;
}
}
class IntegerUtils
{
public static boolean[] sieve(int N)
{
boolean A[]=new boolean[N];
Arrays.fill(A,true);
A[0]=false;
A[1]=false;
for(int i=2;i<N;i++)
{
if(A[i]==true) //a prime
{
int num=i+i;
while (num<N)
{
A[num]=false;
num+=i;
}
}
}
return A;
}
//Return an array of LinkedLists, where L[i] contains the factors
//of i along with its number of occurences
public static LinkedList<Factor>[] genFactorLists(int MAX)
{
LinkedList<Factor> L[]=new LinkedList[MAX+1];
for(int i=0;i<=MAX;i++)
L[i]=new LinkedList<Factor>();
for(int i=2;i<=MAX;i++)
{
if(L[i].isEmpty())
{
int num=i;
while (num<=MAX)
{
int temp=num;
int occ=0;
while (temp!=0&&temp%i==0)
{
temp/=i;
occ++;
}
L[num].add(new Factor(i,occ));
num+=i;
}
}
}
return L;
}
// return the length of the prime factorization of N
public static int primeFactorizationLength(long N)
{
int len=0;
for(long i=2;i*i<=N;i++)
{
while (N%i==0)
{
N=N/i;
len++;
}
}
if(N>1) //a residue prime number
len++;
return len;
}
// returns the 1st N prime factors
public static int[] getNPrimeFactors(int N)
{
int SIEVE_MAX=16000000; //enough for 1st 10^6 primes
boolean IsPrime[]=sieve(SIEVE_MAX);
int Ans[]=new int[N];
int added=0;
for(int i=0;i<SIEVE_MAX;i++)
{
if(IsPrime[i])
{
Ans[added]=i;
added++;
if(added==N)
return Ans;
}
}
// could not find N primes
return null;
}
// return the number of factors of an integer N
public static int numFactors(long N)
{
int ans=1;
int len=0;
for(long i=2;i*i<=N;i++)
{
while (N%i==0)
{
N=N/i;
len++;
}
if(len!=0)
{
ans*=(len+1);
len=0;
}
}
if(N>1) //a residue prime number
ans*=2;
return ans;
}
public static boolean isPrime(int n)
{
if(n==2||n==3||n==5)
return true;
if(n%2==0||n<=1)
return false;
int temp=(int) Math.sqrt(n)+3;
for(int i=3;i<=temp;i+=2)
if(n%i==0)
return false;
return true;
}
//Calculate inverses of 1-->N modulo mod
private static long[] inverses(int N,int mod)
{
long inv[]=new long[N+1];
inv[1]=1;
for(int i=2;i<=N;i++)
inv[i]=(mod-((mod/i)*inv[mod%i])%mod)%mod;
return inv;
}
// calculate a^b modulo p
public static long pow(long a,long b,long p)
{
if(b==1)
return a%p;
if(b%2!=0)
return (a*pow(a,b-1,p))%p;
long temp=pow(a,b/2,p);
return (temp*temp)%p;
}
private static int sumOfDigits(int i)
{
int ans=0;
while (i>0)
{
ans+=i%10;
i=i/10;
}
return ans;
}
private static int productOfDigits(int i)
{
int ans=1;
while (i>0)
{
ans*=i%10;
i=i/10;
}
return ans;
}
public static int gcd(int i,int j)
{
if(i<j)
return gcd(j,i);
if(j==0)
return i;
else
return gcd(j,i%j);
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
2a9e1b3490ab30dcbe8a8d3c0d4d5abe
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class ProblemB {
static final int MAX = 110000;
static boolean[] ptable(int max) {
boolean[] isprime = new boolean[max];
Arrays.fill(isprime, true);
isprime[0] = isprime[1] = false;
for (int i = 2 ; i < max ; i++) {
if (isprime[i]) {
for (int ii = i*2 ; ii < max ; ii += i) {
isprime[ii] = false;
}
}
}
return isprime;
}
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
boolean[] p = ptable(MAX);
int[] nextP = new int[MAX+1];
nextP[MAX] = 100000000;
for (int i = MAX-1 ; i >= 0 ; i--) {
if (p[i]) {
nextP[i] = 0;
} else {
nextP[i] = nextP[i+1] + 1;
}
}
int n = nextInt();
int m = nextInt();
int[][] mat = new int[n][m];
for (int i = 0 ; i < n ; i++) {
for (int j = 0 ; j < m ; j++) {
mat[i][j] = nextP[nextInt()];
}
}
long minCost = Long.MAX_VALUE;
for (int i = 0 ; i < n ; i++) {
long cost = 0;
for (int j = 0 ; j < m ; j++) {
cost += mat[i][j];
}
minCost = Math.min(minCost, cost);
}
for (int i = 0 ; i < m ; i++) {
long cost = 0;
for (int j = 0 ; j < n ; j++) {
cost += mat[j][i];
}
minCost = Math.min(minCost, cost);
}
out.println(minCost);
out.flush();
}
static BufferedReader s = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer st;
static String nextString() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(s.readLine());
}
return st.nextToken();
}
static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextString());
}
public static void debug(Object... os) {
System.err.println(Arrays.deepToString(os));
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
a52d1698b5985816805546e19e09fc52
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
//package round166;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class B {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int[] primes = sieveEratosthenes(110000);
int n = ni(), m = ni();
int[][] a = new int[n][m];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
int v = ni();
int ind = Arrays.binarySearch(primes, v);
if(ind < 0){
a[i][j] = primes[-ind-1]-v;
}else{
a[i][j] = 0;
}
}
}
int min = Integer.MAX_VALUE;
for(int i = 0;i < n;i++){
int sum = 0;
for(int j = 0;j < m;j++){
sum += a[i][j];
}
min = Math.min(min, sum);
}
for(int i = 0;i < m;i++){
int sum = 0;
for(int j = 0;j < n;j++){
sum += a[j][i];
}
min = Math.min(min, sum);
}
out.println(min);
}
public static int[] sieveEratosthenes(int n) {
if(n <= 32){
int[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };
for(int i = 0;i < primes.length;i++){
if(n < primes[i]){
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };
for(int tp : tprimes){
ret[pos++] = tp;
int[] ptn = new int[tp];
for(int i = (tp - 3) / 2;i < tp << 5;i += tp)
ptn[i >> 5] |= 1 << (i & 31);
for(int i = 0;i < tp;i++){
for(int j = i;j < sup;j += tp)
isp[j] |= ptn[i];
}
}
// 3,5,7
// 2x+3=n
int[] magic = { 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4,
13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14 };
int h = n / 2;
for(int i = 0;i < sup;i++){
for(int j = ~isp[i];j != 0;j &= j - 1){
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if(p > n)
break;
ret[pos++] = p;
for(int q = pp;q <= h;q += p)
isp[q >> 5] |= 1 << (q & 31);
}
}
return Arrays.copyOf(ret, pos);
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new B().run(); }
private byte[] inbuf = new byte[1024];
private 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(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
5bf24177c55e1e7e825f813422b519b6
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import static java.lang.Math.min;
import static java.lang.Math.max;
public class Code implements Runnable {
public static void main(String[] args) throws IOException {
new Thread(new Code()).start();
}
private void solve() throws IOException {
int n = nextInt(), m = nextInt();
int[][] matr = new int[n][m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
matr[i][j] = nextInt();
}
}
List<Integer> primes = getPrimes(100008);
long[] rows = new long[n];
long min = Long.MAX_VALUE;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
rows[i] += getPrime(matr[i][j], primes) - matr[i][j];
}
min = min(min, rows[i]);
}
long[] cols = new long[m];
for (int j = 0; j < m; ++j) {
for (int i = 0; i < n; ++i) {
cols[j] += getPrime(matr[i][j], primes) - matr[i][j];
}
min = min(min, cols[j]);
}
System.out.println(min);
}
private int getPrime(int num, List<Integer> primes) {
int l = 0, r = primes.size() - 1;
while (l < r) {
int mid = l + r >> 1;
if (primes.get(mid) < num)
l = mid + 1;
else
r = mid;
}
return primes.get(r);
}
private List<Integer> getPrimes(int n) {
boolean[] primes = new boolean[n];
Arrays.fill(primes, true);
primes[0] = primes[1] = false;
for (int i = 2; i < n; ++i) {
if (primes[i]) {
for (long j = (long) i * i; j < n; j += i) {
primes[(int) j] = false;
}
}
}
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 2; i < n; ++i) {
if (primes[i])
list.add(i);
}
return list;
}
private class IntervalTree {
IntervalTree(int[] arr) {
tree = new int[arr.length << 2];
buildTree(1, 0, arr.length - 1, arr);
}
public int getMax(int l, int r) {
return getMax(1, l, r, 0, (tree.length >> 2) - 1);
}
private int getMax(int u, int l, int r, int tl, int tr) {
if (tl >= l && tr <= r)
return tree[u];
else if (r < tl || l > tr)
return 0;
else {
int mid = tl + tr >> 1, u1 = u << 1, u2 = u1 + 1;
return max(getMax(u1, l, r, tl, mid), getMax(u2, l, r, mid + 1, tr));
}
}
private void buildTree(int v, int l, int r, int[] arr) {
if (l == r)
tree[v] = arr[l];
else {
int mid = l + r >> 1, u1 = v << 1, u2 = u1 + 1;
buildTree(u1, l, mid, arr);
buildTree(u2, mid + 1, r, arr);
tree[v] = max(tree[u1], tree[u2]);
}
}
private int[] tree;
}
private class Pair<E, V> implements Comparable<Pair<E, V>> {
public Pair(E first, V second) {
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair<E, V> obj) {
if (first.equals(obj.first)) return ((Comparable) second).compareTo(obj.second);
return ((Comparable) first).compareTo(obj.first);
}
@Override
public boolean equals(Object obj) {
Pair other = (Pair) obj;
return first.equals(other.first) && second.equals(other.second);
}
@Override
public String toString() {
return first + " " + second;
}
public E first;
public V second;
}
@Override
public void run() {
try {
if (in.equals(""))
reader = new BufferedReader(new InputStreamReader(System.in));
else
reader = new BufferedReader(new FileReader(in));
if (out.equals(""))
writer = new PrintWriter(System.out, false);
else
writer = new PrintWriter(new FileWriter(out), false);
solve();
} catch (IOException e) {
e.printStackTrace();
} finally {
//writer.println((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 + " KB");
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private float nextFloat() throws IOException {
return Float.parseFloat(nextToken());
}
private String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(reader.readLine());
return st.nextToken();
}
private String in = "", out = "";
private BufferedReader reader;
private PrintWriter writer;
private StringTokenizer st;
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
6d4dd4633432a16c329d55deed799117
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.DataInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;
public class Main{
public static void main(String[] args) throws Exception {
Parserdoubt s = new Parserdoubt(System.in);
ArrayList<Integer> arr = sieve2(101000);
TreeSet<Integer> tree = new TreeSet<Integer>();
for (int i = 0; i < arr.size(); i++) {
tree.add(arr.get(i));
}
int n = s.nextInt();
int m = s.nextInt();
int map[][] = new int[n][m];
int count[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = s.nextInt();
Integer next = tree.ceiling(map[i][j]);
// System.out.println(next);
count[i][j] = next - map[i][j];
// System.out.println(next);
}
}
int min = 999888;
int rows[] = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
rows[i] += count[i][j];
}
if(rows[i] < min) min = rows[i];
}
int cols[] = new int[m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cols[i] += count[j][i];
}
if(cols[i] < min) min = cols[i];
}
System.out.println(min);
}
public static ArrayList<Integer> sieve2(int n){
int lp[] = new int [n+1];
ArrayList<Integer> primes = new ArrayList<Integer>();
for (int i = 2; i <= n ; i++) {
if(lp[i]==0){
lp[i]=i;
primes.add(i);
}
for (int j = 0; j < primes.size() && primes.get(j) <= lp[i] && i*primes.get(j)<=n; j++) {
lp[i*primes.get(j)]=primes.get(j);
}
}
return primes;
}
}
class Parserdoubt
{
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parserdoubt(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception
{
StringBuffer sb=new StringBuffer("");
byte c = read();
while (c <= ' ') c = read();
do
{
sb.append((char)c);
c=read();
}while(c>' ');
return sb.toString();
}
public char nextChar() throws Exception
{
byte c=read();
while(c<=' ') c= read();
return (char)c;
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
31b308a7eea26527d96a78971c4f7cac
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static int[] nextPrimeDP;
static boolean isPrime(int x) {
if(x == 1) return false;
if(x == 2) return true;
if(x % 2 == 0) return false;
int sqrtx = (int) Math.sqrt(x);
for(int i = 3; i <= sqrtx; i += 2) {
if(x % i == 0) return false;
}
return true;
}
static int nextPrime(int x) {
if(nextPrimeDP[x] != -1) return nextPrimeDP[x];
nextPrimeDP[x] = isPrime(x)? x: nextPrime(x + 1);
return nextPrimeDP[x];
}
public static void main(String[] args) {
nextPrimeDP = new int[(int)1E6];
Arrays.fill(nextPrimeDP, -1);
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int[][] grid = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int temp = scan.nextInt();
grid[i][j] = nextPrime(temp) - temp;
}
}
int ans = Integer.MAX_VALUE;
for(int i = 0; i < n; i++) {
int row = 0;
for(int j = 0; j < m; j++) {
row += grid[i][j];
}
ans = Math.min(ans, row);
}
for(int j = 0; j < m; j++) {
int col = 0;
for(int i = 0; i < n; i++) {
col += grid[i][j];
}
ans = Math.min(ans, col);
}
System.out.println(ans);
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
b929a845b742b369c4a42da2e95a1f80
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
/**
* Works good for CF
*
* @author cykeltillsalu
*/
public class A {
// some local config
static boolean test = false;
static String testDataFile = "testdata.txt";
static String feedFile = "feed.txt";
CompetitionType type = CompetitionType.CF;
private static String ENDL = "\n";
private boolean[] siev(int n) {
boolean[] prime = new boolean[n+1];
Arrays.fill(prime, true);
prime[0] = false;
prime[1] = false;
for (int i = 2; i < prime.length; i++) {
int nr = i;
if(prime[nr]){
nr += i;
while(nr <= n){
prime[nr] = false;
nr += i;
}
}
}
return prime;
}
// solution
private void solve() throws Throwable {
int n = iread(), m = iread();
int[][] r = new int[n][m];
boolean[] isprime = siev(100500);
for (int i = 0; i < n; i++) {
out:for (int j = 0; j < m; j++) {
int c = iread();
int p = getPrime(isprime, c);
r[i][j] = p - c;
}
}
int best = Integer.MAX_VALUE/2;
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = 0; j < m; j++) {
sum += r[i][j];
}
best = Math.min(sum, best);
}
for (int i = 0; i < m; i++) {
int sum = 0;
for (int j = 0; j < n; j++) {
sum += r[j][i];
}
best = Math.min(sum, best);
}
System.out.println(best);
}
int[] val = new int[100001];
private int getPrime(boolean[] isprime, int c) {
if(val[c] > 0){
return val[c];
}
for (int i = c; ; i++) {
if(isprime[i]){
val[c] = i;
return i;
}
}
}
public int iread() throws Exception {
return Integer.parseInt(wread());
}
public double dread() throws Exception {
return Double.parseDouble(wread());
}
public long lread() throws Exception {
return Long.parseLong(wread());
}
public String wread() throws IOException {
StringBuilder b = new StringBuilder();
int c;
c = in.read();
while (c >= 0 && c <= ' ')
c = in.read();
if (c < 0)
return "";
while (c > ' ') {
b.append((char) c);
c = in.read();
}
return b.toString();
}
public static void main(String[] args) throws Throwable {
if (test) { // run all cases from testfile:
BufferedReader testdataReader = new BufferedReader(new FileReader(testDataFile));
String readLine = testdataReader.readLine();
int casenr = 0;
out: while (true) {
BufferedWriter w = new BufferedWriter(new FileWriter(feedFile));
if (!readLine.equalsIgnoreCase("input")) {
break;
}
while (true) {
readLine = testdataReader.readLine();
if (readLine.equalsIgnoreCase("output")) {
break;
}
w.write(readLine + "\n");
}
w.close();
System.out.println("Answer on case " + (++casenr) + ": ");
new A().solve();
System.out.println("Expected answer: ");
while (true) {
readLine = testdataReader.readLine();
if (readLine == null) {
break out;
}
if (readLine.equalsIgnoreCase("input")) {
break;
}
System.out.println(readLine);
}
System.out.println("----------------");
}
testdataReader.close();
} else { // run on server
new A().solve();
}
out.close();
}
public A() throws Throwable {
if (test) {
in = new BufferedReader(new FileReader(new File(feedFile)));
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inp);
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
enum CompetitionType {
CF, OTHER
};
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
be19eecf205db8bc1d9df9b6ee73e895
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class B {
public void solve() throws IOException {
boolean[] sieve = new boolean[101000];
sieve[0] = true;
sieve[1] = true;
for(int i = 2; i*i < sieve.length; i++){
if( !sieve[i] ){
for(int j = i*i; j < sieve.length; j+=i){
sieve[j] = true;
}
}
}
int n = nextInt();
int m = nextInt();
int[][] mat = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
mat[i][j] = nextInt();
}
}
int min = 1000000;
for(int i = 0; i < n; i++){
int c = 0;
for(int j = 0; j < m; j++){
int a = mat[i][j];
while( sieve[a] ){
a++;
}
c += a-mat[i][j];
}
min = Math.min(min, c);
}
for(int i = 0; i < m; i++){
int c = 0;
for(int j = 0; j < n; j++){
int a = mat[j][i];
while( sieve[a] ){
a++;
}
c += a-mat[j][i];
}
min = Math.min(min, c);
}
writer.println(min);
}
public static void main(String[] args) throws IOException {
new B().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() throws IOException {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
7eb9341984b412c7f3b210e36e182aea
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class B
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
String FInput="";
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
inputParser = new StringTokenizer(line, " ");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
catch (NullPointerException e)
{
line=null;
}
}
long NextLong()
{
String n = inputParser.nextToken();
long val = Long.parseLong(n);
return val;
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public static void main(String [] argv)
{
//String filePath="input.txt";
//String filePath="D:\\_d\\learn\\coursera\\algorithms and design I\\data\\IntegerArray.txt";
String filePath=null;
if(argv.length>0)filePath=argv[0];
new B(filePath);
}
public void readFInput()
{
for(;;)
{
try
{
readNextLine();
FInput+=line+" ";
}
catch(Exception e)
{
break;
}
}
inputParser = new StringTokenizer(FInput, " ");
}
int [] p;
public B(String inputFile)
{
openInput(inputFile);
readNextLine();
int n=NextInt(), m=NextInt();
boolean [] p = new boolean[110001];
p[0]=p[1]=true;
for(int i=2; i<p.length; i++)
{
if(!p[i])
{
for(int j=i*2; j<p.length; j+=i)
p[j]=true;
}
}
int []d =new int[p.length];
int r=-1;
for(int i=p.length-1; i>=0; i--)
{
if(!p[i])r=0;
else r++;
d[i]=r;
}
int [] [] a = new int[n][m];
for(int i=0; i<n; i++)
{
readNextLine();
for(int j=0; j<m; j++)
a[i][j]=d[NextInt()];
}
int ret=Integer.MAX_VALUE;
for(int i=0; i<n; i++)
{
int now=0;
for(int j=0; j<m; j++)
now+=a[i][j];
ret=Math.min(now, ret);
}
for(int j=0; j<m; j++)
{
int now=0;
for(int i=0; i<n; i++)
now+=a[i][j];
ret=Math.min(now, ret);
}
System.out.println(ret);
closeInput();
}
public static void out(Object s)
{
try{
FileWriter fstream = new FileWriter("output.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(s.toString());
out.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
32d81f76d4028c809d46dcfc4a8c7962
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.util.*;
public class Main{
public static int [] PrimeTable = new int[ 100000];
public static int Count = 0;
public static boolean isprime(int a){
if (a%2 == 0)return true;
for (int i=3;i<=Math.sqrt(a) ; i+=2){
if(a % i == 0 ) return false;
}
return true;
}
public static int dis(int a){
int head = 0;
int tail = Count;
int ans = 0;
while (head <= tail){
int mid = (tail+head)/2;
if ( PrimeTable[mid] >= a ){
tail = mid-1;
ans = PrimeTable[mid]-a;
}else{
head = mid+1;
}
}
// System.out.println(a +" " + ans);
return ans;
}
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
int [][] input = new int[500][500];
int [][] dif = new int[500][500];
int [] R = new int[500];
int [] C = new int[500];
int i,j;
PrimeTable[Count++] = 2;
for (int a=3;a<=100050 ; a+=2){
if (isprime(a)) {
PrimeTable[Count++] = a;
//System.out.println(a);
}
}
int n = sc.nextInt(); int m = sc.nextInt();
for(i=0;i<n;i++){
for(j=0;j<m;j++){
input[i][j] = sc.nextInt();
dif[i][j] = dis(input[i][j]);
}
}
for(i=0;i<n;i++){
for(j=0;j<m;j++){
R[i] +=dif[i][j];
C[j] +=dif[i][j];
}
}
int Min = 1000000; int Max = -1000;
for(i=0;i<n;i++)Min = Math.min(R[i] , Min);
for(i=0;i<m;i++)Min = Math.min(C[i] , Min);
System.out.println(Min);
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
0da17e6669d9944a78be130051d7ed68
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.util.Scanner;
public class B {
boolean primes[] = new boolean[100091];
public void generate(int n){
primes[0] = true;
primes[1] = true;
for(int i = 2 ; i <= (int)Math.sqrt(n) ; i++){
for(int j=i+1 ; j<=n ; j++){
if( !primes[j] && j%i==0 ) primes[j] = true;
}
}
}
public int findNext(int n){
while( primes[n] ) n++;
return n;
}
public void solve(){
generate(100090);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int min = Integer.MAX_VALUE;
int ar[][] = new int[n][m];
int ar_col[][] = new int[n][m];
for(int i = 0 ; i < n ; i++){
for(int j = 0; j<m ; j++){
int temp = sc.nextInt();
ar_col[i][j] = ar[i][j] = findNext(temp) - temp;
if(j!=0)
ar[i][j] +=ar[i][j-1];
if(i!=0)
ar_col[i][j] += ar_col[i-1][j];
if(i==n-1 && ar_col[i][j] < min ) min = ar_col[i][j];
}
if( ar[i][m-1] < min ) min = ar[i][m-1];
}
System.out.println(min);
}
public static void main(String args[]){
new B().solve();
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
ee2e3231dbc1eeb479feb52c85f7dd96
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/**
*
* @author user
*/
public class Prime_Matrix {
static boolean prime[]; static int n1=0;//f[]=new int[100000];
static ArrayList<Integer> f=new ArrayList<Integer>();
public static void main(String[] args) throws IOException {
StreamTokenizer in=new StreamTokenizer(new InputStreamReader(System.in));
int n,m,i,j,k,l,c[][];
in.nextToken();
n=(int)in.nval;
in.nextToken();
m=(int)in.nval;
c=new int[n][m];
for(i=0;i<n;i++){
for(j=0;j<m;j++){
in.nextToken();
c[i][j]=(int)in.nval;
}
}
int ans=0,min1=100000000,min2=1000000000,min;
prime_sieve(100100);
// System.out.println(n1);
for(i=0;i<n;i++){
ans=0;
for(j=0;j<m;j++){
l=Collections.binarySearch(f, c[i][j]);
//System.out.println(l);
if(l<0){
l=Math.abs(l)-1;
ans+=f.get(l) -c[i][j];
}
}
//System.out.println(ans);
if(min1>ans)
min1=ans;
}
for(i=0;i<m;i++){
ans=0;
for(j=0;j<n;j++){
l=Collections.binarySearch(f, c[j][i]);
if(l<0){
l=Math.abs(l)-1;
ans+=f.get(l) -c[j][i];
}
}
if(min2>ans)
min2=ans;
}
if(min1<min2)
min=min1;
else
min=min2;
System.out.println(min);
}
static void prime_sieve(int limit)
{
int a,b,d=1;
prime=new boolean[limit];
Arrays.fill(prime, false);
for(a=2;a<=Math.sqrt(limit);a++)
{d=0;
if(!prime[a-1])
{
for(b=a*a;b<=limit;b=a*a+d*a)
{
prime[b-1]=true;
d++;
}
}
}
for(a=1;a<limit;a++)
{
if(!prime[a])
{
f.add((a+1));
//f[n1]=a+1;
//cout<<a+1<<"\t";
//System.out.println((a+1)+" ");
n1++;
/*if(n==15000)
break;*/
}
}
// System.out.println("n = "+n);
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
b8ac2824430a7e8e640f29c49c58af08
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class second
{
static long fast_power(long a,long n,long m)
{
if(n==1)
{
return a%m;
}
if(n%2==1)
{
long power = fast_power(a,(n-1)/2,m)%m;
return ((a%m) * ((power*power)%m))%m;
}
long power = fast_power(a,n/2,m)%m;
return (power*power)%m;
}
static int move(int primes[], int k,int last)
{
int first=0;
int mid=last/2;
while(primes[mid]!=k)
{
if(k>primes[mid])first=mid;
else last=mid-1;
mid = (first+last)/2;
if((last-first)<=1)break;
}
if(primes[mid]==k)return primes[mid];
if(primes[last]<k)return primes[last+1];
return primes[last];
}
public static void main(String arr[])
{
Scanner sc= new Scanner(System.in);
int primes[] = new int[100000];
int k[] = new int[1000000];
int i=2;
int num=0;
while(i<=100000)
{
if(k[i]==0)
{
primes[num++] = i;
for(int j=i;j<1000000;j+=i)
{
k[j]+=1;
}
}
i++;
}
while(k[i]!=0)i++;
primes[num++]=i;
int n = sc.nextInt();
int m = sc.nextInt();
int a[][] = new int[n][m];
for(i=0;i<n;i++)
{
for(int j=0;j<m;j++)
a[i][j] = sc.nextInt();
}
int r[] = new int[n];
int c[] = new int[m];
for(i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int moves= move(primes,a[i][j],num-1)-a[i][j];
r[i]+=moves;
c[j]+=moves;
}
}
int min = r[0];
for( i=0;i<n;i++)
{
if(r[i]<=min)min=r[i];
}
for( i=0;i<m;i++)
{
if(c[i]<=min)min=c[i];
}
System.out.println(min);
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
f6d423fff7b94e2eccaf80c2f0a6a416
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class B {
public static int MAX = 200000;
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
final int n = sc.nextInt();
final int m = sc.nextInt();
int[][] matrix = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
matrix[i][j] = sc.nextInt();
}
}
boolean is_prime[] = new boolean[MAX+1];
final int sqrt = (int) Math.ceil(Math.sqrt(MAX));
Arrays.fill(is_prime, true);
is_prime[0] = is_prime[1] = false;
for(int i = 2; i <= sqrt; i++){
if(is_prime[i]){
for(int j = i * 2; j <= MAX; j += i){
is_prime[j] = false;
}
}
}
int[][] rest = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
for(int k = matrix[i][j] ; ; k++){
if(is_prime[k]){
rest[i][j] = k - matrix[i][j];
break;
}
}
}
}
int min = Integer.MAX_VALUE;
for(int i = 0; i < n; i++){
int sum = 0;
for(int j = 0; j < m; j++){
sum += rest[i][j];
}
min = Math.min(min, sum);
}
for(int i = 0; i < m; i++){
int sum = 0;
for(int j = 0; j < n; j++){
sum += rest[j][i];
}
min = Math.min(min, sum);
}
System.out.println(min);
sc.close();
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
| |
PASSED
|
750d3eb6c411cd028a9d2f57ef594f64
|
train_000.jsonl
|
1360596600
|
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
|
256 megabytes
|
/**
* @author Juan Sebastian Beltran Rojas
* @mail [email protected]
* @veredict No enviado
* @problemId CF166B.java
* @problemName CF166B.java
* @judge http://www.spoj.pl | http://uva.onlinejudge.org/ | http://livearchive.onlinejudge.org/
* @category ---
* @level ???
* @date 11/02/2013
**/
import java.io.*;
import java.util.*;
import static java.lang.Integer.*;
import static java.lang.Math.*;
public class CF166B{
public static void main(String args[]) throws Throwable{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
boolean primos[]=new boolean[1000000];
primos[0]=primos[1]=true;
int[] p=new int[1000000];
int c=0;
for(int i=0;i<primos.length;i++)
if(!primos[i]){
p[c++]=i;
for(int j=i+i;j<primos.length;j+=i)
primos[j]=true;
}
StringTokenizer st=new StringTokenizer(in.readLine());
int N=parseInt(st.nextToken()),M=parseInt(st.nextToken());
int[][] mat=new int[N][M];
for(int i=0;i<N;i++){
st=new StringTokenizer(in.readLine());
for(int j=0;j<M;j++)mat[i][j]=parseInt(st.nextToken());
}
int min=MAX_VALUE;
for(int i=0;i<N;i++) {
int s=0;
for(int j=0;j<M;j++) {
int bs=Arrays.binarySearch(p,0,c,mat[i][j]);
if(bs<0)s+=(p[-bs-1]-mat[i][j]);
}
min=min(min,s);
}
for(int j=0;j<M;j++) {
int s=0;
for(int i=0;i<N;i++) {
int bs=Arrays.binarySearch(p,0,c,mat[i][j]);
if(bs<0)s+=(p[-bs-1]-mat[i][j]);
}
min=min(min,s);
}
System.out.println(min);
}
}
|
Java
|
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
|
2 seconds
|
["1", "3", "0"]
|
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
|
Java 6
|
standard input
|
[
"binary search",
"number theory",
"brute force",
"math"
] |
d549f70d028a884f0313743c09c685f1
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
| 1,300 |
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
|
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.