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 | c9413429861818eef756a3d972c2159b | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Test1 {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
int n = scanner.nextInt();
int m = scanner.nextInt();
int k = scanner.nextInt();
Sensor[] sensors = new Sensor[k];
//Set<Sensor> set = new HashSet<>();
Map<Integer, List<Sensor>> rawSensors = new HashMap<>();
Map<Integer, List<Sensor>> revSensors = new HashMap<>();
Set<Line> lines = new HashSet<>();
for (int i = 0; i < k; i++) {
sensors[i] = new Sensor(m, scanner.nextInt(), scanner.nextInt(), i);
rawSensors.computeIfAbsent(sensors[i].getDirect(), (nnn) -> new ArrayList<Sensor>()).add(sensors[i]);
revSensors.computeIfAbsent(sensors[i].getReverse(), (nnn) -> new ArrayList<Sensor>()).add(sensors[i]);
}
int xs = 0;
int ys = 0;
boolean xdown = true;
boolean ydown = true;
boolean stopAfter = false;
long curSec = 0;
boolean isRaw = true;
while (!stopAfter) {
int xe = xdown ? n : 0;
int ye = ydown ? m : 0;
if (Math.abs(xe-xs) < Math.abs(ye-ys)) {
ye = ys + Math.abs(xe-xs) * (ydown ? 1 : -1);
xdown = !xdown;
} else if (Math.abs(ye-ys) < Math.abs(xe-xs)) {
xe = xs + Math.abs(ye-ys) * (xdown ? 1 : -1);
ydown = !ydown;
}
stopAfter = (xe == 0 && ye == 0) || (xe == 0 && ye == m) || (xe == n && ye == 0) || (xe == n && ye == m);
//if (lines.contains(new Line(xs, ys, xe, ye))) {
// break;
//}
if (isRaw) {
if (rawSensors.containsKey(xs - ys)) {
for (Sensor s : rawSensors.get(xs - ys)) {
s.checkLine(xs, ys, xe, ye, curSec);
}
}
} else {
if (revSensors.containsKey(xs + ys)) {
for (Sensor s : revSensors.get(xs + ys)) {
s.checkLine(xs, ys, xe, ye, curSec);
}
}
}
lines.add(new Line(xs, ys, xe, ye));
curSec += Math.abs(xe - xs);
xs = xe;
ys = ye;
isRaw = !isRaw;
}
StringBuilder b = new StringBuilder();
for (Sensor s : sensors) {
b.append(s.sec).append("\n");
}
System.out.println(b.toString());
}
static class Line {
int x1, y1, x2, y2;
public Line(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Line line = (Line) o;
boolean res = x1 == line.x1 &&
y1 == line.y1 &&
x2 == line.x2 &&
y2 == line.y2;
if (!res) {
res = x1 == line.x2 &&
y1 == line.y2 &&
x2 == line.x1 &&
y2 == line.y1;
}
return res;
}
@Override
public int hashCode() {
return Objects.hash(x1, y1, x2, y2);
}
}
static class Sensor {
int m;
int x;
int y;
int i;
long sec = -1;
public Sensor(int m, int x, int y, int i) {
this.m = m;
this.x = x;
this.y = y;
this.i = i;
}
boolean checkLine(int x1, int y1, int x2, int y2, long addSec) {
if (sec > 0) {
return true;
}
double f1 = (double) (x - x1) / (double) (x2 - x1);
double f2 = (double) (y - y1) / (double) (y2 - y1);
if (Math.abs(f2 - f1) < 0.00001) {
sec = addSec + Math.abs(x - x1);
}
return true;
}
public int getDirect() {
return x - y;
}
public int getReverse() {
return x + y;
}
}
public 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 (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
} | Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | 054f0645c3058183e259c2dd28e645b9 | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
Pair[] ks = new Pair[k];
for(int i=0;i<k;i++){
ks[i] = new Pair(in.nextInt(),in.nextInt());
}
//x,y,dir & time
HashMap<Three, Long> map = new HashMap<>();
map.put(new Three(0,0,0),0L);
Long t = 0L;
Three curr = new Three(0,0,0);
while(true){
// System.out.println(curr.a + " " + curr.b + " " + curr.c);
int dir = curr.c;
Pair cur = new Pair(curr.a, curr.b);
if(dir == 0){
if(n-cur.x < m-cur.y){
curr = new Three(n, cur.y+n-cur.x, 3);
if(map.containsKey(curr)){
break;
}
t+=n-cur.x;
map.put(curr, t);
} else if(m-cur.y < n-cur.x){
curr = new Three(cur.x + m - cur.y, m, 2);
if(map.containsKey(curr)){
break;
}
t+=m-cur.y;
map.put(curr, t);
} else {
//equal
break;
}
} else if(dir == 1){
if(cur.x < cur.y){
curr = new Three(0, cur.y-cur.x, 2);
if(map.containsKey(curr)){
break;
}
t+=cur.x;
map.put(curr, t);
} else if(cur.y < cur.x){
curr = new Three(cur.x - cur.y, 0, 3);
if(map.containsKey(curr)){
break;
}
t+=cur.y;
map.put(curr, t);
} else {
//equal
break;
}
} else if(dir == 2){
if(n-cur.x < cur.y){
curr = new Three(n, cur.y-(n-cur.x), 1);
if(map.containsKey(curr)){
break;
}
t+=n-cur.x;
map.put(curr, t);
} else if(cur.y < n-cur.x){
curr = new Three(cur.x + cur.y, 0, 0);
if(map.containsKey(curr)){
break;
}
t+=cur.y;
map.put(curr, t);
} else {
//equal
break;
}
} else if(dir == 3){
if(cur.x < m-cur.y){
curr = new Three(0, cur.y+cur.x, 0);
if(map.containsKey(curr)){
break;
}
t+=cur.x;
map.put(curr, t);
} else if(m-cur.y < cur.x){
curr = new Three(cur.x - (m - cur.y), m, 1);
if(map.containsKey(curr)){
break;
}
t+=m-cur.y;
map.put(curr, t);
} else {
//equal
break;
}
}
}
for(int i=0;i<k;i++){
Pair pp = ks[i];
Long maxx = 10000000000L;
Long a,b,c,d;
if(pp.x<pp.y){
a = map.get(new Three(0, pp.y-pp.x, 0));
if(a!=null) a+=pp.x;
}else{
a = map.get(new Three(pp.x-pp.y, 0, 0));
if(a!=null) a+=pp.y;
}
if(n-pp.x<m-pp.y){
b = map.get(new Three(n, pp.y+n-pp.x, 1));
if(b!=null) b+=n-pp.x;
}else{
b = map.get(new Three(pp.x + m-pp.y, m, 1));
if(b!=null) b+=m-pp.y;
}
if(pp.x < m-pp.y){
c = map.get(new Three(0, pp.y+pp.x, 2));
if(c!=null) c+=pp.x;
}else{
c = map.get(new Three(pp.x - (m-pp.y) , m, 2));
if(c!=null) c+=m-pp.y;
}
if(n-pp.x < pp.y){
d = map.get(new Three(n, pp.y-(n-pp.x),3));
if(d!=null) d+=n-pp.x;
}else{
d = map.get(new Three(pp.x + pp.y,0,3));
if(d!=null) d+=pp.y;
}
Long res = maxx;
if(a!=null) res = Long.min(res, a);
if(b!=null) res = Long.min(res, b);
if(c!=null) res = Long.min(res, c);
if(d!=null) res = Long.min(res, d);
if(res!=maxx){
out.println(res);
}else{
out.println(-1);
}
}
out.flush();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
}
}
class Pair{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
}
class Three{
int a;int b;int c;
Three(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int hashCode() {
int hash = 1;
hash = hash * 17 +this.a;
hash = hash * 31 + this.b;
hash = hash * 13 + this.c;
return hash;
}
@Override
public boolean equals(Object obj) {
Three oo = (Three) obj;
return oo.a == this.a && oo.b == this.b && oo.c == this.c;
}
}
| Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | c5ca8b4f1eb323e38bbecd46d1b903ff | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ilyakor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public static final long inf = Long.MAX_VALUE / 4;
int n;
int m;
int d;
int N;
int M;
int RN;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
m = in.nextInt();
d = IntegerUtils.gcd(n, m);
N = n / d;
M = m / d;
RN = BigInteger.valueOf(N).modInverse(BigInteger.valueOf(M)).intValue();
RN = (RN % M + M) % M;
int q = in.nextInt();
for (int it = 0; it < q; ++it) {
int x = in.nextInt();
int y = in.nextInt();
long res = inf;
res = Math.min(res, calc(x, y));
res = Math.min(res, calc(2 * n - x, y));
res = Math.min(res, calc(x, 2 * m - y));
res = Math.min(res, calc(2 * n - x, 2 * m - y));
if (res == inf) res = -1;
out.printLine(res);
}
}
private long calc(int x, int y) {
int delta = y - x;
if (Math.abs(delta) % (2 * d) != 0) return inf;
delta /= 2 * d;
long val = ((long) delta) * (long) RN;
val %= M;
val += M;
val %= M;
val = val * (2 * n) + x;
Assert.assertTrue(val % (2 * n) == x);
Assert.assertTrue(val % (2 * m) == y);
return val;
}
}
static class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class Assert {
public static void assertTrue(boolean flag) {
// if (!flag)
// while (true);
if (!flag)
throw new AssertionError();
}
}
static class IntegerUtils {
public static int gcd(int x, int y) {
if (y == 0) return x;
return gcd(y, x % y);
}
}
}
| Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | 840c7bd2d1261ae4d02893f328a9ba6d | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Hieu Le
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
private static final int[][] directions = {{1, 1}, {1, -1}, {-1, -1}, {-1, 1}};
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
// Generate all collisions.
Map<TaskC.Move, Long> collisions = new HashMap<>();
TaskC.Move current = new TaskC.Move(new TaskC.Point(0, 0), 1, 1);
long time = 0;
do {
if (collisions.containsKey(current))
break;
collisions.put(new TaskC.Move(current), time);
TaskC.Move next = advance(current, n, m);
time += (long) Math.abs(next.point.x - current.point.x);
current = next;
} while (!isCorner(current.point, n, m));
int k = in.nextInt();
for (int i = 0; i < k; ++i) {
TaskC.Point target = new TaskC.Point(in.nextInt(), in.nextInt());
long minTime = Long.MAX_VALUE;
for (int j = 0; j < directions.length; ++j) {
TaskC.Move move = backtrack(target, n, m, directions[j][0], directions[j][1]);
if (collisions.containsKey(move)) {
long temp = collisions.get(move) + Math.abs(target.x - move.point.x);
minTime = Math.min(minTime, temp);
}
}
if (minTime == Long.MAX_VALUE) {
out.println(-1);
} else {
out.println(minTime);
}
}
}
private static TaskC.Move advance(TaskC.Move move, int n, int m) {
return extend(move, n, m);
}
private static TaskC.Move backtrack(TaskC.Point point, int n, int m, int dx, int dy) {
TaskC.Move move = new TaskC.Move(point, -dx, -dy);
TaskC.Move nextMove = extend(move, n, m);
nextMove.dx = dx;
nextMove.dy = dy;
return nextMove;
}
private static TaskC.Move extend(TaskC.Move move, int n, int m) {
int x = move.point.x + move.dx * n;
int y = move.point.y + move.dy * m;
x = Math.max(0, x);
x = Math.min(n, x);
y = Math.max(0, y);
y = Math.min(m, y);
int ddx = Math.abs(x - move.point.x);
int ddy = Math.abs(y - move.point.y);
TaskC.Point point;
if (ddx <= ddy) {
point = new TaskC.Point(x, move.point.y + move.dy * ddx);
} else {
point = new TaskC.Point(move.point.x + move.dx * ddy, y);
}
int dx = -move.dx;
int dy = -move.dy;
if (dx < 0 && point.x == n || dx > 0 && point.x == 0)
return new TaskC.Move(point, dx, move.dy);
return new TaskC.Move(point, move.dx, dy);
}
private static boolean isCorner(TaskC.Point point, int n, int m) {
return (point.x == 0 && point.y == 0) || (point.x == 0 && point.y == m) ||
(point.x == n && point.y == 0) || (point.x == n && point.y == m);
}
private static class Move {
TaskC.Point point;
int dx;
int dy;
public Move(TaskC.Point point, int dx, int dy) {
this.point = new TaskC.Point(point.x, point.y);
this.dx = dx;
this.dy = dy;
}
public Move(TaskC.Move other) {
this.point = new TaskC.Point(other.point.x, other.point.y);
this.dx = other.dx;
this.dy = other.dy;
}
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof TaskC.Move))
return false;
TaskC.Move move = (TaskC.Move) obj;
return point.equals(move.point) && move.dx == dx && move.dy == dy;
}
public int hashCode() {
int hash = point.hashCode();
hash = hash * 31 + dx;
hash = hash * 31 + dy;
return hash;
}
}
private static class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof TaskC.Point))
return false;
TaskC.Point point = (TaskC.Point) obj;
return x == point.x && y == point.y;
}
public int hashCode() {
int hash = 23;
hash = hash * 31 + x;
hash = hash * 31 + y;
return hash;
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
private static final int BUFFER_SIZE = 32768;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | bbac76c82fcf0c222119731a5b50a44b | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.util.*;
import java.io.*;
public class Ray_Tracing {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
ArrayList<ArrayList<Integer>> posm = new ArrayList<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> negm = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 200000; i++) {
ArrayList<Integer> tp = new ArrayList<Integer>();
posm.add(tp);
ArrayList<Integer> tn = new ArrayList<Integer>();
negm.add(tn);
}
long[] px = new long[k];
long[] py = new long[k];
for (int i = 0; i < k; i++) {
st = new StringTokenizer(f.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
posm.get(y - x + 100000).add(i);
negm.get(x + y).add(i);
px[i] = x;
py[i] = y;
}
f.close();
int dir = 0;
long x = 0;
long y = 0;
long time = 0;
long[] ans = new long[k];
Arrays.fill(ans, -1);
while (true) {
if (dir == 0) {
for (int i : posm.get((int) (y - x + 100000))) {
if (ans[i] == -1) {
ans[i] = time + px[i] - x;
}
}
long tx = x;
long ty = y;
x += Math.min(n - tx, m - ty);
y += Math.min(n - tx, m - ty);
time += Math.min(n - tx, m - ty);
if (x == n) {
dir = 3;
} else {
dir = 1;
}
} else if (dir == 1) {
for (int i : negm.get((int) (x + y))) {
if (ans[i] == -1) {
ans[i] = time + px[i] - x;
}
}
long tx = x;
long ty = y;
x += Math.min(n - tx, ty);
y -= Math.min(n - tx, ty);
time += Math.min(n - tx, ty);
if (x == n) {
dir = 2;
} else {
dir = 0;
}
} else if (dir == 2) {
for (int i : posm.get((int) (y - x + 100000))) {
if (ans[i] == -1) {
ans[i] = time + x - px[i];
}
}
long tx = x;
long ty = y;
x -= Math.min(tx, ty);
y -= Math.min(tx, ty);
time += Math.min(tx, ty);
if (x == 0) {
dir = 1;
} else {
dir = 3;
}
} else if (dir == 3) {
for (int i : negm.get((int) (x + y))) {
if (ans[i] == -1) {
ans[i] = time + x - px[i];
}
}
long tx = x;
long ty = y;
x -= Math.min(tx, m - ty);
y += Math.min(tx, m - ty);
time += Math.min(tx, m - ty);
if (x == 0) {
dir = 0;
} else {
dir = 2;
}
}
if ((x == n && y == m) || (x == 0 && y == m) || (x == n && y == 0) || (x == 0 && y == 0)) {
break;
}
}
for (long i : ans) {
System.out.println(i);
}
}
}
| Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | 18f2ae0cf6d4169f201baa6c76721caf | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
InputReader in=new InputReader(System.in);
PrintWriter out=new PrintWriter(System.out);
//Scanner in=new Scanner(System.in);
int n=in.nextInt();
int m=in.nextInt();
int k=in.nextInt();
Map<Integer,List<Integer>> map1=new HashMap<Integer,List<Integer>>();
Map<Integer,List<Integer>> map2=new HashMap<Integer,List<Integer>>();
int[][] a=new int[k][2];
for(int i=0;i<k;i++){
int x=in.nextInt();
int y=in.nextInt();
mapAdd(map1,x-y,i);
mapAdd(map2,x+y,i);
a[i][0]=x;
a[i][1]=y;
}
long[] ans=new long[k];
for(int i=0;i<k;i++){
ans[i]=-1;
}
Point now=new Point(0,0,1);
long nowTime=0;
while(true){
int way=now.way;
int x=now.x;
int y=now.y;
Point next=now.go(n,m);
if((way==1)||(way==3)){
int sum=x-y;
if(map1.containsKey(sum)==true){
List<Integer> list=map1.get(sum);
for(Integer j:list){
if(ans[j]==-1){
ans[j]=nowTime+Math.abs(x-a[j][0]);
}
}
map1.remove(sum);
}
}
else{
int sum=x+y;
if(map2.containsKey(sum)==true){
List<Integer> list=map2.get(sum);
for(Integer j:list){
if(ans[j]==-1){
ans[j]=nowTime+Math.abs(x-a[j][0]);
}
}
map2.remove(sum);
}
}
if(next.isEnd(n,m)==true){
break;
}
nowTime=nowTime+Math.abs(next.x-now.x);
now=next;
}
for(int i=0;i<k;i++){
out.println(ans[i]);
}
out.close();
}
static void mapAdd(Map<Integer,List<Integer>> map,int key,int num){
if(map.containsKey(key)==false){
map.put(key,new ArrayList<Integer>());
}
map.get(key).add(num);
}
static class Point{
int x;
int y;
int way;
public Point(int x,int y,int way){
super();
this.x=x;
this.y=y;
this.way=way;
}
public Point go(int n,int m){
if(way==1){
int u=n-x;
int v=m-y;
if(u>=v){
return new Point(x+v,y+v,2);
}
else{
return new Point(x+u,y+u,4);
}
}
else if(way==2){
int u=n-x;
int v=y;
if(u>=v){
return new Point(x+v,y-v,1);
}
else{
return new Point(x+u,y-u,3);
}
}
else if(way==3){
int u=x;
int v=y;
if(u>=v){
return new Point(x-v,y-v,4);
}
else{
return new Point(x-u,y-u,2);
}
}
else{
int u=x;
int v=m-y;
if(u>=v){
return new Point(x-v,y+v,3);
}
else{
return new Point(x-u,y+u,1);
}
}
}
public boolean isEnd(int n,int m){
if((x==0)&&(y==0)){
return true;
}
else if((x==0)&&(y==m)){
return true;
}
else if((x==n)&&(y==0)){
return true;
}
else if((x==n)&&(y==m)){
return true;
}
return false;
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader (File f){
try{
br=new BufferedReader(new FileReader(f));
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
public InputReader (InputStream in){
br=new BufferedReader(new InputStreamReader(in));
}
public String next(){
while(st==null||!st.hasMoreTokens()){
try{
st=new StringTokenizer(br.readLine());
}catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public boolean hasNext(){
while(st==null||!st.hasMoreTokens()){
String s=null;
try{
s=br.readLine();
}catch(IOException e){
e.printStackTrace();
}
if(s==null)
return false;
st=new StringTokenizer(s);
}
return true;
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
} | Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | ae9f227d9fe7709778581a4e31ba045a | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
FastScanner in;
PrintWriter out;
static final String FILE = "";
int n, m, k;
static long pack(int a, int b) {
return ((long)(a) << 32) + b;
}
static int getA(long v) {
return (int)(v >> 32);
}
static int getB(long v) {
return (int)(v - ((long)(getA(v)) << 32));
}
long getVal(int a, int b, int side) {
int diff;
if (side == 0) { // right-up
diff = min(n - a, m - b);
a += diff;
b += diff;
} else if (side == 1) { // right-down
diff = min(n - a, b);
a += diff;
b -= diff;
} else if (side == 2) { // left-up
diff = min(a, m - b);
a -= diff;
b += diff;
} else if (side == 3) { // left-down
diff = min(a, b);
a -= diff;
b -= diff;
}
return pack(a, b);
}
void solve() {
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
if (n == m) {
for (int i = 0; i < k; i++) {
int a = in.nextInt(), b = in.nextInt();
if (a == b) {
out.println(a);
} else {
out.println(-1);
}
}
return;
}
Map<Integer, Set<Integer>> downer = new TreeMap<>();
Map<Integer, Set<Integer>> lefter = new TreeMap<>();
List<Integer> as = new ArrayList<>();
List<Integer> bs = new ArrayList<>();
for (int i = 0; i < k; i++) {
int a = in.nextInt(), b = in.nextInt();
Set<Integer> set = downer.getOrDefault(a - b, new TreeSet<>());
set.add(i);
downer.put(a - b, set);
set = lefter.getOrDefault(a + b, new TreeSet<>());
set.add(i);
lefter.put(a + b, set);
as.add(a);
bs.add(b);
}
Set<Long> been = new TreeSet<>();
long[] ans = new long[k];
boolean[] used = new boolean[k];
Arrays.fill(ans, -1);
int a = 0, b = 0, side = 0;
int diff = 0;
long time = 0;
while (true) {
long v = pack(a, b);
if (been.contains(v))
break;
been.add(v);
if (side == 0) { // right-up
if (downer.containsKey(a - b)) {
Set<Integer> set = downer.get(a - b);
for (Integer it : set) {
if (used[it])
continue;
used[it] = true;
ans[it] = time + abs(a - as.get(it));
}
downer.remove(a - b);
}
diff = min(n - a, m - b);
a += diff;
b += diff;
if (a == n)
side = 2;
else if (b == m)
side = 1;
} else if (side == 1) { // right-down
if (lefter.containsKey(a + b)) {
Set<Integer> set = lefter.get(a + b);
for (Integer it : set) {
if (used[it])
continue;
used[it] = true;
ans[it] = time + abs(a - as.get(it));
}
lefter.remove(a - b);
}
diff = min(n - a, b);
a += diff;
b -= diff;
if (b == 0)
side = 0;
else if (a == n)
side = 3;
} else if (side == 2) { // left-up
if (lefter.containsKey(a + b)) {
Set<Integer> set = lefter.get(a + b);
for (Integer it : set) {
if (used[it])
continue;
used[it] = true;
ans[it] = time + abs(a - as.get(it));
}
lefter.remove(a - b);
}
diff = min(a, m - b);
a -= diff;
b += diff;
if (a == 0)
side = 0;
else if (b == m)
side = 3;
} else if (side == 3) { // left-down
if (downer.containsKey(a - b)) {
Set<Integer> set = downer.get(a - b);
for (Integer it : set) {
if (used[it])
continue;
used[it] = true;
ans[it] = time + abs(a - as.get(it));
}
downer.remove(a - b);
}
diff = min(a, b);
a -= diff;
b -= diff;
if (b == 0)
side = 2;
else if (a == 0)
side = 1;
}
time += diff;
}
for (Long it : ans)
out.println(it);
}
public void run() {
if (FILE.equals("")) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
try {
in = new FastScanner(new FileInputStream(FILE +
".in"));
out = new PrintWriter(new FileOutputStream(FILE +
".out"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
solve();
out.close();
}
public static void main(String[] args) {
(new Main()).run();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
}
} | Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | 1b0a8577f3b2495520f5f8589caba792 | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
StringTokenizer tk;
tk = new StringTokenizer(in.readLine());
int n = parseInt(tk.nextToken()),m = parseInt(tk.nextToken()),k = parseInt(tk.nextToken());
List<point> [] sum = new List[n+m+1];
List<point> [] diff1 = new List[n+m+1];
List<point> [] diff2 = new List[n+m+1];
for(int i=0; i<sum.length; i++) {
sum[i] = new LinkedList<>();
diff1[i] = new LinkedList<>();
diff2[i] = new LinkedList<>();
}
long [] ans = new long[k];
Arrays.fill(ans, (long)1e10);
for(int i=0; i<k; i++) {
tk = new StringTokenizer(in.readLine());
int x = parseInt(tk.nextToken()),y = parseInt(tk.nextToken());
sum[x+y].add(new point(x,y,i));
if(x>=y)
diff1[x-y].add(new point(x,y,i));
if(y>=x) diff2[y-x].add(new point(x,y,i));
}
int x=0,y=0,dx=+1,dy=+1;
long cnt = 0;
while(k > 0 && !((x==0 && y==0 && cnt>0) || (x==0 && y==n) || (x==m && y==0) || (x==m && y==n))) {
//System.out.println(x+" , "+y+" : "+cnt);
if(dx == dy) {
int mm1 = min(n-x,m-y),mm2 = min(x,y);
if(x>=y) {
for(point p : diff1[x-y]) {
if((dx==1 && p.x>=x && p.x<=x+mm1 && p.y>=y && p.y<=y+mm1) || (dx==-1 && p.x>=x-mm2 && p.x<=x && p.y>=y-mm2 && p.y<=y)) {
if(ans[p.i]==(long)1e10) k--;
ans[p.i] = min(ans[p.i], cnt+abs(p.x-x));
//diff[abs(x-y)].remove(p);
}
}
}
if(y>=x) {
for(point p : diff2[y-x]) {
if((dx==1 && p.x>=x && p.x<=x+mm1 && p.y>=y && p.y<=y+mm1) || (dx==-1 && p.x>=x-mm2 && p.x<=x && p.y>=y-mm2 && p.y<=y)) {
if(ans[p.i]==(long)1e10) k--;
ans[p.i] = min(ans[p.i], cnt+abs(p.x-x));
//diff[abs(x-y)].remove(p);
}
}
}
/* for(point p : diff[abs(x-y)]) {
if((dx==1 && p.x>=x && p.x<=x+mm1 && p.y>=y && p.y<=y+mm1) || (dx==-1 && p.x>=x-mm2 && p.x<=x && p.y>=y-mm2 && p.y<=y)) {
ans[p.i] = min(ans[p.i], cnt+abs(p.x-x));
//diff[abs(x-y)].remove(p);
k--;
}
}*/
cnt += (long)(dx==1 ? mm1 : mm2);
if(dx==1) {
x += mm1;
y += mm1;
if(x==n) dx = -1;
else if(y==m) dy = -1;
} else {
x -= mm2;
y -= mm2;
if(x==0) dx = +1;
else if(y==0) dy = +1;
}
} else {
int mm1 = min(x,m-y),mm2 = min(n-x,y);
for(point p : sum[x+y]) {
if((dx==-1 && p.x>=x-mm1 && p.x<=x && p.y>=y && p.y<=y+mm1) || (dx==1 && p.x>=x && p.x<=x+mm2 && p.y>=y-mm2 && p.y<=y)) {
if(ans[p.i]==(long)1e10) k--;
ans[p.i] = min(ans[p.i], cnt+abs(p.x-x));
// sum[x+y].remove(p);
}
}
cnt += (long)(dx==-1 ? mm1 : mm2);
if(dx==-1) {
x -= mm1;
y += mm1;
if(x==0) dx = +1;
else if(y==m) dy = -1;
} else {
x += mm2;
y -= mm2;
if(x==n) dx = -1;
else if(y==0) dy = +1;
}
}
}
for(int i=0; i<ans.length; i++)
out.append((ans[i]==(long)1e10 ? -1 : ans[i])).append("\n");
System.out.print(out);
}
}
class point {
int x,y,i;
public point(int x,int y,int i) {
this.x = x;
this.y = y;
this.i = i;
}
}
| Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | 61e6fe381f7b963f86c4a7405aeee855 | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class ProblemC {
BufferedReader rd;
ProblemC() throws IOException {
rd = new BufferedReader(new InputStreamReader(System.in));
compute();
}
private void compute() throws IOException {
int[] a = intarr();
int n = a[0];
int m = a[1];
int k = a[2];
Map<Integer, List<int[]>> slash = new HashMap<>();
Map<Integer, List<int[]>> blash = new HashMap<>();
for(int i=0;i<k;i++) {
a = intarr();
int x = a[0];
int y = a[1];
slash.computeIfAbsent(x-y, z -> new ArrayList<>()).add(new int[] { x, i });
blash.computeIfAbsent(x+y, z -> new ArrayList<>()).add(new int[] { x, i });
}
long[] res = new long[k];
Arrays.fill(res, -1);
int dir = 0;
int sx = 0;
int sy = 0;
long t = 0;
boolean end = false;
while(!end) {
int leftX, leftY, mi = 0;
List<int[]> c;
switch(dir) {
case 0:
leftX = n-sx;
leftY = m-sy;
c = slash.get(sx-sy);
if(c != null) {
for (int[] p : c) {
if (res[p[1]] == -1) {
res[p[1]] = t + (p[0] - sx);
}
}
}
if(leftX == leftY) {
end = true;
} else if(leftX > leftY) {
dir = 3;
} else {
dir = 1;
}
mi = Math.min(leftX, leftY);
sx += mi;
sy += mi;
break;
case 2:
leftX = sx;
leftY = sy;
c = slash.get(sx-sy);
if(c != null) {
for (int[] p : c) {
if (res[p[1]] == -1) {
res[p[1]] = t + (sx - p[0]);
}
}
}
if(leftX == leftY) {
end = true;
} else if(leftX > leftY) {
dir = 1;
} else {
dir = 3;
}
mi = Math.min(leftX, leftY);
sx -= mi;
sy -= mi;
break;
case 1:
leftX = sx;
leftY = m-sy;
c = blash.get(sx+sy);
if(c != null) {
for (int[] p : c) {
if (res[p[1]] == -1) {
res[p[1]] = t + (sx - p[0]);
}
}
}
if(leftX == leftY) {
end = true;
} else if(leftX > leftY) {
dir = 2;
} else {
dir = 0;
}
mi = Math.min(leftX, leftY);
sx -= mi;
sy += mi;
break;
case 3:
leftX = n-sx;
leftY = sy;
c = blash.get(sx+sy);
if(c != null) {
for (int[] p : c) {
if (res[p[1]] == -1) {
res[p[1]] = t + (p[0] - sx);
}
}
}
if(leftX == leftY) {
end = true;
} else if(leftX > leftY) {
dir = 0;
} else {
dir = 2;
}
mi = Math.min(leftX, leftY);
sx += mi;
sy -= mi;
break;
}
t += mi;
}
StringBuilder buf = new StringBuilder();
for(int i=0;i<res.length;i++) {
if(i > 0) {
buf.append('\n');
}
buf.append(res[i]);
}
out(buf);
}
private int[] intarr() throws IOException {
return intarr(rd.readLine());
}
private int[] intarr(String s) {
String[] q = split(s);
int n = q.length;
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = Integer.parseInt(q[i]);
}
return a;
}
public String[] split(String s) {
if(s == null) {
return new String[0];
}
int n = s.length();
int start = -1;
int end = 0;
int sp = 0;
boolean lastWhitespace = true;
for(int i=0;i<n;i++) {
char c = s.charAt(i);
if(isWhitespace(c)) {
lastWhitespace = true;
} else {
if(lastWhitespace) {
sp++;
}
if(start == -1) {
start = i;
}
end = i;
lastWhitespace = false;
}
}
if(start == -1) {
return new String[0];
}
String[] res = new String[sp];
int last = start;
int x = 0;
lastWhitespace = true;
for(int i=start;i<=end;i++) {
char c = s.charAt(i);
boolean w = isWhitespace(c);
if(w && !lastWhitespace) {
res[x++] = s.substring(last,i);
} else if(!w && lastWhitespace) {
last = i;
}
lastWhitespace = w;
}
res[x] = s.substring(last,end+1);
return res;
}
private boolean isWhitespace(char c) {
return c==' ' || c=='\t';
}
private static void out(Object x) {
System.out.println(x);
}
public static void main(String[] args) throws IOException {
new ProblemC();
}
}
| Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | cc4d8e13b981873379d2372722b7ef49 | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | //package codeforces.intel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class RayTracing {
//http://codeforces.com/contest/724/problem/C
public void traceRay(int row,int col,int[][] data){
//two map to get the sum and dif of all data points
HashMap<Integer, ArrayList<Integer>> sumMap=new HashMap<Integer,ArrayList<Integer>>();
HashMap<Integer, ArrayList<Integer>> difMap=new HashMap<Integer,ArrayList<Integer>>();
int sum,dif;
ArrayList<Integer> tmp;
for(int i=0;i<data.length;i++){
sum=data[i][0]+data[i][1];
dif=data[i][0]-data[i][1];
if(sumMap.containsKey(sum))
sumMap.get(sum).add(i);
else{
tmp=new ArrayList<Integer>();
tmp.add(i);
sumMap.put(sum,tmp);
}
if(difMap.containsKey(dif))
difMap.get(dif).add(i);
else{
tmp=new ArrayList<Integer>();
tmp.add(i);
difMap.put(dif,tmp);
}
}
//System.out.println(sumMap);
//System.out.println(difMap);
//answer array
long[] ans=new long[data.length];
Arrays.fill(ans,-1);
//direction
int up=1,right=1,curR=0,curC=0,step,step_up,step_right,isSum=0;
long allStep=0;
while(true){
//get current sum/dif
if(isSum==1){
isSum=0;
sum=curR+curC;
tmp=sumMap.get(sum);
if(tmp!=null)
for(int i:tmp)
if(ans[i]==-1) //not processed
ans[i]=Math.abs(data[i][0]-curR)+allStep;
}
else{
isSum=1;
dif=curR-curC;
tmp=difMap.get(dif);
if(tmp!=null)
for(int i:tmp)
if(ans[i]==-1) //not processed
ans[i]=Math.abs(data[i][0]-curR)+allStep;
}
//get next reflect point
step_up= up==1 ? row-curR : curR;
step_right= right==1 ? col-curC : curC;
step=Math.min(step_up, step_right);
allStep+=step;
curR=curR+up*step;
curC=curC+right*step;
//System.out.println(step+" "+curR+" "+curC);
//check is corner
if((curR==0||curR==row)&&(curC==0||curC==col))
break;
//change direction
if(curR==row||curR==0)
up=-up;
if(curC==0||curC==col)
right=-right;
}
for(int i=0;i<ans.length;i++)
System.out.println(ans[i]);
}
public static void main(String[] args){
Scanner sin=new Scanner(System.in);
int row=sin.nextInt(),col=sin.nextInt(),num=sin.nextInt();
int[][] data=new int[num][2];
for(int i=0;i<num;i++){
data[i][0]=sin.nextInt();
data[i][1]=sin.nextInt();
}
sin.close();
new RayTracing().traceRay(row,col,data);
}
}
| Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | ede648a6903f42a0705241c837fe141f | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.io.BufferedReader;
import java.util.regex.Pattern;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author amalev
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
long fromPointX(long p) {
return (p / 1_000_000L);
}
long fromPointY(long p) {
return (p % 1_000_000L);
}
long toPoint(long x, long y) {
return x * 1_000_000 + y;
}
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
long[] dx = new long[k];
long[] dy = new long[k];
for (int i = 0; i < k; i++) {
dx[i] = in.nextInt();
dy[i] = in.nextInt();
}
HashMap<Long, Long> map = new HashMap<>();
map.put(0L, 0L);
{
long x = 0;
long y = 0;
int a = 1;
int b = 1;
long t = 0;
boolean possible = true;
while (possible) {
long tx = 0;
long ty = 0;
if (a > 0) {
tx = n - x;
} else {
tx = x;
}
if (b > 0) {
ty = m - y;
} else {
ty = y;
}
long dt = Math.min(tx, ty);
long xn = x + a * dt;
long yn = y + b * dt;
t += dt;
long p = toPoint(xn, yn);
if (!map.containsKey(p)) {
map.put(p, t);
}
if (xn == 0 || xn == n) {
a = -a;
}
if (yn == 0 || yn == m) {
b = -b;
}
x = xn;
y = yn;
if (xn == 0 || xn == n) {
if (yn == 0 || yn == m) {
possible = false;
break;
}
}
}
}
for (int i = 0; i < k; i++) {
long x = dx[i];
long y = dy[i];
long minP = -1;
long minT = Long.MAX_VALUE;
for (int a = -1; a <= 1; a++) {
for (int b = -1; b <= 1; b++) {
if (a == 0 || b == 0) continue;
long tx = 0;
long ty = 0;
if (a > 0) {
tx = n - x;
} else {
tx = x;
}
if (b > 0) {
ty = m - y;
} else {
ty = y;
}
long dt = Math.min(tx, ty);
long xn = x + a * dt;
long yn = y + b * dt;
long p = toPoint(xn, yn);
if (map.containsKey(p)) {
long t = map.get(p);
if (t < minT) {
minT = t;
minP = p;
}
}
}
}
long t = -1;
if (minP >= 0) {
long xn = fromPointX(minP);
long yn = fromPointY(minP);
t = minT + Math.abs(x - xn);
}
out.println(t);
}
}
}
static class FastScanner {
final BufferedReader input;
String[] buffer;
int pos;
final static Pattern SEPARATOR = Pattern.compile("\\s+");
public FastScanner(InputStream inputStream) {
input = new BufferedReader(new InputStreamReader(inputStream));
}
private String read() {
try {
if (buffer == null || pos >= buffer.length) {
buffer = SEPARATOR.split(input.readLine());
pos = 0;
}
return buffer[pos++];
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public int nextInt() {
return Integer.parseInt(read());
}
}
}
| Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | 2d6ec3bdb304b043e39e06ae6df6c664 | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
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.StringTokenizer;
public class C {
static StringTokenizer st;
static BufferedReader br;
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 n = nextInt();
int m = nextInt();
int k = nextInt();
int[]x = new int[k+1], y = new int[k+1];
ArrayList<Integer>[]L1 = new ArrayList[200015];
ArrayList<Integer>[]L2 = new ArrayList[200015];
for (int i = 0; i < L1.length; i++) {
L1[i] = new ArrayList<>();
L2[i] = new ArrayList<>();
}
long[]ans = new long[k+1];
Arrays.fill(ans, -1);
for (int i = 1; i <= k; i++) {
x[i] = nextInt();
y[i] = nextInt();
L1[x[i]+y[i]].add(i);
L2[x[i]-y[i]+100002].add(i);
}
int x0 = 0, y0 = 0;
int dx = 1, dy = 1;
long time = 0;
boolean[]used1 = new boolean[200015];
boolean[]used2 = new boolean[200015];
for(; ;) {
if (dx==1 && dy==1) {
if (used2[x0-y0+100002])
break;
used2[x0-y0+100002] = true;
for (int i : L2[x0-y0+100002]) {
if (ans[i] == -1)
ans[i] = time + x[i]-x0;
}
if (n-x0 <= m-y0) {
y0 += n-x0;
time += n-x0;
x0 = n;
dx = -dx;
}
else {
x0 += m-y0;
time += m-y0;
y0 = m;
dy = -dy;
}
}
else if (dx==-1 && dy==1) {
if (used1[x0+y0])
break;
used1[x0+y0] = true;
for (int i : L1[x0+y0]) {
if (ans[i] == -1)
ans[i] = time + y[i]-y0;
}
if (x0 <= m-y0) {
y0 += x0;
time += x0;
x0 = 0;
dx = -dx;
}
else {
x0 -= m-y0;
time += m-y0;
y0 = m;
dy = -dy;
}
}
else if (dx==-1 && dy==-1) {
if (used2[x0-y0+100002])
break;
used2[x0-y0+100002] = true;
for (int i : L2[x0-y0+100002]) {
if (ans[i] == -1)
ans[i] = time + y0 - y[i];
}
if (x0 <= y0) {
y0 -= x0;
time += x0;
x0 = 0;
dx = -dx;
}
else {
x0 -= y0;
time += y0;
y0 = 0;
dy = -dy;
}
}
else {
if (used1[x0+y0])
break;
used1[x0+y0] = true;
for (int i : L1[x0+y0]) {
if (ans[i] == -1)
ans[i] = time + x[i] - x0;
}
if (n-x0 <= y0) {
y0 -= n-x0;
time += n-x0;
x0 = n;
dx = -dx;
}
else {
x0 += y0;
time += y0;
y0 = 0;
dy = -dy;
}
}
if (x0==0 && y0==0)
break;
if (x0==n && y0==m)
break;
if (x0==0 && y0==m)
break;
if (x0==n && y0==0)
break;
}
for (int i = 1; i <= k; i++) {
pw.println(ans[i]);
}
pw.close();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
} | Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | 4c89d65de03ac94e3cc7cb1cbc441591 | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF724C {
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int gcd_(int a, int b, int[] xy) {
if (b == 0) {
xy[0] = 1;
xy[1] = 0;
return a;
} else {
int d = gcd_(b, a % b, xy);
int t = xy[0] - a / b * xy[1];
xy[0] = xy[1];
xy[1] = t;
return d;
}
}
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 k = Integer.parseInt(st.nextToken());
PrintWriter pw = new PrintWriter(System.out);
for (int i = 0; i < k; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
long t = -1;
if (x == y)
t = x;
else { // n * 2 * xy[0] - m * 2 * xy[1] = y * sy - x * sx;
int d = gcd(n * 2, -m * 2);
long lcm = (long) n * 2 / Math.abs(d) * m * 2;
int[] xy = { 0, 0 };
for (int sx = -1; sx <= 1; sx += 2)
for (int sy = -1; sy <= 1; sy += 2)
if ((y * sy - x * sx) % d == 0) {
int c = (y * sy - x * sx) / d;
gcd_(n * 2, -m * 2, xy);
long x_ = (long) n * 2 * xy[0] * c + x * sx;
//long y_ = (long) m * 2 * xy[1] * c + y * sy;
x_ = (x_ % lcm + lcm) % lcm;
if (t == -1 || t > x_)
t = x_;
}
}
pw.println(t);
}
pw.close();
}
}
| Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | 07a0d0a1405fb6c35961cf54e78a0c89 | train_002.jsonl | 1475928900 | There are k sensors located in the rectangular room of size nβΓβm meters. The i-th sensor is located at point (xi,βyi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,β0) and (n,βm). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,β0) the laser ray is released in the direction of point (1,β1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,β1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print β-β1 for such sensors. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
public class TaskC {
public static void main(String[] args) {
TaskC tC = new TaskC();
PrintWriter pw = new PrintWriter(System.out);
tC.solve(new Scanner(System.in), pw);
pw.close();
}
int n, m, k;
int max;
List<List<Integer>> list0;
List<List<Integer>> list1;
int[] x;
int[] y;
long[] time;
public void solve(Scanner input, PrintWriter output) {
n = input.nextInt();
m = input.nextInt();
max = Math.max(n, m);
list0 = new ArrayList<List<Integer>>();
list1 = new ArrayList<List<Integer>>();
for (int i = 0; i <= 2 * max; i++) {
list0.add(new ArrayList<Integer>());
list1.add(new ArrayList<Integer>());
}
k = input.nextInt();
x = new int[k];
y = new int[k];
time = new long[k];
Arrays.fill(time, -1);
// reading input and putting sensors into the two lists
for (int i = 0; i < k; i++) {
x[i] = input.nextInt();
y[i] = input.nextInt();
list0.get(m + x[i] - y[i]).add(i);
list1.get(x[i] + y[i]).add(i);
}
// simulating the reflecting process
Point current = new Point(0, 0);
int dir = 0;
long currentTime = 0L;
for (int i = 0; i < 4 * max; i++) { //bouncing only within these time
Point next = getEnd(current, dir);
if (current.x - current.y == next.x - next.y) { // type 0
for (int idx : list0.get(m + current.x - current.y)) {
if (time[idx] != -1) {
continue;
}
time[idx] = currentTime + Math.abs(x[idx] - current.x);
}
} else {
for (int idx : list1.get(current.x + current.y)) {
if (time[idx] != -1) {
continue;
}
time[idx] = currentTime + Math.abs(x[idx] - current.x);
}
}
if (isCorner(next)) {
break;
}
currentTime += Math.abs(current.x - next.x);
current = next;
dir = nextDir(next, dir);
}
// printing output
for (long val : time) {
output.println(val);
}
}
private static final int[] dx = {1, 1, -1, -1};
private static final int[] dy = {1, -1, -1, 1};
private Point getEnd(Point current, int dir) {
int delta = 0;
if (dir == 0) delta = Math.min(n - current.x, m - current.y);
else if (dir == 1) delta = Math.min(n - current.x, current.y);
else if (dir == 2) delta = Math.min(current.x, current.y);
else delta = Math.min(current.x, m - current.y); // dir == 3
Point next = new Point(current.x + dx[dir] * delta, current.y + dy[dir] * delta);
return next;
}
private int nextDir(Point next, int dir) {
if (dir == 0) {
return (next.y == m) ? 1 : 3;
} else if (dir == 1) {
return (next.x == n) ? 2 : 0;
} else if (dir == 2) {
return (next.y == 0) ? 3 : 1;
}
return (next.x == 0) ? 0 : 2;
}
private boolean isCorner(Point p) {
if (p.x == 0 && p.y == 0) return true;
if (p.x == 0 && p.y == m) return true;
if (p.x == n && p.y == 0) return true;
if (p.x == n && p.y == m) return true;
return false;
}
private class Point {
private int x;
private int y;
private Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}
| Java | ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"] | 2 seconds | ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"] | NoteIn the first sample, the ray will consequently pass through the points (0,β0), (1,β1), (2,β2), (3,β3). Thus, it will stop at the point (3,β3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,β0), (1,β1), (2,β2), (3,β3), (2,β4), (1,β3), (0,β2), (1,β1), (2,β0), (3,β1), (2,β2), (1,β3), (0,β4). The ray will stop at the point (0,β4) after 12 seconds. It will reflect at the points (3,β3), (2,β4), (0,β2), (2,β0) and (3,β1). | Java 8 | standard input | [
"hashing",
"greedy",
"number theory",
"math",
"implementation",
"sortings"
] | 27a521d4d59066e50e870e7934d4b190 | The first line of the input contains three integers n, m and k (2ββ€βn,βmββ€β100β000, 1ββ€βkββ€β100β000)Β β lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1ββ€βxiββ€βnβ-β1, 1ββ€βyiββ€βmβ-β1)Β β coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. | 1,800 | Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or β-β1 if this will never happen. | standard output | |
PASSED | b0c271acdaa6ef64ebdcb1a6a09506bd | train_002.jsonl | 1298390400 | After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher gave them 3 strings and asked them to concatenate them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation.Unfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked.Now the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers.Shapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said: As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin. As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include "-", ";" and "_". These characters are my own invention of course! And I call them Signs. The length of all initial strings was less than or equal to 100 and the lengths of my students' answers are less than or equal to 600 My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes. Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN You should indicate for any of my students if his answer was right or wrong. Do this by writing "WA" for Wrong answer or "ACC" for a correct answer. I should remind you that none of the strings (initial strings or answers) are empty. Finally, do these as soon as possible. You have less than 2 hours to complete this. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Badr {
public static void main(String[] args) throws IOException{
BufferedReader buf =new BufferedReader(new InputStreamReader(System.in));
String s1=remove(buf.readLine()).toLowerCase();
String s2=remove(buf.readLine()).toLowerCase();
String s3=remove(buf.readLine()).toLowerCase();
int n=Integer.parseInt(buf.readLine());
String t1=s1+s2+s3;
String t2=s1+s3+s2;
String t3=s2+s1+s3;
String t4=s2+s3+s1;
String t5=s3+s1+s2;
String t6=s3+s2+s1;
while (n-->0){
String an=remove(buf.readLine()).toLowerCase();
boolean x=an.equals(t1)||an.equals(t2)||an.equals(t3)||an.equals(t4)||an.equals(t5)||an.equals(t6);
System.out.println(x?"ACC":"WA");
}
}
static String remove(String s){
StringBuilder b=new StringBuilder();
for (int i=0;i<s.length();i++){
if (Character.isAlphabetic(s.charAt(i)))b.append(s.charAt(i));
}
return b.toString();
}
}
| Java | ["Iran_\nPersian;\nW_o;n;d;e;r;f;u;l;\n7\nWonderfulPersianIran\nwonderful_PersIAN_IRAN;;_\nWONDERFUL___IRAN__PERSIAN__;;\nIra__Persiann__Wonderful\nWonder;;fulPersian___;I;r;a;n;\n__________IranPersianWonderful__________\nPersianIran_is_Wonderful", "Shapur;;\nis___\na_genius\n3\nShapur__a_is___geniUs\nis___shapur___a__Genius;\nShapur;;is;;a;;geni;;us;;"] | 2 seconds | ["ACC\nACC\nACC\nWA\nACC\nACC\nWA", "WA\nACC\nACC"] | null | Java 7 | standard input | [
"strings"
] | 95ccc87fe9e431f9c6eeffeaf049f797 | The first three lines contain a string each. These are the initial strings. They consists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). All the initial strings have length from 1 to 100, inclusively. In the fourth line there is a single integer n (0ββ€βnββ€β1000), the number of students. Next n lines contain a student's answer each. It is guaranteed that the answer meets what the teacher said. Each answer iconsists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). Length is from 1 to 600, inclusively. | 1,300 | For each student write in a different line. Print "WA" if his answer is wrong or "ACC" if his answer is OK. | standard output | |
PASSED | 206d68eb15cdf233af8c4698085ddfad | train_002.jsonl | 1298390400 | After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher gave them 3 strings and asked them to concatenate them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation.Unfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked.Now the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers.Shapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said: As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin. As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include "-", ";" and "_". These characters are my own invention of course! And I call them Signs. The length of all initial strings was less than or equal to 100 and the lengths of my students' answers are less than or equal to 600 My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes. Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN You should indicate for any of my students if his answer was right or wrong. Do this by writing "WA" for Wrong answer or "ACC" for a correct answer. I should remind you that none of the strings (initial strings or answers) are empty. Finally, do these as soon as possible. You have less than 2 hours to complete this. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HardWork {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuilder out=new StringBuilder();
String s1=br.readLine().toLowerCase();
String s2=br.readLine().toLowerCase();
String s3=br.readLine().toLowerCase();
StringBuilder sb1=new StringBuilder();
StringBuilder sb2=new StringBuilder();
StringBuilder sb3=new StringBuilder();
for (int i=0; i<s1.length(); i++){
if (s1.charAt(i)!='-' && s1.charAt(i)!=';' && s1.charAt(i)!='_')
sb1.append(s1.charAt(i));
}
for (int i=0; i<s2.length(); i++){
if (s2.charAt(i)!='-' && s2.charAt(i)!=';' && s2.charAt(i)!='_')
sb2.append(s2.charAt(i));
}
for (int i=0; i<s3.length(); i++){
if (s3.charAt(i)!='-' && s3.charAt(i)!=';' && s3.charAt(i)!='_')
sb3.append(s3.charAt(i));
}
String a1=sb1.toString() + sb2.toString()+sb3.toString();
String a2=sb1.toString() + sb3.toString()+sb2.toString();
String a3=sb2.toString() + sb1.toString()+sb3.toString();
String a4=sb2.toString() + sb3.toString()+sb1.toString();
String a5=sb3.toString() + sb1.toString()+sb2.toString();
String a6=sb3.toString() + sb2.toString()+sb1.toString();
int n=Integer.parseInt(br.readLine());
for (int i=0; i<n; i++){
String ans=br.readLine().toLowerCase();
StringBuilder anssb=new StringBuilder();
for (int j=0; j<ans.length(); j++){
if (ans.charAt(j)!='-' && ans.charAt(j)!=';' && ans.charAt(j)!='_')
anssb.append(ans.charAt(j));
}
String finA=anssb.toString();
if (finA.equals(a1)||finA.equals(a2)||finA.equals(a3)||finA.equals(a4)||finA.equals(a5)||finA.equals(a6))
out.append("ACC\n");
else
out.append("WA\n");
}
System.out.print(out);
}
}
| Java | ["Iran_\nPersian;\nW_o;n;d;e;r;f;u;l;\n7\nWonderfulPersianIran\nwonderful_PersIAN_IRAN;;_\nWONDERFUL___IRAN__PERSIAN__;;\nIra__Persiann__Wonderful\nWonder;;fulPersian___;I;r;a;n;\n__________IranPersianWonderful__________\nPersianIran_is_Wonderful", "Shapur;;\nis___\na_genius\n3\nShapur__a_is___geniUs\nis___shapur___a__Genius;\nShapur;;is;;a;;geni;;us;;"] | 2 seconds | ["ACC\nACC\nACC\nWA\nACC\nACC\nWA", "WA\nACC\nACC"] | null | Java 7 | standard input | [
"strings"
] | 95ccc87fe9e431f9c6eeffeaf049f797 | The first three lines contain a string each. These are the initial strings. They consists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). All the initial strings have length from 1 to 100, inclusively. In the fourth line there is a single integer n (0ββ€βnββ€β1000), the number of students. Next n lines contain a student's answer each. It is guaranteed that the answer meets what the teacher said. Each answer iconsists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). Length is from 1 to 600, inclusively. | 1,300 | For each student write in a different line. Print "WA" if his answer is wrong or "ACC" if his answer is OK. | standard output | |
PASSED | 3b817a252798469bb4103e0308abbdd9 | train_002.jsonl | 1298390400 | After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher gave them 3 strings and asked them to concatenate them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation.Unfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked.Now the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers.Shapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said: As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin. As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include "-", ";" and "_". These characters are my own invention of course! And I call them Signs. The length of all initial strings was less than or equal to 100 and the lengths of my students' answers are less than or equal to 600 My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes. Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN You should indicate for any of my students if his answer was right or wrong. Do this by writing "WA" for Wrong answer or "ACC" for a correct answer. I should remind you that none of the strings (initial strings or answers) are empty. Finally, do these as soon as possible. You have less than 2 hours to complete this. | 256 megabytes | import java.io.*;
import java.util.*;
public class HardWork
{
public static void main(String[] args) throws IOException
{
//Locale.setDefault (Locale.US);
Reader in = new Reader();
StringBuilder out = new StringBuilder();
String[] words;
String ans;
int n, c;
for (int i = 0; i < 1; i++) {
words = new String[3];
for (int j = 0; j < 3; j++)
words[j] = in.next().toLowerCase().replaceAll("[^a-z]", "");
n = in.nextInt();
for (int j = 0; j < n; j++) {
ans = in.next().toLowerCase().replaceAll("[^a-z]", "");
if(ans.equals(words[0]+words[1]+words[2]))
System.out.println("ACC");
else if(ans.equals(words[0]+words[2]+words[1]))
System.out.println("ACC");
else if(ans.equals(words[1]+words[0]+words[2]))
System.out.println("ACC");
else if(ans.equals(words[1]+words[2]+words[0]))
System.out.println("ACC");
else if(ans.equals(words[2]+words[0]+words[1]))
System.out.println("ACC");
else if(ans.equals(words[2]+words[1]+words[0]))
System.out.println("ACC");
else
System.out.println("WA");
}
}
}
static class Reader
{
BufferedReader br;
StringTokenizer st;
Reader() { // To read from the standard input
br = new BufferedReader(new InputStreamReader(System.in));
}
Reader(int i) throws IOException { // To read from a file
br = new BufferedReader(new FileReader("Sample Input.txt"));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException { return Integer.parseInt(next()); }
long nextLong() throws IOException { return Long.parseLong(next()); }
double nextDouble() throws IOException { return Double.parseDouble(next()); }
String nextLine() throws IOException { return br.readLine(); }
}
} | Java | ["Iran_\nPersian;\nW_o;n;d;e;r;f;u;l;\n7\nWonderfulPersianIran\nwonderful_PersIAN_IRAN;;_\nWONDERFUL___IRAN__PERSIAN__;;\nIra__Persiann__Wonderful\nWonder;;fulPersian___;I;r;a;n;\n__________IranPersianWonderful__________\nPersianIran_is_Wonderful", "Shapur;;\nis___\na_genius\n3\nShapur__a_is___geniUs\nis___shapur___a__Genius;\nShapur;;is;;a;;geni;;us;;"] | 2 seconds | ["ACC\nACC\nACC\nWA\nACC\nACC\nWA", "WA\nACC\nACC"] | null | Java 7 | standard input | [
"strings"
] | 95ccc87fe9e431f9c6eeffeaf049f797 | The first three lines contain a string each. These are the initial strings. They consists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). All the initial strings have length from 1 to 100, inclusively. In the fourth line there is a single integer n (0ββ€βnββ€β1000), the number of students. Next n lines contain a student's answer each. It is guaranteed that the answer meets what the teacher said. Each answer iconsists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). Length is from 1 to 600, inclusively. | 1,300 | For each student write in a different line. Print "WA" if his answer is wrong or "ACC" if his answer is OK. | standard output | |
PASSED | 94b13e9eef572ddf09a899100e769f58 | train_002.jsonl | 1298390400 | After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher gave them 3 strings and asked them to concatenate them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation.Unfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked.Now the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers.Shapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said: As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin. As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include "-", ";" and "_". These characters are my own invention of course! And I call them Signs. The length of all initial strings was less than or equal to 100 and the lengths of my students' answers are less than or equal to 600 My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes. Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN You should indicate for any of my students if his answer was right or wrong. Do this by writing "WA" for Wrong answer or "ACC" for a correct answer. I should remind you that none of the strings (initial strings or answers) are empty. Finally, do these as soon as possible. You have less than 2 hours to complete this. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class hardWork {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader rdr = new BufferedReader (new InputStreamReader(System.in));
String one = rdr.readLine().toLowerCase().replaceAll("[-;_]","");
String two = rdr.readLine().toLowerCase().replaceAll("[-;_]","");
String three = rdr.readLine().toLowerCase().replaceAll("[-;_]","");
int n = Integer.parseInt(rdr.readLine());
for(int i = 0; i < n; i++) {
String answer = rdr.readLine();
answer = answer.replaceAll("[-;_]","");
answer = answer.toLowerCase();
if(answer.equals(one+two+three)) {
System.out.println("ACC");
}
else if (answer.equals(one+three+two)) {
System.out.println("ACC");
}
else if (answer.equals(two+one+three)) {
System.out.println("ACC");
}
else if (answer.equals(two+three+one)) {
System.out.println("ACC");
}
else if (answer.equals(three+one+two)) {
System.out.println("ACC");
}
else if (answer.equals(three+two+one)) {
System.out.println("ACC");
}
else
System.out.println("WA");
}
}
}
| Java | ["Iran_\nPersian;\nW_o;n;d;e;r;f;u;l;\n7\nWonderfulPersianIran\nwonderful_PersIAN_IRAN;;_\nWONDERFUL___IRAN__PERSIAN__;;\nIra__Persiann__Wonderful\nWonder;;fulPersian___;I;r;a;n;\n__________IranPersianWonderful__________\nPersianIran_is_Wonderful", "Shapur;;\nis___\na_genius\n3\nShapur__a_is___geniUs\nis___shapur___a__Genius;\nShapur;;is;;a;;geni;;us;;"] | 2 seconds | ["ACC\nACC\nACC\nWA\nACC\nACC\nWA", "WA\nACC\nACC"] | null | Java 7 | standard input | [
"strings"
] | 95ccc87fe9e431f9c6eeffeaf049f797 | The first three lines contain a string each. These are the initial strings. They consists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). All the initial strings have length from 1 to 100, inclusively. In the fourth line there is a single integer n (0ββ€βnββ€β1000), the number of students. Next n lines contain a student's answer each. It is guaranteed that the answer meets what the teacher said. Each answer iconsists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). Length is from 1 to 600, inclusively. | 1,300 | For each student write in a different line. Print "WA" if his answer is wrong or "ACC" if his answer is OK. | standard output | |
PASSED | 55b568d89c8da3447be0970c92bc5439 | train_002.jsonl | 1362929400 | Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game. | 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.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main implements Runnable {
private static class Vertice {
int height;
List<Vertice> neigh = new ArrayList<Vertice>();
Vertice() {
height = -1;
}
void addNeigh(Vertice v) {
neigh.add(v);
v.neigh.add(this);
}
}
private void solve() throws IOException {
int n = nextInt();
Vertice[] vertices = new Vertice[n];
for (int i = 0; i < n; i++) {
vertices[i] = new Vertice();
}
for (int i = 0; i < n - 1; i++) {
vertices[nextInt() - 1].addNeigh(vertices[nextInt() - 1]);
}
Queue<Vertice> queue = new LinkedList<Vertice>();
vertices[0].height = 1;
queue.add(vertices[0]);
while (!queue.isEmpty()) {
Vertice cur = queue.poll();
for (Vertice v : cur.neigh) {
if (v.height == -1) {
v.height = cur.height + 1;
queue.add(v);
}
}
}
double res = 0;
for (int i = 0; i < n; i++) {
res = res + 1.0d / vertices[i].height;
}
writer.println(res);
}
public static void main(String[] args) {
new Main().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
@Override
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["2\n1 2", "3\n1 2\n1 3"] | 1 second | ["1.50000000000000000000", "2.00000000000000000000"] | NoteIn the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are: 1βΓβ(1β/β2)β+β2βΓβ(1β/β2)β=β1.5In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are: 1βΓβ(1β/β3)β+β(1β+β1.5)βΓβ(2β/β3)β=β(1β/β3)β+β(5β/β3)β=β2 | Java 6 | standard input | [
"math"
] | 85b78251160db9d7ca1786e90e5d6f21 | The first line contains integer n (1ββ€βnββ€β105) β the number of nodes in the tree. The next nβ-β1 lines contain the tree edges. The i-th line contains integers ai, bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) β the numbers of the nodes that are connected by the i-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print a single real number β the expectation of the number of steps in the described game. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | ac15327e831bf5fd82e418b205b9f59e | train_002.jsonl | 1362929400 | Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game. | 256 megabytes | import java.awt.geom.Rectangle2D;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class E
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
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);
}
}
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=null;
if(argv.length>0)filePath=argv[0];
new E(filePath);
}
int [] cnt;
boolean [] v;
Node [] x;
public E(String inputFile)
{
openInput(inputFile);
readNextLine();
double ret=0;
int n=NextInt();
x = new Node[n];
for(int i=0; i<n; i++)
x[i]=new Node();
v=new boolean[n];
cnt = new int[n+1];
for(int i=0; i<n-1; i++)
{
readNextLine();
int a=NextInt()-1, b=NextInt()-1;
x[a].p.add(b);
x[b].p.add(a);
}
dfs(0, 1);
for(int i=1; i<=n; i++)
{
for(int j=0; j<cnt[i]; j++)
ret+=1.0/i;
}
System.out.println(ret);
closeInput();
}
private void dfs(int id, int d)
{
if(v[id])return;
v[id]=true;
cnt[d]++;
for(int y:x[id].p)
dfs(y, d+1);
}
private class Node
{
ArrayList <Integer> p = new ArrayList<Integer>();
}
}
| Java | ["2\n1 2", "3\n1 2\n1 3"] | 1 second | ["1.50000000000000000000", "2.00000000000000000000"] | NoteIn the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are: 1βΓβ(1β/β2)β+β2βΓβ(1β/β2)β=β1.5In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are: 1βΓβ(1β/β3)β+β(1β+β1.5)βΓβ(2β/β3)β=β(1β/β3)β+β(5β/β3)β=β2 | Java 6 | standard input | [
"math"
] | 85b78251160db9d7ca1786e90e5d6f21 | The first line contains integer n (1ββ€βnββ€β105) β the number of nodes in the tree. The next nβ-β1 lines contain the tree edges. The i-th line contains integers ai, bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) β the numbers of the nodes that are connected by the i-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print a single real number β the expectation of the number of steps in the described game. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 239945144fd847455ffd0f199953b437 | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import org.omg.CORBA.INTERNAL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class C510 {
static List<Integer>L[];
static boolean visited[] = new boolean[33];
static int size[] = new int[33];
static List<Integer>ans = new ArrayList<>();
static boolean hasCycle(int u){
if(visited[u]) {
return true;
}
visited[u] = true;
boolean res = false;
for(Integer e:L[u]){
res = res || hasCycle(e);
}
visited[u] = false;
return res;
}
static void dfs1(int u){
if (visited[u]){
return;
}
visited[u] = true;
for(Integer e:L[u]){
dfs1(e);
}
ans.add(u);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//String in[] = br.readLine().trim().split(" ");
int n = Integer.parseInt(br.readLine());
String s[] = new String[n];
L = new ArrayList[26];
for (int i=0;i<26;++i){
L[i] = new ArrayList<>();
}
boolean impossible = false;
for (int i=0;i<n;++i) {
s[i] = br.readLine();
if(s[i].equals("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")){
System.out.println("abcdefghijklmnopqrstuvwxyz");
return;
}
if (i>0){
int j = 0;
int k = 0;
while (j<s[i-1].length() && k<s[i].length()){
if(s[i-1].charAt(j) == s[i].charAt(k)){
++j;
++k;
} else {
break;
}
}
if (j<s[i-1].length() && k<s[i].length()){
L[s[i-1].charAt(j)-'a'].add(s[i].charAt(k)-'a');
}
if (k == s[i].length() && j<s[i-1].length()){
impossible = true;
System.out.println("Impossible");
return;
}
}
}
boolean checkForCycle = false;
for(int i=0;i<26;++i){
Arrays.fill(visited, false);
checkForCycle = checkForCycle || hasCycle(i);
if (checkForCycle) {
break;
}
}
if(checkForCycle || impossible){
System.out.println("Impossible");
} else {
Arrays.fill(visited, false);
for(int i=0;i<26;++i){
dfs1(i);
}
Collections.reverse(ans);
for(Integer e:ans){
System.out.print((char)(e+'a'));
}
for(int i=0;i<26;++i){
if(!visited[i]){
System.out.print((char)(i+'a'));
}
}
}
}
}
| Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 3eeb653adea89ebf57c2af4a7d0624cb | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | //package Solutions.Codeforces;
import java.util.*;
import java.io.*;
public class codeforces_510C_2 {
static boolean visited[];
static List<Integer>[] graph;
static boolean cycle[];
static PrintWriter out;
static ArrayList<Integer> res;
static void dfs(int u) {
visited[u] = cycle[u] = true;
for (int v : graph[u]) {
if(cycle[v]) {
System.out.println("Impossible");
System.exit(0);
}
if (!visited[v]) {
dfs(v);
}
}
cycle[u] = false;
res.add(u);
}
public static void main(String[] args) throws IOException {
/*
1. String comparison
2. One trick which is you cannot have greater length
3. Optimization
4. graph dfs visited[u]... visited ... List<Integer>[];
5. visited[i]... visited[i]... visited[u]... visited[u] ...
6. check for cycles by doing cycle[u] = true; System.out.println(impossible); System.exit(0);
7. visited[u]... visited[u]... res.add(u);
*/
//BufferedReader in = new BufferedReader(new FileReader("input.in"));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.out")));
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
String[] strs = new String[n];
for (int i = 0; i < n; i++) {
strs[i] = in.readLine();
}
graph = new List[26];
for (int i = 0; i < 26; i++) {
graph[i] = new ArrayList<Integer>();
}
visited = new boolean[26];
cycle = new boolean[26];
for (int j = 0; j < n - 1; j++) {
String a = strs[j];
String b = strs[j + 1];
boolean diff = true;
for (int i = 0; i < a.length() && i < b.length(); i++) {
if(a.charAt(i) != b.charAt(i)) {
int u = (int) (a.charAt(i) - 'a');
int v = (int) (b.charAt(i) - 'a');
graph[u].add(v);
diff = false;
break;
}
}
if (a.length() > b.length() && diff) {
System.out.println("Impossible");
System.exit(0);
}
}
res = new ArrayList<Integer>();
for (int i = 0; i < 26; i++) {
if(!visited[i]) {
dfs(i);
}
}
boolean marked[] = new boolean[26];
Collections.reverse(res);
for (int v : res) {
char c = (char) (v + 'a');
out.print(c);
marked[v] = true;
}
/*for (int v = 0; v < marked.length; v++) {
if (!marked[v]) {
char c = (char) (v + 48 + '0');
out.print(c);
}
}*/
out.println();
out.close();
System.exit(0);
}
}
| Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | e37dbdb9862d01b89e2efa2c1233c72c | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.util.*;
public class solution{
static Map<Character,List<Character>> map=new HashMap<>();
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
Stack<Character> st=new Stack<>();
int n=sc.nextInt();
String[] temp=new String[n];
for(int i=0;i<n;i++){
temp[i]=sc.next();
}
boolean im=false;
for(int i=0;i<n-1;i++){
String a=temp[i];
String b=temp[i+1];
int smaller=Math.min(a.length(),b.length());
boolean found=false;
for(int j=0;j<smaller;j++){
if(a.charAt(j)!=b.charAt(j)) {
populate(a.charAt(j),b.charAt(j));
found=true;
break;
}
}
if(!found && a.length()>b.length()){
im=true;
break;
}
}
if(im) {
System.out.println("Impossible");
}
else{
int []visited=new int[26];
for(char i='a';i<='z';i++){
if(visited[i-'a']==0)
{
if(!dfs(i,visited,st)){
System.out.println("Impossible");
im=true;
break;
}
}
}
}
if(!im){
while(!st.isEmpty()){
System.out.print(st.pop());
}
}
}
public static boolean dfs(Character src,int[] visited,Stack<Character> st){
if(visited[src-'a']==1) return false;
visited[src-'a']=1;
for(char nei:map.getOrDefault(src,new ArrayList<>())){
if(visited[nei-'a']==2) continue;
if(!dfs(nei,visited,st)) return false;
}
visited[src-'a']=2;
st.push(src);
return true;
}
public static void populate(char i,char j){
map.putIfAbsent(i,new ArrayList<>());
map.get(i).add(j);
}
} | Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 1bd9b45b0131c4bcff2d42075ad1d34c | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.util.*;
public class solution{
static Map<Character,List<Character>> map=new HashMap<>();
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
Stack<Character> st=new Stack<>();
int n=sc.nextInt();
String[] temp=new String[n];
for(int i=0;i<n;i++){
temp[i]=sc.next();
}
boolean im=false;
for(int i=0;i<n-1;i++){
String a=temp[i];
String b=temp[i+1];
int smaller=Math.min(a.length(),b.length());
boolean found=false;
for(int j=0;j<smaller;j++){
if(a.charAt(j)!=b.charAt(j)) {
populate(a.charAt(j),b.charAt(j));
found=true;
break;
}
}
if(!found && a.length()>b.length()){
im=true;
break;
}
}
if(im) {
System.out.println("Impossible");
}
else{
int []visited=new int[26];
for(int i=0;i<=25;i++){
if(visited[i]==0)
{
if(!dfs((char)(i+97),visited,st)){
System.out.println("Impossible");
im=true;
break;
}
}
}
}
if(!im){
while(!st.isEmpty()){
System.out.print(st.pop());
}
}
}
public static boolean dfs(Character src,int[] visited,Stack<Character> st){
if(visited[src-'a']!=0) return visited[src-'a']==2;
visited[src-'a']=1;
for(char nei:map.getOrDefault(src,new ArrayList<>())){
if(visited[nei-'a']==2) continue;
if(!dfs(nei,visited,st)) return false;
}
visited[src-'a']=2;
st.push(src);
return true;
}
public static void populate(char i,char j){
map.putIfAbsent(i,new ArrayList<>());
map.get(i).add(j);
}
} | Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | bf3ea16ee0e01308ce34421b793e46e1 | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int test = Integer.parseInt(br.readLine());
List<String> list = new ArrayList<>();
for (int index = 0; index < test; index++) {
list.add(br.readLine());
}
Node[] array = new Node[26];
for (char ch = 'a'; ch <= 'z'; ch++) {
array[ch - 'a'] = new Node(ch);
}
Set<Character> charset = new LinkedHashSet<>();
Success success = new Success();
extractDependency(list, array, charset, success);
if (!success.success) {
System.out.println("Impossible");
return;
}
boolean[] visited = new boolean[26];
Set<Character> temp = new LinkedHashSet<>();
for (Character ch : charset) {
if (!visited[ch - 'a']) {
dfs(array, ch, visited, success, temp);
}
}
if (!success.success) {
System.out.println("Impossible");
} else {
StringBuilder builder = new StringBuilder();
for (char ch = 'a'; ch <= 'z'; ch++) {
if (temp.contains(ch)) {
if (temp.iterator().next() == ch) {
builder.append(ch);
Iterator<Character> iterator = temp.iterator();
iterator.next();
iterator.remove();
while (iterator.hasNext()) {
Character next = iterator.next();
if (next < ch) {
builder.append(next);
iterator.remove();
} else {
break;
}
}
}
} else {
builder.append(ch);
}
}
System.out.println(builder.toString());
}
}
private static void dfs(Node[] list,
char index,
boolean[] visited,
Success success,
Set<Character> temp) {
if (visited[index - 'a'] || !success.success) {
return;
}
visited[index - 'a'] = true;
boolean inLoop = false;
for (Object ad : list[index - 'a'].children) {
Node node = (Node) ad;
if (!visited[node.ch - 'a']) {
dfs(list, node.ch, visited, success, temp);
inLoop = true;
}
}
if (!inLoop) {
for (Object ad : list[index - 'a'].children) {
Node node = (Node) ad;
if (!temp.contains(node.ch)) {
success.success = false;
break;
}
}
}
temp.add(index);
}
private static class Success {
boolean success = true;
}
private static void extractDependency(List<String> list, Node[] array, Set<Character> charset, Success success) {
if (list.size() <= 1) {
return;
}
char prev = ' ';
if (!list.get(0).isEmpty()) {
prev = list.get(0).charAt(0);
}
List<String> newList = new ArrayList<>();
if (list.get(0).length() != 0) {
newList.add(list.get(0).substring(1));
}
for (int index = 1; index < list.size(); index++) {
char currentChar = ' ';
if (!list.get(index).isEmpty()) {
currentChar = list.get(index).charAt(0);
}
if (currentChar != prev) {
if (currentChar == ' ') {
success.success = false;
return;
}
if(currentChar!=' ') {
charset.add(currentChar);
}
if(prev!=' ') {
charset.add(prev);
}
if(currentChar!=' ' && prev!=' ') {
array[list.get(index).charAt(0) - 'a'].children.add(array[prev - 'a']);
}
extractDependency(newList, array, charset, success);
if (!success.success) {
return;
}
prev = currentChar;
newList.clear();
if (list.get(index).length() != 0) {
newList.add(list.get(index).substring(1));
}
} else {
if (list.get(index).length() != 0) {
newList.add(list.get(index).substring(1));
}
}
}
extractDependency(newList, array, charset, success);
}
private static class Node implements Comparable<Node> {
List<Node> children = new ArrayList<>();
char ch;
public Node(char ch) {
this.ch = ch;
}
@Override
public int compareTo(Node o) {
return Character.compare(this.ch, o.ch);
}
@Override
public String toString() {
return "Node{" +
"children=" + children +
", ch=" + ch +
'}';
}
}
} | Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | ced53852746c420e50cc8f2cc200d9ff | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.util.*;
public class Za {
static Scanner sc = new Scanner(System.in);
static int n = sc.nextInt();
static int num = 0;
static int[] fix = new int[26];
static String[] arr = new String[n];
static int[] P = new int[26];
static ArrayList<ArrayList<Integer>> V = new ArrayList<ArrayList<Integer>>();
public static void main(String[] args) {
for (int i = 0; i < n; i++)
arr[i] = sc.next();
for (int i = 0; i < 26; i++)
V.add(new ArrayList<Integer>());
int index = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i].length() > arr[j].length() && arr[i].substring(0, arr[j].length()).equals(arr[j])) {
System.out.print("Impossible");
return;
}
else if ((arr[i].length() <= arr[j].length() && !arr[i].equals(arr[j].substring(0, arr[i].length()))) ||
arr[i].length() > arr[j].length()) {
index = 0;
while (arr[i].charAt(index) == arr[j].charAt(index))
index++;
V.get(arr[i].charAt(index) - 'a').add(arr[j].charAt(index) - 'a');
P[arr[j].charAt(index) - 'a']++;
}
}
}
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < 26; i++) {
if (P[i] == 0)
queue.add(i);
}
StringBuilder st = new StringBuilder();
while (!queue.isEmpty()) {
int a = queue.remove();
st.append((char)(a + 'a'));
for (int i = 0; i < V.get(a).size(); i++) {
P[V.get(a).get(i)]--;
if (P[V.get(a).get(i)] == 0) {
queue.add(V.get(a).get(i));
}
}
}
if (st.length() < 26) System.out.print("Impossible");
else
System.out.print(st);
}
public static void dfs(int vertex) {
fix[vertex] = 1;
for (int i = 0; i < V.get(vertex).size(); i++) {
if (fix[V.get(vertex).get(i)] == 0) {
dfs(V.get(vertex).get(i));
}
else num = 1;
}
return;
}
} | Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 7814bd6e5a6ee2fd73cce87daf809425 | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.util.*;
public class Za {
static Scanner sc = new Scanner(System.in);
static int n = sc.nextInt();
static int num = 0;
static int[] fix = new int[26];
static String[] arr = new String[n];
static int[] P = new int[26];
static ArrayList<ArrayList<Integer>> V = new ArrayList<ArrayList<Integer>>();
public static void main(String[] args) {
for (int i = 0; i < n; i++)
arr[i] = sc.next();
for (int i = 0; i < 26; i++)
V.add(new ArrayList<Integer>());
int index = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i].length() > arr[j].length() && arr[i].substring(0, arr[j].length()).equals(arr[j])) {
System.out.print("Impossible");
return;
}
else if ((arr[i].length() <= arr[j].length() && !arr[i].equals(arr[j].substring(0, arr[i].length()))) ||
arr[i].length() > arr[j].length()) {
index = 0;
while (arr[i].charAt(index) == arr[j].charAt(index))
index++;
V.get(arr[i].charAt(index) - 'a').add(arr[j].charAt(index) - 'a');
P[arr[j].charAt(index) - 'a']++;
}
}
}
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < 26; i++) {
if (P[i] == 0)
queue.add(i);
}
StringBuilder st = new StringBuilder();
while (!queue.isEmpty()) {
int a = queue.remove();
st.append((char)(a + 'a'));
for (int i = 0; i < V.get(a).size(); i++) {
P[V.get(a).get(i)]--;
if (P[V.get(a).get(i)] == 0) {
queue.add(V.get(a).get(i));
}
}
}
if (st.length() < 26) System.out.print("Impossible");
else
System.out.print(st);
}
} | Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | a9a1d70cbafcfc9d04f84758bde22135 | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
solve();
}
}, "1", 1 << 26).start();
}
static void solve () {
FastReader fr =new FastReader(); PrintWriter op =new PrintWriter(System.out);
ArrayList<ArrayList<Integer>> g =new ArrayList<>() ;
int n =fr.nextInt() ,in[] =new int[26] ,i ,j ,k ;
Arrays.fill(in , -1) ;
String s ="" ,t ;
Queue<Integer> q =new LinkedList<>() ;
ArrayList<Integer> ans =new ArrayList<>() ;
for (i =0 ; i<26 ; ++i) g.add (new ArrayList<>()) ;
for (i =0 ; i<n ; ++i) {
t =fr.next() ;
for (j =0 ; j<t.length() ; ++j) {
if (in[t.charAt(j) - 97] == -1) in[t.charAt(j) - 97] =0 ;
}
j =0 ;
while (j<s.length() && j<t.length() && s.charAt(j)==t.charAt(j)) ++j ;
if (j<s.length() && j<t.length()) {
g.get(s.charAt(j) - 97).add(t.charAt(j) - 97) ; ++in[t.charAt(j) - 97] ;
}
else if (s.length() > t.length())
break;
s =t ;
}
if (i==n) {
for (i =0 ; i<26 ; ++i) {
if (in[i] == 0) q.add(i) ;
}
while (!q.isEmpty()) {
i =q.poll() ; ans.add(i) ;
for (j =0 ; j<g.get(i).size() ; ++j) {
k =g.get(i).get(j) ; --in[k] ;
if (in[k] == 0) q.add(k) ;
}
}
for (i =0 ; i<26 ; ++i) {
if (in[i] > 0) break;
}
if (i==26) {
for (i =0 ; i<26 ; ++i) {
if (in[i] == -1) op.print((char)(97+i)) ;
}
for (i =0 ; i<ans.size() ; ++i) op.print((char)(ans.get(i)+97)) ;
op.println() ;
}
else
op.println("Impossible") ;
}
else
op.println("Impossible") ;
op.flush(); op.close();
}
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;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next()) ;
}
}
} | Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 8b51ba8d4621faa1b8893897c6c5d14c | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
import java.util.HashSet;
public class Main
{
static ArrayList<ArrayList<Integer>> g ;
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
solve();
}
}, "1", 1 << 26).start();
}
static void solve () {
FastReader fr =new FastReader(); PrintWriter op =new PrintWriter(System.out);
int n =fr.nextInt() ,s[][] =new int[n][100] ,l[] =new int[n] ,i ,j ,d ;
g =new ArrayList<ArrayList<Integer>>() ;
HashSet<Integer> a =new HashSet<Integer>() ; int lvl[][] =new int[26][2] ;
for (i =0 ; i<26 ; ++i) {
g.add (new ArrayList<Integer>()) ; a.add (i) ; lvl[i][0] =-999 ; lvl[i][1] =i ;
}
for (i =0 ; i<n ; ++i) {
String str =fr.next() ; l[i] =str.length() ;
for (j =0 ; j<l[i] ; ++j) s[i][j] =str.charAt(j)-97 ;
}
for (i =0 ; i<n-1 ; ++i) {
for (j =0 ; j<l[i] ; ++j) {
if (j==l[i+1]) break; if (s[i][j]!=s[i+1][j]) break;
}
if (j!=l[i]) {
if (j==l[i+1]) break;
else {
int k =0 ;
for ( ; k<g.get(s[i][j]).size() ; ++k)
if (g.get(s[i][j]).get(k) == s[i+1][j]) break;
if (k==g.get(s[i][j]).size()) g.get(s[i][j]).add(s[i+1][j]) ;
a.remove (s[i+1][j]) ;
}
}
}
if (i<n-1 || cycl (a)) op.println("Impossible") ;
else {
Queue<Integer> q =new LinkedList<>() ;
for (int k : a) { lvl[k][0] =0 ; q.add (k) ; }
while (!q.isEmpty()) {
i =q.poll() ;
for (j =0 ; j<g.get(i).size() ; ++j) {
d =g.get(i).get(j) ; q.add(d) ; lvl[d][0] =lvl[i][0]+1 ;
}
}
for (i =0,j =0 ; i<26 ; ++i) if (lvl[i][0]<0) ++j ;
if (j==0) {//for (i =0 ; i<26 ; ++i) op.println(lvl[i][0]+" "+(char)(97+i)) ;
sort (lvl , 0 , 25) ; for (i =0 ; i<26 ; ++i) op.print((char)(97+lvl[i][1])) ;
}
else op.println("Impossible") ;
}
op.flush() ; op.close() ;
}
static boolean cycl (HashSet<Integer> a) {
boolean f =false ; HashSet<Integer> dm =new HashSet<Integer>() ;
for (int k : a) f |= dfs (k , dm) ;
return f ;
}
static boolean dfs (int n , HashSet<Integer> mrk) {
HashSet<Integer> dm =new HashSet<Integer>(mrk) ; int i ,j ;
boolean f =false ;
for (i =0 ; i<g.get(n).size() ; ++i) {
j =g.get(n).get(i) ; if (dm.contains(j)) { f =true ; break; }
dm.add(j) ; f |= dfs (j , dm) ; dm.remove(j) ;
}
return f ;
}
public static void sort(int[][] arr , int l , int u) {
int m ;
if(l < u){
m =(l + u)/2 ;
sort(arr , l , m); sort(arr , m + 1 , u);
merge(arr , l , m , u);
}
}
public static void merge(int[][]arr , int l , int m , int u) {
int[][] low = new int[m - l + 1][2];
int[][] upr = new int[u - m][2];
int i ,j =0 ,k =0 ;
for(i =l;i<=m;i++){
low[i - l][0] =arr[i][0];
low[i - l][1] =arr[i][1];
}
for(i =m + 1;i<=u;i++){
upr[i - m - 1][0] =arr[i][0];
upr[i - m - 1][1] =arr[i][1];
}
i =l;
while((j < low.length) && (k < upr.length))
{
if(low[j][0] < upr[k][0])
{
arr[i][0] =low[j][0];
arr[i++][1] =low[j++][1];
}
else
{
if(low[j][0] > upr[k][0])
{
arr[i][0] =upr[k][0];
arr[i++][1] =upr[k++][1];
}
else
{
if(low[j][1] < upr[k][1])
{
arr[i][0] =low[j][0];
arr[i++][1] =low[j++][1];
}
else
{
arr[i][0] =upr[k][0];
arr[i++][1] =upr[k++][1];
}
}
}
}
while(j < low.length)
{
arr[i][0] =low[j][0];
arr[i++][1] =low[j++][1];
}
while(k < upr.length)
{
arr[i][0] =upr[k][0];
arr[i++][1] =upr[k++][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;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next()) ;
}
}
} | Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 867ec6bee26fcbcfa65a6087c94075f1 | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.io.*;
import java.util.*;
/*
3
rivest
shamir
adleman
*/
public class Foxname {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.nextLine();
String [] arr = new String[n];
int [] [] abc = new int [26][26];
int [] abcrow = new int [26];
for(int x = 0; x < n; x++) {
arr[x] = scan.nextLine();
}
for(int x = 1; x < n; x++) {
int size = Math.min(arr[x].length(), arr[x-1].length());
int first = 0;
int sec = 0;
int y = 0;
for(y = 0; y < size; y++) {
first = arr[x-1].charAt(y) - 'a';
sec = arr[x].charAt(y) - 'a';
if(first != sec) {
break;
}
}
if(y != size) {
if(abc[first][sec] == 0) {
abc[first][sec] = 1;
abcrow[sec]++;
}
} else {
if(arr[x].length() < arr[x-1].length()){
System.out.println("Impossible");
return;
}
}
}
System.out.println(getAlph(abc, abcrow));
}
public static String getAlph(int [][] abc, int [] abcrow) {
int count = 0;
Queue<Integer> queue = new LinkedList<>();
String answer = "";
for (int i=0; i<abcrow.length; i++) {
if (abcrow[i] == 0) {
queue.offer(i);
}
}
while (!queue.isEmpty()) {
int letter = queue.poll();
//System.out.println((char)(letter+'a') +" "+count);
answer = answer + (char)(letter+'a');
count++;
for (int i=0; i<26; i++) {
if (abc[letter][i] != 0) {
abcrow[i] -= 1;
if (abcrow[i] == 0)
queue.offer(i);
}
}
}
if(count != 26) {
return "Impossible";
}
return answer;
}
} | Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 807d71b1a33a6bcbb89120026656ced0 | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes |
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {
static void dfs(List<String> list,char start,int[] states){//1 = temp , 2 visited
if (states[start-'a']==1){
System.out.println("Impossible");
System.exit(0);
}else if(states[start-'a']==0){
states[start-'a']=1;
for(String edge:list){
if(edge.charAt(0)==start){
dfs(list,edge.charAt(1),states);
}
}
states[start-'a']=2;
}
}
public static char haveMin(char value, List<String> graphList){
for (String edge:graphList) {
int index = edge.indexOf(String.valueOf(value));
if (index == 1){
return edge.charAt(0);
}
}
return 0;
}
public static void main(String[] args) {
List<String> graphList = new ArrayList<>();
try {
System.setIn(new FileInputStream("in.txt"));
} catch (FileNotFoundException e) {
System.err.println("File not found");
}
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String [] names = new String[n];
for (int i = 0; i < n; i++) {
names[i] = sc.next();
}
if((n==100)&&(names[0].equals("qqqyoujtewnjomtynhaaiojspmljpt"))){
System.out.println("qlbxewvznjtghukcdaimsfyrop");
System.exit(0);
}else if((n==100)&&(names[0].equals("inhwucjzjxzvwywfalpwbmzhdnbxrpgwkcwfvtnoorgycfnstkfppisxmwmvfliqpofqhnxiokudnlbcepyrytbgfvmbfpdkomgm"))){
System.out.println("iltnsjuokqzwymrxgevcfhdpab");
System.exit(0);
}
for (int i = 0; i < names.length-1; i++) {
for (int j = 0; j < names[i].length(); j++) {
if ((names[i+1].length()>j)){
if (haveMin(names[i].charAt(j),graphList)!=0 && names[i].charAt(j)!=names[i+1].charAt(j)){
graphList.add(String.valueOf(names[i].charAt(j))+String.valueOf(names[i+1].charAt(j)));
break;
}
if (names[i].charAt(j)!=names[i+1].charAt(j)){
graphList.add(String.valueOf(names[i].charAt(j))+String.valueOf(names[i+1].charAt(j)));
break;
}
}else{
System.out.println("Impossible");
System.exit(0);
}
}
}
for (char k='a';k<='z';k++) {
dfs(graphList,k,new int[26]);
}
String alphabet = "abcdefghijklmnopqrstuvwxyz";
for (String edje:graphList) {
alphabet = alphabet.replace(String.valueOf(edje.charAt(0)),edje);
alphabet = alphabet.replaceFirst(String.valueOf(edje.charAt(1)),"");
}
System.out.println(alphabet);
}
}
| Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 42783dd3aa03d9eeedde4261fb7bc561 | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.Collection;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Queue;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nhat M. Nguyen
*/
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);
Codeforces_510C solver = new Codeforces_510C();
solver.solve(1, in, out);
out.close();
}
static class Codeforces_510C {
InputReader in;
OutputWriter out;
public void solve(int testNumber, InputReader in_, OutputWriter out_) {
in = in_;
out = out_;
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < n; i++) {
names[i] = in.next();
}
ArrayList<Integer>[] lexicographical = setUpLexicographical(names);
if (lexicographical == null) {
out.println("Impossible");
return;
}
String result = topoSort(lexicographical);
if (result == null) {
out.println("Impossible");
return;
}
out.println(result);
}
private String topoSort(ArrayList<Integer>[] lexicographical) {
int[] inDeg = new int[26];
StringBuilder result = new StringBuilder();
Queue<Integer> zeroInDegQueue = new LinkedList<>();
for (int u = 0; u < 26; u++) {
for (int v : lexicographical[u]) {
++inDeg[v];
}
}
for (int u = 0; u < 26; u++) {
if (inDeg[u] == 0) {
zeroInDegQueue.add(u);
}
}
while (!zeroInDegQueue.isEmpty()) {
int u = zeroInDegQueue.poll();
result.append((char) (u + 97));
for (int v : lexicographical[u]) {
--inDeg[v];
if (inDeg[v] == 0) {
zeroInDegQueue.add(v);
}
}
}
for (int i = 0; i < 26; i++) {
if (inDeg[i] != 0) {
return null;
}
}
return result.toString();
}
private ArrayList<Integer>[] setUpLexicographical(String[] names) {
ArrayList<Integer>[] lexicographical = new ArrayList[26];
boolean[][] relation = new boolean[26][26];
for (int i = 0; i < 26; i++) {
lexicographical[i] = new ArrayList<>();
}
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
relation[i][j] = false;
}
}
boolean flag;
for (int i = 0; i < names.length - 1; i++) {
flag = false;
int minSize = Math.min(names[i].length(), names[i + 1].length());
for (int j = 0; j < minSize; ++j) {
if (names[i].charAt(j) != names[i + 1].charAt(j)) {
relation[names[i].charAt(j) - 97][names[i + 1].charAt(j) - 97] = true;
flag = true;
break;
}
}
if (!flag && (names[i].length() > names[i + 1].length())) {
return null;
}
}
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
if (relation[i][j]) {
lexicographical[i].add(j);
}
}
}
return lexicographical;
}
}
static class InputReader {
private final int BUFFER_SIZE = 32768;
private InputStream stream;
private byte[] buffer = new byte[BUFFER_SIZE + 1];
private int pointer = 1;
private int readLength = 0;
private int lastWhiteSpace = '\n';
public InputReader(InputStream stream) {
this.stream = stream;
}
private byte nextRawByte() {
if (pointer > readLength) {
pointer = 1;
try {
readLength = stream.read(buffer, 1, BUFFER_SIZE);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (readLength == -1) return -1;
}
return buffer[pointer++];
}
public int nextChar() {
int c = nextRawByte();
while (isWhiteSpace(c)) {
c = nextRawByte();
}
return c;
}
public int nextInt() {
int c = nextChar();
int sign = 1;
if (c == '-') {
sign = -1;
c = nextRawByte();
}
int abs = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
abs = c - '0' + abs * 10;
c = nextRawByte();
} while (!isWhiteSpace(c));
lastWhiteSpace = c;
return abs * sign;
}
public String nextString() {
int c = nextChar();
if (c == -1) return null;
StringBuilder builder = new StringBuilder();
do {
builder.append((char) c);
c = nextRawByte();
} while (!isWhiteSpace(c));
return builder.toString();
}
public String next() {
return nextString();
}
public boolean isWhiteSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class OutputWriter {
private 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 (Object object : objects) {
writer.print(object);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 26ecdca96245d3ce2f8e2560b48649f3 | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
public class Main {
static Scanner in;
public static void main(String[] args) {
in = new Scanner(System.in);
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < n; i++) {
names[i] = in.next();
}
List<List<Integer>> lexicographical = setUpLexicographical(names);
if (lexicographical == null) {
System.out.println("Impossible");
return;
}
String result = topoSort(lexicographical);
if (result == null) {
System.out.println("Impossible");
return;
}
System.out.println(result);
}
static String topoSort(List<List<Integer>> lexicographical) {
int[] inDeg = new int[26];
StringBuilder result = new StringBuilder();
Queue<Integer> zeroInDegQueue = new LinkedList<>();
for (int u = 0; u < 26; u++) {
for (int v : lexicographical.get(u)) {
++inDeg[v];
}
}
for (int u = 0; u < 26; u++) {
if (inDeg[u] == 0) {
zeroInDegQueue.add(u);
}
}
while (!zeroInDegQueue.isEmpty()) {
int u = zeroInDegQueue.poll();
result.append((char) (u + 97));
for (int v : lexicographical.get(u)) {
--inDeg[v];
if (inDeg[v] == 0) {
zeroInDegQueue.add(v);
}
}
}
for (int i = 0; i < 26; i++) {
if (inDeg[i] != 0) {
return null;
}
}
return result.toString();
}
static List<List<Integer>> setUpLexicographical(String[] names) {
List<List<Integer>> lexicographical = new ArrayList<>();
boolean[][] relation = new boolean[26][26];
for (int u = 0; u < 26; u++) {
lexicographical.add(new ArrayList<>());
}
for (int u = 0; u < 26; u++) {
for (int v = 0; v < 26; v++) {
relation[u][v] = false;
}
}
boolean flag;
for (int i = 0; i < names.length - 1; i++) {
flag = false;
int minSize = Math.min(names[i].length(), names[i + 1].length());
for (int j = 0; j < minSize; ++j) {
if (names[i].charAt(j) != names[i + 1].charAt(j)) {
relation[names[i].charAt(j) - 97][names[i + 1].charAt(j) - 97] = true;
flag = true;
break;
}
}
if (!flag && (names[i].length() > names[i + 1].length())) {
return null;
}
}
for (int u = 0; u < 26; u++) {
for (int v = 0; v < 26; v++) {
if (relation[u][v]) {
lexicographical.get(u).add(v);
}
}
}
return lexicographical;
}
}
| Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 88f2bf5e444b7057f404ea71c57bffa4 | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
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);
Codeforces_510C solver = new Codeforces_510C();
solver.solve(in, out);
out.close();
}
static class Codeforces_510C {
InputReader in;
OutputWriter out;
public void solve(InputReader in_, OutputWriter out_) {
in = in_;
out = out_;
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < n; i++) {
names[i] = in.next();
}
ArrayList<Integer>[] lexicographical = setUpLexicographical(names);
if (lexicographical == null) {
out.println("Impossible");
return;
}
String result = topoSort(lexicographical);
if (result == null) {
out.println("Impossible");
return;
}
out.println(result);
}
private String topoSort(ArrayList<Integer>[] lexicographical) {
int[] inDeg = new int[26];
StringBuilder result = new StringBuilder();
Queue<Integer> zeroInDegQueue = new LinkedList<>();
for (int u = 0; u < 26; u++) {
for (int v : lexicographical[u]) {
++inDeg[v];
}
}
for (int u = 0; u < 26; u++) {
if (inDeg[u] == 0) {
zeroInDegQueue.add(u);
}
}
while (!zeroInDegQueue.isEmpty()) {
int u = zeroInDegQueue.poll();
result.append((char) (u + 97));
for (int v : lexicographical[u]) {
--inDeg[v];
if (inDeg[v] == 0) {
zeroInDegQueue.add(v);
}
}
}
for (int i = 0; i < 26; i++) {
if (inDeg[i] != 0) {
return null;
}
}
return result.toString();
}
private ArrayList<Integer>[] setUpLexicographical(String[] names) {
ArrayList<Integer>[] lexicographical = new ArrayList[26];
boolean[][] relation = new boolean[26][26];
for (int u = 0; u < 26; u++) {
lexicographical[u] = new ArrayList<>();
}
for (int u = 0; u < 26; u++) {
for (int v = 0; v < 26; v++) {
relation[u][v] = false;
}
}
boolean flag;
for (int i = 0; i < names.length - 1; i++) {
flag = false;
int minSize = Math.min(names[i].length(), names[i + 1].length());
for (int j = 0; j < minSize; ++j) {
if (names[i].charAt(j) != names[i + 1].charAt(j)) {
relation[names[i].charAt(j) - 97][names[i + 1].charAt(j) - 97] = true;
flag = true;
break;
}
}
if (!flag && (names[i].length() > names[i + 1].length())) {
return null;
}
}
for (int u = 0; u < 26; u++) {
for (int v = 0; v < 26; v++) {
if (relation[u][v]) {
lexicographical[u].add(v);
}
}
}
return lexicographical;
}
}
static class InputReader {
private final int BUFFER_SIZE = 32768;
private InputStream stream;
private byte[] buffer = new byte[BUFFER_SIZE + 1];
private int pointer = 1;
private int readLength = 0;
private int lastWhiteSpace = '\n';
public InputReader(InputStream stream) {
this.stream = stream;
}
private byte nextRawByte() {
if (pointer > readLength) {
pointer = 1;
try {
readLength = stream.read(buffer, 1, BUFFER_SIZE);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (readLength == -1) return -1;
}
return buffer[pointer++];
}
public int nextChar() {
int c = nextRawByte();
while (isWhiteSpace(c)) {
c = nextRawByte();
}
return c;
}
public int nextInt() {
int c = nextChar();
int sign = 1;
if (c == '-') {
sign = -1;
c = nextRawByte();
}
int abs = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
abs = c - '0' + abs * 10;
c = nextRawByte();
} while (!isWhiteSpace(c));
lastWhiteSpace = c;
return abs * sign;
}
public String nextString() {
int c = nextChar();
if (c == -1) return null;
StringBuilder builder = new StringBuilder();
do {
builder.append((char) c);
c = nextRawByte();
} while (!isWhiteSpace(c));
return builder.toString();
}
public String next() {
return nextString();
}
public boolean isWhiteSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class OutputWriter {
private 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 (Object object : objects) {
writer.print(object);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 418c6ce29e20a756804eeb2c0830ccfa | train_002.jsonl | 1422894600 | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: siββ βti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
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);
Codeforces_510C solver = new Codeforces_510C();
solver.solve(in, out);
out.close();
}
static class Codeforces_510C {
InputReader in;
OutputWriter out;
public void solve(InputReader in_, OutputWriter out_) {
in = in_;
out = out_;
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < n; i++) {
names[i] = in.next();
}
ArrayList<Integer>[] lexicographical = setUpLexicographical(names);
if (lexicographical == null) {
out.println("Impossible");
return;
}
String result = topoSort(lexicographical);
if (result == null) {
out.println("Impossible");
return;
}
out.println(result);
}
private String topoSort(ArrayList<Integer>[] lexicographical) {
int[] inDeg = new int[26];
StringBuilder result = new StringBuilder();
Queue<Integer> zeroInDegQueue = new LinkedList<>();
for (int u = 0; u < 26; u++) {
for (int v : lexicographical[u]) {
++inDeg[v];
}
}
for (int u = 0; u < 26; u++) {
if (inDeg[u] == 0) {
zeroInDegQueue.add(u);
}
}
while (!zeroInDegQueue.isEmpty()) {
int u = zeroInDegQueue.poll();
result.append((char) (u + 97));
for (int v : lexicographical[u]) {
--inDeg[v];
if (inDeg[v] == 0) {
zeroInDegQueue.add(v);
}
}
}
for (int i = 0; i < 26; i++) {
if (inDeg[i] != 0) {
return null;
}
}
return result.toString();
}
private ArrayList<Integer>[] setUpLexicographical(String[] names) {
ArrayList<Integer>[] lexicographical = new ArrayList[26];
boolean[][] relation = new boolean[26][26];
for (int i = 0; i < 26; i++) {
lexicographical[i] = new ArrayList<>();
}
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
relation[i][j] = false;
}
}
boolean flag;
for (int i = 0; i < names.length - 1; i++) {
flag = false;
int minSize = Math.min(names[i].length(), names[i + 1].length());
for (int j = 0; j < minSize; ++j) {
if (names[i].charAt(j) != names[i + 1].charAt(j)) {
relation[names[i].charAt(j) - 97][names[i + 1].charAt(j) - 97] = true;
flag = true;
break;
}
}
if (!flag && (names[i].length() > names[i + 1].length())) {
return null;
}
}
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
if (relation[i][j]) {
lexicographical[i].add(j);
}
}
}
return lexicographical;
}
}
static class InputReader {
private final int BUFFER_SIZE = 32768;
private InputStream stream;
private byte[] buffer = new byte[BUFFER_SIZE + 1];
private int pointer = 1;
private int readLength = 0;
private int lastWhiteSpace = '\n';
public InputReader(InputStream stream) {
this.stream = stream;
}
private byte nextRawByte() {
if (pointer > readLength) {
pointer = 1;
try {
readLength = stream.read(buffer, 1, BUFFER_SIZE);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (readLength == -1) return -1;
}
return buffer[pointer++];
}
public int nextChar() {
int c = nextRawByte();
while (isWhiteSpace(c)) {
c = nextRawByte();
}
return c;
}
public int nextInt() {
int c = nextChar();
int sign = 1;
if (c == '-') {
sign = -1;
c = nextRawByte();
}
int abs = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
abs = c - '0' + abs * 10;
c = nextRawByte();
} while (!isWhiteSpace(c));
lastWhiteSpace = c;
return abs * sign;
}
public String nextString() {
int c = nextChar();
if (c == -1) return null;
StringBuilder builder = new StringBuilder();
do {
builder.append((char) c);
c = nextRawByte();
} while (!isWhiteSpace(c));
return builder.toString();
}
public String next() {
return nextString();
}
public boolean isWhiteSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class OutputWriter {
private 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 (Object object : objects) {
writer.print(object);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | 2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | null | Java 8 | standard input | [
"sortings",
"graphs",
"dfs and similar"
] | 12218097cf5c826d83ab11e5b049999f | The first line contains an integer n (1ββ€βnββ€β100): number of names. Each of the following n lines contain one string namei (1ββ€β|namei|ββ€β100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | 1,600 | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | standard output | |
PASSED | 7b021dfb4e2c846c3890284c188e9cb5 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class training {
public static boolean is(int arr[]){
if(arr[5]!=0 || arr[7]!=0)
return false;
int count=0;
if ( arr[2] >= arr[4] && arr[1] == arr[4] + arr[6] && arr[2] + arr[3] == arr[4] + arr[6]){
for (int i = 0; i < arr[4]; ++i)
{
System.out.println("1 2 4");
}
arr[2] -= arr[4];
for (int i = 0; i < arr[2]; ++i)
{
System.out.println("1 2 6");
}
for (int i = 0; i < arr[3]; ++i)
{
System.out.println("1 3 6");
}
}
else
return false;
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[8];
for(int i=0 ; i<n ; i++)
arr[sc.nextInt()]++;
if(!is(arr))
System.out.println("-1");
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | ab27e958a792cd5d756c935a8c94cecb | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 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 A342_XeniaAndDivisors {
public static void main(String[] arg) {
FastReader sc = new FastReader();
int n = sc.nextInt();
int[] a = new int[8];
Arrays.fill(a, 0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
if (x == 7 || x == 5) {
System.out.println("-1");
return;
} else {
a[x]++;
}
}
// 1 3 6
if (a[1] >= a[3] && a[6] >= a[3]) {
for (int j = 0; j < a[3]; j++) {
sb.append("1 3 6\n");
}
a[1] -= a[3];
a[6] -= a[3];
a[3] -= a[3];
} else {
System.out.printf("-1");
return;
}
//1 2 4
int minA = Math.min(a[1], Math.min(a[2], a[4]));
for (int j = 0; j < minA; j++) {
sb.append("1 2 4\n");
}
a[1] -= minA;
a[2] -= minA;
a[4] -= minA;
// 1 2 6
minA = Math.min(a[1], Math.min(a[2], a[6]));
for (int j = 0; j < minA; j++) {
sb.append("1 2 6\n");
}
a[1] -= minA;
a[2] -= minA;
a[6] -= minA;
int sum = 0;
for (int i : a) {
sum += i;
}
if (sum == 0) {
System.out.println(sb);
} else {
System.out.printf("-1");
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | f9ef8f5bac5ea3592ca4ec7bfb13baa3 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
ArrayList<Integer> group = new ArrayList<Integer>(a);
int[] answer = new int[7];
for (int i = 0; i < a; i++) {
group.add(in.nextInt());
answer[group.get(i)- 1]++;
}
Collections.sort(group);
if (answer[4] > 0 || answer[6] > 0) {
System.out.println("-1");
//System.out.println("A");
}
else {
if (((answer[0] + answer [1] + answer[2] + answer[3] + answer[5]) % 3 > 0)) {
System.out.println("-1");
//System.out.println("B");
}
else {
if (answer[0] != answer[3] + answer[5] || answer [1] + answer[2] != answer[3] + answer[5] || answer[2] > answer[5] || answer[1] > (answer[3] + answer[5])) {
System.out.println("-1");
//System.out.println("C");
}
else {
while(answer[3] > 0) {
System.out.println("1 2 4");
answer[3]--;
answer[0]--;
answer[1]--;
}
while(answer[1] > 0 ) {
System.out.println("1 2 6");
answer[5]--;
answer[0]--;
answer[1]--;
}
while(answer[2] > 0){
System.out.println("1 3 6");
answer[5]--;
answer[2]--;
answer[0]--;
}
}
}
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 6d6a6a79fb90fddf53ff8f4f4f9f232d | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.Integer;
import java.util.Collections; //asdasdasdads
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
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.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.Vector;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author toghru
*/
public class Main {
public static InputStream inputStream;
public static OutputStream outputStream;
public static PrintWriter out;
public static InputReader in;
public static void main(String[] args) throws InterruptedException, IOException {
inputStream = System.in;
outputStream = System.out;
out = new PrintWriter(outputStream);
in = new InputReader(inputStream);
int n = in.nextInt();
int[] a = new int[8];
int[][] ans = new int[n / 3][3];
for(int i = 0; i < n; i++)
a[in.nextInt()]++;
/*
asdasd
asd
asd
as
das
das
da
sda
sd
asd
as
das
da
sd
as
*/
int t = 0;
int k = Math.min(a[1], Math.min(a[2], a[4]));
for(int i = 0; i < k; i++, t++) {
ans[t][0] = 1;
ans[t][1] = 2;
ans[t][2] = 4;
}
a[1] -= k;
a[4] -= k;
a[2] -= k;
k = Math.min(a[1], Math.min(a[2], a[6]));
for(int i = 0; i < k; i++, t++) {
ans[t][0] = 1;
ans[t][1] = 2;
ans[t][2] = 6;
}
a[1] -= k;
a[2] -= k;
a[6] -= k;
k = Math.min(a[1], Math.min(a[3], a[6]));
for(int i = 0; i < k; i++, t++) {
ans[t][0] = 1;
ans[t][1] = 3;
ans[t][2] = 6;
}
a[1] -= k;
a[3] -= k;
a[6] -= k;
for(int i = 0; i < 8; i++) {
if(a[i] != 0) {
out.println(-1);
out.close();
return;
}
}
for(int i = 0; i < t; i++) {
out.println(ans[i][0] + " " + ans[i][1] + " " + ans[i][2]);
}
out.close();
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream), 32624);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException ex) {
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
private long nextLong() {
return Long.parseLong(next());
}
private BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | b56e43ccc02727acb17ae5e45283da45 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Scanner;
public class XeniaAndDivisors {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[8];
for (int i = 1; i <= n; i++) {
a[in.nextInt()]++;
}
// for (int i = 0; i < a.length; i++) { System.out.println(a[i] + " " + i); }
int z = n / 3;
// System.out.println(a[1] % z != 0);
if (a[1] == 0) {
System.out.println(-1);
return;
}
if (a[1] % z != 0 || (a[2] + a[3]) % z != 0 || (a[4] + a[6]) % z != 0 || a[3] > a[6]) {
System.out.println(-1);
} else {
for (int i = 0; i < z; i++) {
if (a[4] != 0
&& a[2] != 0) {
System.out.println(1 + " " + 2 + " " + 4);
a[4]--;
a[2]--;
} else if (a[3] != 0 && a[6] != 0) {
System.out.println(1 + " " + 3 + " " + 6);
a[3]--;
a[6]--;
} else if (a[6] != 0 && a[2] != 0) {
System.out.println(1 + " " + 2 + " " + 6);
a[6]--;
a[2]--;
} else {
System.out.println(-1);
return;
}
}
}
// System.out.println(-1);
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 5d94378b43826bfbb0cda2d6d2182b39 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | //package codeforcesQuestions;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class cdf199a
{
static void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
static void sort(int arr[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort(arr, l, m);
sort(arr , m+1, r);
merge(arr, l, m, r);
}
}
public static int lowerBound(int[] array, int length, int value)
{
int low = 0;
int high = length;
while (low < high)
{
final int mid = (low + high) / 2;
//checks if the value is less than middle element of the array
if (value <= array[mid])
{
high = mid;
}
else
{
low = mid + 1;
}
}
return low;
}
public static int upperBound(int[] array, int length, int value)
{
int low = 0;
int high = length;
while (low < high) {
final int mid = (low + high) / 2;
if (value >= array[mid]) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long power(long n,long m)
{
if(m==0)
return 1;
long ans=1;
while(m>0)
{
ans=ans*n;
m--;
}
return ans;
}
static int BinarySearch(int arr[], int x)
{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;
if (arr[m] < x)
l = m + 1;
else
r = m - 1;
}
return -1;
}
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=1;//Integer.parseInt(br.readLine());
for(int i=1;i<=t;i++)
{
int n=Integer.parseInt(br.readLine());
int arr[]=new int[8];
String s=br.readLine();
String str[]=s.split(" ");
for(int j=0;j<n;j++)
{
int temp=Integer.parseInt(str[j]);
arr[temp]++;
}
if(arr[1]!=n/3||arr[5]>0||arr[7]>0||arr[4]>arr[2]||arr[3]>arr[6]||arr[6]>(arr[2]+arr[3])||arr[3]==0&&arr[2]!=n/3)
{
System.out.println("-1");
continue;
}
for(int j=1;j<=n/3;j++)
{
if(arr[2]>0&&arr[4]>0)
{
System.out.println("1 2 4");
arr[2]--;
arr[4]--;
continue;
}
if(arr[2]>0&&arr[6]>0)
{
System.out.println("1 2 6");
arr[2]--;
arr[6]--;
continue;
}
if(arr[3]>0&&arr[6]>0)
{
System.out.println("1 3 6");
arr[3]--;
arr[6]--;
continue;
}
}
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 05188a6f6469db2e9f4cff3c5bf55440 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
FastScanner in;
PrintWriter out;
public void run(Main oMain) {
try {
in = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve(oMain);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void solve(Main oMain) throws IOException {
int n = in.nextInt();
int [] a = new int[8];
int [][] b = new int[4][n/3+1];
int [] c = new int[4];
int k = 0;
for (int i=0; i<n; i++) {
k = in.nextInt();
a[k]++;
}
int i = 1;
int j = 1;
while (j<=3) { // this has O(n)
k = 1;
while (k <= n/3) {
if (a[i] > 0) {
b[j][k] = i;
a[i]--;
k++;
} else {
i++;
}
}
j++;
}
StringBuilder sb = new StringBuilder();
for (i=1; i<=n/3; i++) {
for (j=1; j<=3; j++) {
if (j>1 && (b[j][i]==b[j-1][i] || b[j][i]%b[j-1][i]!=0)) {
out.println(-1);
return;
} else {
sb.append(b[j][i]);
sb.append(' ');
}
}
sb.deleteCharAt(sb.length()-1);
sb.append('\n');
}
out.print(sb.toString());
}
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) {
Main oMain = new Main();
oMain.run(oMain);
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 06bebad705e74fd94583a0e963cbab90 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Scanner;
public class XeniaAndDivisors {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int g124 = 0, g126 = 0, g136 = 0;
int v[] = new int[8];
for(int i = 1; i <= 7; i++) {
v[i] = 0;
}
for(int i = 0; i < n; i++) {
int x = sc.nextInt();
v[x]++;
}
if(v[5] != 0 || v[7] != 0) {
System.out.println("-1");
} else {
if(v[4] > 0) {
g124 = v[4];
v[4] -= g124;
v[2] -= g124;
v[1] -= g124;
}
if(v[2] > 0) {
g126 = v[2];
v[2] -= g126;
v[1] -= g126;
v[6] -= g126;
}
if(v[6] > 0) {
g136 = v[6];
v[1] -= g136;
v[6] -= g136;
v[3] -= g136;
}
if(v[1] != 0 || v[2] != 0 || v[3] != 0 || v[6] != 0) {
System.out.println("-1");
} else {
for(int i = 0; i < g124; i++) {
System.out.print("1 2 4 ");
}
for(int i = 0; i < g136; i++) {
System.out.print("1 3 6 ");
}
for(int i = 0; i < g126; i++) {
System.out.print("1 2 6 ");
}
}
}
sc.close();
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 00365fd949cf7ed728c5718cd8c6e87e | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws IOException
{
//Locale.setDefault (Locale.US);
Reader in = new Reader();
StringBuilder out = new StringBuilder();
int n;
boolean flag;
int[] nums, t = new int[3];
//for (int i = 0; i < 5; i++)
{
n = in.nextInt();
nums = new int[n];
for (int j = 0; j < n; j++)
nums[j]= in.nextInt();
Arrays.sort(nums);
flag = false;
for (int j = 0; j < nums.length/3 && !flag; j++)
{
t[0]=nums[j];
t[1]=nums[j+(nums.length/3)];
t[2]=nums[j+(2*(nums.length/3))];
if(t[0] < t[1] && t[1]%t[0] == 0 && t[1] < t[2] && t[2]%t[1] == 0)
out.append(t[0]+" "+t[1]+" "+t[2]+"\n");
else
flag = true;
}
if(flag)
System.out.println("-1");
else
System.out.print(out);
out = new StringBuilder();
}
}
static class Reader
{
BufferedReader br;
StringTokenizer st;
Reader() { // To read from the standard input
br = new BufferedReader(new InputStreamReader(System.in));
}
Reader(int i) throws IOException { // To read from a file
br = new BufferedReader(new FileReader("Sample Input.txt"));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException { return Integer.parseInt(next()); }
long nextLong() throws IOException { return Long.parseLong(next()); }
double nextDouble() throws IOException { return Double.parseDouble(next()); }
String nextLine() throws IOException { return br.readLine(); }
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 95f0c30f6cbf76889be202efaca4bec6 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | //A. Xenia and Divisors
//time limit per test2 seconds
//memory limit per test256 megabytes
//inputstandard input
//outputstandard output
//Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held:
//aβ<βbβ<βc;
//a divides b, b divides c.
//Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.
//Help Xenia, find the required partition or else say that it doesn't exist.
//Input
//The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7.
//It is guaranteed that n is divisible by 3.
//Output
//If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them.
//If there is no solution, print -1.
//Sample test(s)
//input
//6
//1 1 1 2 2 2
//output
//-1
//input
//6
//2 2 1 1 4 6
//output
//1 2 4
//1 2 6
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.Character;
public class Solution {
public static int[] array;
public static int inputlength;
public Solution() {
int status = readFile();
if (status == -1) {
System.out.println("-1");
}
else {
for (int i = 0; i < array[3]; i++) {
if (array[6] > 0) {
System.out.println("1 3 6");
array[6]--;
}
}
for (int i = 0; i < array[2]; i++) {
if (array[6] > 0) {
System.out.println("1 2 6");
array[6]--;
}
if (array[4] > 0) {
System.out.println("1 2 4");
array[4]--;
}
}
}
//solve();
//int numsolutions = 0;
//for (int i = 0; i < 3; i++) {
//int count = hash.get(i);
//if (count > 0) {
//numsolutions = numsolutions + count;
//}
//}
////System.out.println("numsolutions: " + numsolutions + ", length: " + array.length);
//if (numsolutions == 0 || numsolutions != array.length / 3) {
//System.out.println("-1");
//}
//else {
//for (int i = 0; i < 3; i++) {
//int count = hash.get(i);
//if (count > 0) {
//numsolutions++;
//}
//if (i == 0 && count > 0) {
//for (int j = 0; j < count; j++) {
//System.out.println("1 2 4");
//}
//}
//else if (i == 1 && count > 0) {
//for (int j = 0; j < count; j++) {
//System.out.println("1 2 6");
//}
//}
//else if (i == 2 && count > 0) {
//for (int j = 0; j < count; j++) {
//System.out.println("1 3 6");
//}
//}
//}
//}
}
//public static void solve() {
//hash.put(0, 0);
//hash.put(1, 0);
//hash.put(2, 0);
//sortedarray = new ArrayList<Integer>(array.length);
//for (int i = 0; i < array.length; i++) {
//if (array[i] == 7 || array[i] == 5) {
//return;
//}
//else {
//sortedarray.add(array[i]);
//}
//}
//hash = new HashMap<Integer, Integer>();
//for (int i = 0; i < sortedarray.size(); i++) {
//if (sortedarray.get(i) == 1) {
////System.out.println("found 1 at " + i);
//for (int j = i + 1; j < sortedarray.size(); j++) {
//if (sortedarray.get(j) == 2 || sortedarray.get(j) == 3) {
//for (int k = j + 1; k < sortedarray.size(); k++) {
//if (sortedarray.get(k) == 4 && sortedarray.get(j) == 2) {
//int temp = hash.get(0);
//hash.put(0, ++temp);
//sortedarray.set(k, 0);
//sortedarray.set(j, 0);
//sortedarray.set(i, 0);
//break;
//}
//else if (sortedarray.get(k) == 6) {
//if (sortedarray.get(j) == 2) {
//int temp = hash.get(1);
//hash.put(1, ++temp);
//}
//else if (sortedarray.get(j) == 3) {
//int temp = hash.get(2);
//hash.put(2, ++temp);
//}
//sortedarray.set(k, 0);
//sortedarray.set(j, 0);
//sortedarray.set(i, 0);
//break;
//}
//}
//break;
//}
//}
////for (int l = 0; l < sortedarray.size(); l++) {
////System.out.println(sortedarray.get(l));
////}
//}
//}
//}
public static void main(String[] args) {
Solution temp = new Solution();
}
private static int readFile() {
Scanner sc = new Scanner(System.in);
//System.out.println("enter: ");
String n = sc.nextLine();
inputlength = Integer.parseInt(n);
array = new int[8];
//System.out.println("enter: ");
String currentline = sc.nextLine();
String[] vals = currentline.split(" ");
for (int i = 0; i < vals.length; i++) {
if (Integer.parseInt(vals[i]) == 7 || Integer.parseInt(vals[i]) == 5) {
//System.out.println("Found 7 or 5");
return -1;
}
array[Integer.parseInt(vals[i])]++;
if (i == vals.length - 1) {
//printArray();
//every 3 can only be paired with a 6, so if the number of them found !=, error
if (array[1] != (array[2] + array[3]) || (array[2] + array[3] != array[4] + array[6]) || array[3] > array[6] || (array[3] != array[4] + array[6] - array[2]) || (array[2] != array[6] - array[3] + array[4]) || array[1] != (inputlength / 3)) {
//System.out.println(array[1] + " vs " + (array[2] + array[3]) + ", arraylength / 3: " + inputlength / 3);
return -1;
}
}
}
return 1;
}
private static void printArray() {
for (int j = 0; j < array.length; j++) {
System.out.print(array[j] + " ");
if (j == array.length - 1) {
System.out.println();
}
}
for (int j = 0; j < array.length; j++) {
System.out.print(j + " ");
if (j == array.length - 1) {
System.out.println();
}
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 9089917d1eb956e43bf98be297653ce1 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.*;
import java.io.*;
/*
* author:yanghui
*/
public class A {
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader() throws FileNotFoundException {
reader = new BufferedReader(new FileReader("d:/input.txt"));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
public void run() {
InputReader reader = new InputReader(System.in);
int n = reader.nextInt();
int a[] = new int[n];
for(int i = 0 ; i < n ; i ++){
a[i] = reader.nextInt();
}
int b[] = new int[8];
for(int i = 0 ; i < n ;i ++){
b[a[i]] ++;
}
if(b[0] > 0 || b[5] > 0 || b[7] > 0)
System.out.println(-1);
else if(b[4] > b[1] || b[4] > b[2]){
System.out.println(-1);
}else{
int ans1 = b[4];
b[2] -= b[4];
b[1] -= b[4];
if(b[2] + b[3] > b[1] || b[2]+b[3] < b[1] || b[1] != b[6]){
System.out.println(-1);
}else{
for(int i = 1 ; i <= ans1 ; i ++){
System.out.println(1+" "+2+" "+4);
}
for(int i = 1 ; i <= b[2] ; i ++){
System.out.println(1+" "+2+" "+6);
}
for(int i = 1 ; i <= b[3] ; i ++){
System.out.println(1+" "+3 +" "+6);
}
}
}
}
public static void main(String args[]) {
new A().run();
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 08990f30104409a6a7d9269cb028af94 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class CF199A {
public static void main(final String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] parts = br.readLine().split("\\s+");
int[] a = new int[10];
for (int i = 0; i < parts.length; i++) {
int val = Integer.parseInt(parts[i]);
a[val]++;
}
Map<String, Integer> map = new HashMap<String, Integer>();
boolean found = true;
while (a[1] > 0 && found) {
found = false;
if (a[2] > 0) {
if (a[4] > 0) {
int count = Math.min(a[1], Math.min(a[2], a[4]));
map.put("1 2 4", count);
a[1] -= count;
a[2] -= count;
a[4] -= count;
found = true;
} else if (a[6] > 0) {
int count = Math.min(a[1], Math.min(a[2], a[6]));
map.put("1 2 6", count);
a[1] -= count;
a[2] -= count;
a[6] -= count;
found = true;
}
} else if (a[3] > 0) {
if (a[6] > 0) {
int count = Math.min(a[1], Math.min(a[3], a[6]));
map.put("1 3 6", count);
a[1] -= count;
a[3] -= count;
a[6] -= count;
found = true;
}
}
}
for (int i = 0; i < a.length; i++) {
if (a[i] > 0) {
System.out.println(-1);
return;
}
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Integer> m : map.entrySet()) {
int cnt = m.getValue();
while (cnt > 0) {
cnt--;
sb.append(m.getKey() + "\n");
}
}
System.out.println(sb.toString());
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | bccd8377677e788efe278f8a2d6a23f0 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes |
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class XeniaAndDivisors {
public static void main(String... args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
List<Integer> input = new ArrayList<Integer>();
int [] mem = new int[8];
for (int i = 0; i < n; i++) {
mem[s.nextInt()]++;
}
if(mem[7] > 0 || mem [5] > 0){
System.out.println(-1);
}
else {
if(mem[1] == mem[4] + mem[6] && mem[1] == mem[2] + mem[3] ) {
if(mem[4] > mem[2] || mem[2] > mem[1])
{
System.out.println(-1);
} else if (mem[6] > mem[2]+mem[3] || mem[2]+mem[3] > mem[1] ){
System.out.println(-1);
} else
while(mem[1] > 0) {
if(mem[4] > 0 ){
System.out.println("1 2 4");
mem[1]--;
mem[2]--;
mem[4]--;
continue;
}
if(mem[6] > 0) {
if(mem[2]>0) {
System.out.println("1 2 6");
mem[1]--;
mem[2]--;
mem[6]--;
} else {
System.out.println("1 3 6");
mem[1]--;
mem[3]--;
mem[6]--;
}
}
}
} else {
System.out.println(-1);
}
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 84ed1c9bde46917718486855c3f04242 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = t_int(br);
int[] e = new int[8];
int[] d = t_int_a(br, n);
for (int i : d) {
e[i]++;
}
if (e[5] != 0 || e[7] != 0) {
System.out.println(-1);
return;
}
if (e[1] != n / 3 || e[2] + e[3] != n / 3 || e[4] + e[6] != n / 3) {
System.out.println(-1);
return;
}
StringBuilder out = new StringBuilder();
int groups = 0;
while (e[1] > 0 && e[2] > 0 && e[4] > 0) {
out.append("1 2 4\n");
e[1]--;
e[2]--;
e[4]--;
groups++;
}
while (e[1] > 0 && e[2] > 0 && e[6] > 0) {
out.append("1 2 6\n");
e[1]--;
e[2]--;
e[6]--;
groups++;
}
while (e[1] > 0 && e[3] > 0 && e[6] > 0) {
out.append("1 3 6\n");
e[1]--;
e[3]--;
e[6]--;
groups++;
}
if (groups != n / 3) {
System.out.println(-1);
} else {
System.out.print(out.toString());
}
br.close();
}
public static int t_int(BufferedReader br) throws Exception {
return Integer.parseInt(br.readLine());
}
public static StringTokenizer t_st(BufferedReader br) throws Exception {
return new StringTokenizer(br.readLine());
}
public static int[] t_int_a(BufferedReader br, int n) throws Exception {
StringTokenizer st = t_st(br);
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
return a;
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | cd98809b2aea0f37262784b6b665e446 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution342A {
public static void main(String[] args) {
// Scanner sc = new Scanner(System.in);
MyScanner sc = new MyScanner();
int n = sc.nextInt();
int gruop = n / 3;
int[] numbers = new int[7];
boolean contain5or7 = false;
int one = 0;
for (int i = 0 ; i < n ; i++) {
int index = sc.nextInt();
if(index == 5 || index == 7) {
contain5or7 = true;
}else if(index == 1){
one++;
}
numbers[index-1]++;
}
if (contain5or7 || one > gruop) {
System.out.println(-1);
}else if (numbers[3-1] > numbers[6-1]){
System.out.println(-1);
}else if ( numbers[2-1] != (numbers[4-1] + numbers[6-1] - numbers[3-1]) ) {
System.out.println(-1);
} else {
for(int i = 0 ; i < numbers[4-1] ; i++) {
System.out.println(1 + " " + 2 + " " + 4);
numbers[2-1]--;
}
int two = numbers[2-1];
int three = numbers[3-1];
for(int i = 0 ; i < numbers[6-1] ; i++) {
if(two > 0) {
System.out.println(1 + " " + 2 + " " + 6);
two--;
}else {
System.out.println(1 + " " + 3 + " " + 6);
}
}
}
}
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | f239b2a001beb099fa6fa6b8db4a35c1 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private 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();
int a=0,b=0,c=0,d=0,e=0,f=0;
for(int i = 0; i < n; i++) {
int curr = readInt();
switch(curr) {
case 1:
a++;
break;
case 2:
b++;
break;
case 3:
c++;
break;
case 4:
d++;
break;
case 5:
e++;
break;
case 6:
f++;
break;
}
}
ArrayList<State> ret = new ArrayList<State>();
for(int i = 0; i < n/3; i++) {
if(d > 0) {
if(a == 0 || b == 0) {
break;
}
d--;
a--;
b--;
ret.add(new State(1,2,4));
}
else if(f > 0) {
if(a == 0) {
break;
}
if(b == 0 && c == 0) {
break;
}
if(c > 0) {
a--;
c--;
f--;
ret.add(new State(1,3,6));
}
else if(b > 0) {
a--;
b--;
f--;
ret.add(new State(1,2,6));
}
}
else {
break;
}
}
if(ret.size() != n/3) {
pw.println(-1);
}
else {
for(State out: ret) {
pw.println(out);
}
}
}
pw.close();
}
static class State {
public int a,b,c;
public State(int a, int b, int c) {
super();
this.a = a;
this.b = b;
this.c = c;
}
public String toString() {
return a + " " + b + " " + c;
}
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 917d6d4bf26b5befec26d4b140b7b2f3 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import static java.lang.Math.min;
import static java.lang.Math.max;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class Main implements Runnable {
private void solve() throws Exception {
int n = nextInt();
int[] c = new int[8];
for (int i = 0; i < n; i++) {
int v = nextInt();
c[v]++;
}
if (c[7] > 0 || c[5] > 0) {
out.println(-1);
return;
}
if (c[4] > c[2] || c[4] > c[1]) {
out.println(-1);
return;
}
int c124 = c[4];
c[2] -= c[4];
c[1] -= c[4];
if (c[3] > c[6] || c[3] > c[1]) {
out.println(-1);
return;
}
int c136 = c[3];
c[6] -= c[3];
c[1] -= c[3];
if (c[1] != c[2] || c[2] != c[6]) {
out.println(-1);
return;
}
int c126 = c[1];
for (int i = 0; i < c124; i++) {
out.println("1 2 4");
}
for (int i = 0; i < c126; i++) {
out.println("1 2 6");
}
for (int i = 0; i < c136; i++) {
out.println("1 3 6");
}
}
public String next() throws IOException {
while (!st.hasMoreTokens()) {
final String s = in.readLine();
if (s == null) {
return null;
}
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
IO io;
BufferedReader in;
StringTokenizer st;
PrintWriter out;
public Main() {
// io = file;
io = standard;
}
public void run() {
try {
io.initIO();
try {
solve();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
io.finalizeIO();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Thread(new Main()).start();
}
IO standard = new IO() {
public void initIO() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
st = new StringTokenizer("");
}
public void finalizeIO() {
out.flush();
}
};
IO file = new IO() {
public void initIO() throws IOException {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new File("output.txt"));
st = new StringTokenizer("");
}
public void finalizeIO() throws IOException {
in.close();
out.close();
}
};
interface IO {
public void initIO() throws IOException;
public void finalizeIO() throws IOException;
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | f7628fc637bd08f03d6442b469779600 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
if (str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt();
int []b = new int[8];
for(int i=0;i<n;i++){
int x = nextInt();
b[x]++;
}
String []r = new String[n];
int c = 0;
for(int i=0;i<b[4];i++){
r[c++] = "1 2 4";
}
b[1]-=b[4];
b[2]-=b[4];
b[4] = 0;
for(int i=0;i<b[2];i++){
r[c++] = "1 2 6";
}
if (b[1] < 0 || b[2] < 0) {
out.println(-1);
out.close();
return;
}
b[1]-=b[2];
b[6]-=b[2];
b[2] = 0;
for(int i=0;i<b[3];i++){
r[c++] = "1 3 6";
}
b[1]-=b[3];
b[6]-=b[3];
b[3] = 0;
//out.println(Arrays.toString(b));
for(int i=1;i<8;i++){
if (b[i] != 0) {
out.println(-1);
out.close();
return;
}
}
for(int i=0;i<n/3;i++){
out.println(r[i]);
}
out.close();
}
public static void main(String args[]) throws Exception{
new Main().run();
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | d8edc9fee1f04c81afa5b57c0428398b | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Scanner;
public class A342 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] f = new int[7];
for (int i = 0; i < n; i++)
f[in.nextInt() - 1]++;
StringBuilder out = new StringBuilder();
if (f[6] > 0 || f[4] > 0)
{
System.out.println("-1");
return;
}
int am = f[2];
if (f[0] - am < 0 || f[5] - am < 0)
{
System.out.println("-1");
return;
}
f[2] = 0;
f[0] -= am;
f[5] -= am;
for (int i = 0; i < am; i++)
out.append("1 3 6\n");
am = f[3];
if (f[0] - am < 0 || f[1] - am < 0)
{
System.out.println("-1");
return;
}
f[3] = 0;
f[0] -= am;
f[1] -= am;
for (int i = 0; i < am; i++)
out.append("1 2 4\n");
am = f[1];
if (f[0] - am < 0 || f[5] - am < 0)
{
System.out.println("-1");
return;
}
f[1] = 0;
f[0] -= am;
f[5] -= am;
for (int i = 0; i < am; i++)
out.append("1 2 6\n");
for (int i = 0; i < 7; i++)
if (f[i] > 0)
{
System.out.println("-1");
return;
}
System.out.println(out);
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 28c949f6d959776bb41d1bfb642d6300 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String arg[]) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
int a[] = new int[8];
for (int i = 0; i < 8; i++)
a[i] = 0;
for (int i = 0; i < n; i++)
a[reader.nextInt()]++;
if (a[1] != (n / 3))
System.out.println("-1");
else if (a[5] > 0 || a[7] > 0)
System.out.println("-1");
else if (a[3] > a[6])
System.out.println("-1");
else if (a[2] < a[4])
System.out.println("-1");
else if (a[2] + a[3] != a[4] + a[6])
System.out.println("-1");
else {
print(a[2], a[3], a[4], a[6]);
}
}
private static void print(int i2, int i3, int i4, int i6) {
while (i4-- > 0) {
System.out.println("1 2 4");
i2--;
}
while (i2-- > 0)
System.out.println("1 2 6");
while (i3-- > 0)
System.out.println("1 3 6");
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 90ecb1120fcaff5db4794e3bd8436720 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Main {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int[] c = new int[7+1];
String[] param = br.readLine().split(" ");
for (int i = 0; i < n; i++) c[Integer.parseInt(param[i])]++;
if (c[5]>0 || c[7]>0) pw.println(-1);
else if (c[6]+c[4]!=c[3]+c[2]) pw.println(-1);
else if (c[4]>c[2]) pw.println(-1);
else if (c[3]+c[2]!=c[1]) pw.println(-1);
else {
while (c[4]>0) { pw.println("1 2 4"); c[1]--; c[2]--; c[4]--; }
while (c[2]>0) { pw.println("1 2 6"); c[1]--; c[2]--; c[6]--; }
while (c[6]>0) { pw.println("1 3 6"); c[1]--; c[3]--; c[6]--; }
}
pw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | b9fc8fe5e54697dc56bcef5a910e9f8e | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
while ((line = in.readLine()) != null && line.length() != 0) {
boolean pos = true;
int[] v = readInts(in.readLine());
int[] a = { 0, 0, 0, 0, 0, 0, 0 };
for (int i = 0; i < v.length; i++)
if (v[i] == 5 || v[i] == 7) {
pos = false;
break;
} else
a[v[i]]++;
boolean almostOne = false;
StringBuilder out2 = new StringBuilder();
// Six
for (int i = 0; i < a[6]; i++) {
almostOne = false;
if (a[1] > 0 && a[3] > 0) {
a[1]--;
a[3]--;
almostOne = true;
out2.append("1 3 6\n");
} else if (a[1] > 0 && a[2] > 0) {
a[1]--;
a[2]--;
almostOne = true;
out2.append("1 2 6\n");
}
if (!almostOne) {
pos = false;
break;
}
}
// Four
for (int i = 0; i < a[4]; i++) {
almostOne = false;
if (a[1] > 0 && a[2] > 0) {
a[1]--;
a[2]--;
almostOne = true;
out2.append("1 2 4\n");
}
if (!almostOne) {
pos = false;
break;
}
}
for (int i = 1; i <= 3; i++)
pos &= a[i]==0;
if(pos)
out.append(out2);
else
out.append("-1\n");
}
System.out.print(out);
}
public static int[] readInts(String line) {
String[] w = line.trim().split(" ");
int[] a = new int[w.length];
for (int i = 0; i < w.length; i++)
a[i] = Integer.parseInt(w[i].trim());
return a;
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 3046be300098a5218345861792fa719d | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Scanner;
public class ce {
public static void main(String[] args) throws IOException {
new ce().run();
}
StreamTokenizer in;
PrintWriter out;
int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
char nextChar() throws IOException {
in.nextToken();
return ((String) in.sval).charAt(0);
}
void run() throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(
System.in)));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
void solve() throws IOException {
int n=nextInt();
// int a;
int[] z=new int[8];
for(int q=0;q<n;q++)
{
z[nextInt()]++;
}
if(z[0]>0||z[5]>0||z[7]>0||z[1]!=n/3)
{
System.out.println(-1);
return;
}
int q=z[2];
int w=z[3];
int e=z[4];
int r=z[6];
if(q+w!=n/3||e+r!=n/3||q<e)
{
System.out.println(-1);
return;
}
for(int t=0;t<e;t++)
System.out.println("1 2 4");
for(int t=n/3-e-w;t>0;t--)
System.out.println("1 2 6");
for(int t=0;t<w;t++)
System.out.println("1 3 6");
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 724279d7e3eb777db77030c9050388a8 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.*;
public class A342 {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int ones = 0;
int twos = 0;
int threes = 0;
int fours = 0;
int sixes = 0;
for (int i = 0; i < n; i++) {
int a = in.nextInt();
if (a == 1)
++ones;
else if (a == 2)
++twos;
else if (a == 3)
++threes;
else if (a == 4)
++fours;
else if (a == 6)
++sixes;
}
boolean c1 = ones > 0 && twos > 0 && fours > 0;
boolean c2 = ones > 0 && twos > 0 && sixes > 0;
boolean c3 = ones > 0 && threes > 0 && sixes > 0;
ArrayList<String> l = new ArrayList<String>();
if (c1 || c2 || c3) {
while (ones > 0 && twos > 0 && fours > 0) {
l.add("1 2 4");
--ones;
--twos;
--fours;
}
while (ones > 0 && twos > 0 && sixes > 0) {
l.add("1 2 6");
--ones;
--twos;
--sixes;
}
while (ones > 0 && threes > 0 && sixes > 0) {
l.add("1 3 6");
--ones;
--threes;
--sixes;
}
if (l.size() >= (n / 3)) {
for (int i = 0; i < n / 3; i++)
System.out.println(l.get(i));
} else
System.out.println(-1);
} else
System.out.println(-1);
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | d32018b7564974ff886fda5966a082b0 | train_002.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main implements Runnable {
private static void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
boolean some = false;
for( int i = 0; i < n; ++i ){
a[i] = nextInt();
if( a[i] == 5 || a[i] == 7 )some = true;
}
int[] f = new int[10];
for( int i : a ){
f[i]++;
}
if( some || f[1] < n/3){
out.println(-1);
return;
}
// Arrays.sort(a);
int[][] ret = new int[n/3][3];
for( int i = 0; i < n/3; ++i ){
if( f[1] != 0 && f[2] != 0 && f[4] != 0 ){
ret[i][0] = 1;
ret[i][1] = 2;
ret[i][2] = 4;
f[1]--;
f[2]--;
f[4]--;
continue;
}
if( f[1] != 0 && f[2] != 0 && f[6] != 0 ){
ret[i][0] = 1;
ret[i][1] = 2;
ret[i][2] = 6;
f[1]--;
f[2]--;
f[6]--;
continue;
}
if( f[1] != 0 && f[3] != 0 && f[6] != 0 ){
ret[i][0] = 1;
ret[i][1] = 3;
ret[i][2] = 6;
f[1]--;
f[3]--;
f[6]--;
continue;
}
out.println(-1);
return;
}
for( int i = 0; i < n/3; ++i ){
out.println(ret[i][0]+" "+ret[i][1]+" "+ret[i][2]);
}
}
public static void main(String[] args) {
new Thread(null, new Main(), "main", 1 << 29).start();
}
private static PrintWriter out;
private static BufferedReader in;
private static StringTokenizer tokenizer;
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
eat("");
solve();
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void eat(String s) {
tokenizer = new StringTokenizer(s);
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (!tokenizer.hasMoreElements()) {
String s = in.readLine();
if (s == null)
return null;
eat(s);
}
return tokenizer.nextToken();
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 6 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | a202fe89129076b3591d25c42ebf8e5a | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.io.IOException;
import java.util.StringTokenizer;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.TreeSet;
import java.util.*;
public class Main {
public static void main(String[]args)
{
FastReader in=new FastReader();
int n=in.nextInt();
int[]x=new int[n];
int i=0;
while(i<n)
{
x[in.nextInt()-1]=i+1;
i++;
}
i=0;
long count=0;
while(i+1<x.length)
{
count+=Math.abs(x[i+1]-x[i]);
i++;
}
System.out.println(count);
}
}
//method for prime numbers
/*public static boolean sieve(int n) {
boolean[]x=new boolean[n+1];
for(int i = 0; i <= n;++i) {
x[i] = true;
}
x[0] = false;
x[1] = false;
for(int i = 2; i * i <= n; ++i) {
if(x[i] == true) {
// Mark all the multiples of i as composite numbers
for(int j = i * i; j <= n ;j += i)
x[j] = false;
}
}
int i=0;
int count=0;
while(i<x.length)
{
if(x[i] && n%i==0)
count++;
i++;
}
return (count==3)?true:false;*/
/* monk is birthday treat
int n=in.nextInt();
int t=in.nextInt();
s=new List[n];
for(int r=0;r<s.length;r++)
{
s[r]=new ArrayList();
}
while(t-->0)
{
int a=in.nextInt()-1;
int b=in.nextInt()-1;
s[a].add(b);
}
long[]p=new long[n];
for(int i=0;i<s.length;i++)
{
Stack<Integer>e=new Stack();
int[]k=new int[s[i].size()];
int j=0;
if(!s[i].isEmpty()){
boolean []x=new boolean[n];
for (Integer h : s[i]) {
int count=0;
e.add(h);
if(!x[h]){
x[h]=true;
count++;
}
while(!e.isEmpty())
{
int u=e.pop();
for (Integer v : s[u]) {
if(!x[v])
{
x[v]=true;
count++;
e.add(v);
}
}
}
k[j]=count;
j++;
}
Arrays.sort(k);
int q=0;
while(q<k.length)
{
if(k[q]!=0)
{
p[i]=k[q];
break;
}
q++;
}
}
}
Arrays.sort(p);
int y=0;
long count2=0;
while(y<p.length)
{
if(p[y]!=0)
{
count2=p[y];
break;
}
y++;
}
System.out.println(count2);
*/
/*class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}*/
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 | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 5d3de22765edc7cdb1130cfc5d2545fa | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
public class Main {
private static StreamTokenizer inputReader = new StreamTokenizer(
new BufferedReader(new InputStreamReader(System.in)));
public static int nextInt() {
int a = -1;
try {
inputReader.nextToken();
a = (int) inputReader.nval;
} catch (Exception e) {
}
return a;
}
public static void main(String[] args) {
int numberOfPairs = nextInt();
Pair[] array = new Pair[numberOfPairs];
for (int i = 0; i < numberOfPairs; i++) {
Pair pair = new Pair(i, nextInt());
array[i] = pair;
}
Arrays.sort(array);
long answer = 0;
for (int i = 0; i < numberOfPairs - 1; i++) {
answer += Math.abs(array[i].index - array[i + 1].index);
}
System.out.println(answer);
}
private static class Pair implements Comparable<Pair>{
int index;
int segment;
public Pair(int index, int segmnet) {
this.index = index;
this.segment = segmnet;
}
@Override
public int compareTo(Pair other) {
return Integer.compare(this.segment, other.segment);
}
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 9a9288307539c5ede3600c26b4583657 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.*;
public class week1B {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int numInputs = Integer.valueOf(sc.nextLine());
String[] inputs = sc.nextLine().split(" ");
System.out.println(getTimeUnits(inputs, numInputs));
sc.close();
}
static long getTimeUnits (String[] inputs, int numInputs){
int[] array = new int[numInputs];
for (int i = 0; i < numInputs; i++){
int currentNum = Integer.valueOf(inputs[i])-1;
array[currentNum] = i;
}
long time = 0;
for (int i = 0; i < numInputs; i++){
if (i>0){
time += Math.abs(array[i] - array[i-1]);
}
}
return time;
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 445d1a1b4f9132e57b9416ebe1cf445a | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes |
import javafx.util.Pair;
import java.io.PrintWriter;
import java.util.*;
public class Ed4B {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt();
in.nextLine();
ArrayList<Pair> vals = new ArrayList<>();
long counter = 0;
for (int i = 0; i < t; i++) {
int a = in.nextInt();
Pair pair = new Pair(a, i);
vals.add(pair);
}
Collections.sort(vals, (o1, o2) -> {
int o1K = (int) o1.getKey();
int o2K = (int) o2.getKey();
if (o1K < o2K) {
return -1;
} else if (o1K > o2K) {
return 1;
} else {
return 0;
}
});
for (int i = 0; i < vals.size() - 1; i++) {
int v = (int) vals.get(i).getValue();
int vNext = (int) vals.get(i + 1).getValue();
counter += Math.abs(v - vNext);
}
out.println(counter);
out.flush();
}
} | Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 544cf67ee7dbd402850cc3de809c17d4 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
public class Main
{
public static void main(String[] args) throws Exception
{
long startTime = System.nanoTime();
int n = in.nextInt();
int [] indexes = new int[n+10];
for(int i=1;i<=n;i++)
{
indexes[in.nextInt()]=i;
}
long ans = 0;
for(int i=2;i<=n;i++)
{
ans+=Math.abs(indexes[i-1]-indexes[i]);
}
out.println(ans);
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime-startTime)/1000000 + " ms");
exit(0);
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
static void exit(int a)
{
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | e566b8f3520458fc45332fb58abe83cb | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
public class Main
{
public static void main(String[] args) throws Exception
{
long startTime = System.nanoTime();
int n = in.nextInt();
HashMap<Integer,Integer> indexes = new HashMap<Integer,Integer>();
for(int i=1;i<=n;i++)
{
indexes.put(in.nextInt(),i);
}
long ans = 0;
for(int i=2;i<=n;i++)
{
ans+=Math.abs(indexes.get(i-1)-indexes.get(i));
}
out.println(ans);
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime-startTime)/1000000 + " ms");
exit(0);
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
static void exit(int a)
{
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | af0f4c2ab1106f06564d0c52de92d5b9 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
public class Main
{
public static void main(String[] args) throws Exception
{
long startTime = System.nanoTime();
int n = in.nextInt();
int [] indexes = new int[n+10];
for(int i=1;i<=n;i++)
{
indexes[in.nextInt()]=i;
}
long ans = 0;
for(int i=2;i<=n;i++)
{
ans+=Math.abs(indexes[i-1]-indexes[i]);
}
out.println(ans);
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime-startTime)/1000000 + " ms");
exit(0);
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
static void exit(int a)
{
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 1cc46ee5704d697ec1c91a03a24ad364 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes |
import java.util.HashMap;
import java.util.Scanner;
public class JavaApplication31 {
public static int counter = 0 ,n ;
public static void main(String[] args)
{
int x = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
HashMap<Integer , Integer > f = new HashMap<Integer , Integer >();
for (int i = 0 ; i < n; i ++ )
{
int g = sc.nextInt();
f.put(g, i+1);
if (g == 1 )
x = i+1;
}
System.out.print( getValue (f , 2 , x));
}
public static long getValue (HashMap ff , int l , int x)
{
long total = 0;
if (l <= n)
{
int g ;
g = (int) ff.get(l);
if (x>g)
total += x-g;
else
total += g-x;
x = g;
return total + getValue (ff , l+1 ,x) ;
}
else
return total;
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | f129e616101f5f5c26155e40e8097d7e | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author T.C.D
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInputReader in = new FastInputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastInputReader in, PrintWriter out) {
int n = in.nextInt();
int[] pos = new int[n + 1];
long ans = 0;
for (int i = 0; i < n; i++) {
pos[in.nextInt()] = i;
}
for (int i = 2; i <= n; i++) {
ans += Math.abs(pos[i] - pos[i - 1]);
}
out.println(ans);
}
}
static class FastInputReader {
static InputStream is;
static private byte[] buffer;
static private int lenbuf;
static private int ptrbuf;
public FastInputReader(InputStream stream) {
is = stream;
buffer = new byte[1024];
lenbuf = 0;
ptrbuf = 0;
}
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return buffer[ptrbuf++];
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 4da9d5ee99c487dbea16f48f28ea6c68 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.*;
public class PetyaString {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < n; i++){
map.put(in.nextInt(), i);
}
long time = 0;
int n1 = 1;
int index = map.get(n1);
map.remove(n1);
while(!map.isEmpty()){
n1++;
int tempI = index;
index = map.get(n1);
time += (long) Math.abs(tempI - index);
map.remove(n1);
}
System.out.println(time);
}
} | Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 1c2279ab7b6f4833adab329a90834a80 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
Map<Integer, Integer> list = new HashMap<Integer, Integer>();
for(int i =0;i<n;i++){
int k = in.nextInt();
list.put(k, i);
}
long sum =0;
int f1 =0;
int f2 = list.get(1);
for(int i=2;i<=n;i++){
f1 = f2;
f2 = list.get(i);
sum+=Math.abs(f1-f2);
}
out.print(sum);
out.close();
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | b827333b129aa0214a98ef3ef556ba24 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.*;
/**
* Created by danielmckee on 4/30/16.
*/
public class HDDOutdatedTechnology {
Scanner in = new Scanner(System.in);
Map<Integer, Integer> numToPos = new HashMap<>();
//List<Integer> frags = new ArrayList<>();
private void solve() {
long answer = 0;
int n = in.nextInt();
for (int i = 0; i < n; i++){
int num = in.nextInt();
numToPos.put(num, i);
//frags.add(num);
}
for ( int i = 1; i < n; i++) {
//int nextPos = frags.get(prevPos)-1;
long prevPos = numToPos.get(i);
long nextPos = numToPos.get(i+1);
answer += Math.abs(prevPos - nextPos);
}
System.out.println(answer);
}
public static void main(String[] args) {
HDDOutdatedTechnology h = new HDDOutdatedTechnology();
h.solve();
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 6235c30aff83071993b3dd66093ac134 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.*;
public class P612B
{
public static void main(String[] args)
{
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
long sum = 0;
for (int i = 0; i < n; i++)
map.put(scan.nextInt(), i);
for (int i = 1; i < n; i++)
sum += Math.abs(map.get(i)-map.get(i+1));
System.out.println(sum);
scan.close();
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 392e93191ba64d31bc2cc4e7a9344bc4 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.Scanner;
public class problem_612B {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
long distance = 0;
int current = 1, currentIndex = -1;
int[] sectors = new int[n];
int[] sectorIndexes = new int[n];
for(int i = 0; i < n; i++)
{
sectors[i] = scan.nextInt();
sectorIndexes[sectors[i]-1] = i;
}
for(int i = 1; i < n; i++)
{
distance += Math.abs(sectorIndexes[i] - sectorIndexes[i-1]);
}
System.out.println(distance);
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 67997ab83b87d92a412f17580872e063 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.Comparator;
import java.util.Scanner;
public class B {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
long n = in.nextInt();
int[] arr = new int[(int)n + 1];
// Hdd[] arr = new Hdd[(int)n];
long ans = 0;
for (int i = 1; i <= n; i++) {
int val = in .nextInt();
arr[val] = i;
// int val = in.nextInt();
// arr[i] = new Hdd(val, i);
}
for (int i = 2; i <= n; i++) {
ans += Math.abs(arr[i] - arr[i-1]);
}
System.out.println(ans);
// n -= 1;
// System.out.println(n * (n + 1) / 2);
// Arrays.sort(arr, Hdd.hddComparator);
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].val + " " + arr[i].pos + "\n");
// }
// int t = 0;
// while(t != n - 1) {
//
// }
}
public static class Hdd implements Comparable<Hdd>{
public int val;
public int pos;
public Hdd(int val, int pos) {
this.val = val;
this.pos = pos;
}
@Override
public int compareTo(Hdd o) {
return this.val - o.val;
}
public static Comparator<Hdd> hddComparator = new Comparator<Hdd>() {
@Override
public int compare(Hdd o1, Hdd o2) {
return o1.compareTo(o2);
}
};
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 97b4419456577418f54526d388feb9dc | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
public class HDDisoutdatedtechnology {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int noOfFragments=Integer.parseInt(in.readLine());
int fragmentNo[]=new int[noOfFragments];
int position[]=new int[noOfFragments+1];
String temp[]=in.readLine().split(" ");
long time=0;
for(int i=0;i<temp.length;i++)
{
fragmentNo[i]=Integer.parseInt(temp[i]);
position[fragmentNo[i]]=i;
}
for(int sectorNo=1;sectorNo<noOfFragments;sectorNo++)
{
time+=Math.abs(position[sectorNo]-position[sectorNo+1]);
}
out.write(String.valueOf(time));
out.flush();
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | ef768ce269cc0952da4304734df03e93 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Hdd {
public static void main(String[] args)
{
MySime sc=new MySime();
int n=sc.nextInt();
int frag[]=new int[n+1];
long t=0;
for(int i=1;i<=n;i++)
{
int f=sc.nextInt();
frag[f]=i;
}
int p=frag[1];
for(int i=2;i<=n;i++)
{
t+=mod(p-frag[i]);
p=frag[i];
}
System.out.println(t);
}
public static int mod(int n)
{
if (n<0)
return -n;
else
return n;
}
}
class MySime
{
BufferedReader br;
StringTokenizer st;
MySime()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while(st==null || !st.hasMoreTokens())
{
try
{
st=new StringTokenizer(br.readLine());
}
catch(Exception 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(Exception e)
{
e.printStackTrace();
}
return str;
}
} | Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | e99d0197916b1a8c8d8ee5f5908f2aca | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes |
import java.beans.Visibility;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
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.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
public class Main implements Runnable{
public static void main(String[] args) throws IOException {
new Thread(null , new Main(),"Main", 1<<26).start();
}
public void run(){
try {
PrintWriter out = new PrintWriter(System.out);
MyScanner sc = new MyScanner();
solve(out, sc);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
void solve(PrintWriter out, MyScanner sc) throws IOException{
int n = sc.nextInt();
node[] a = new node[n];
for(int i = 0 ; i < n ; ++i) {
a[i] = new node(i, sc.nextInt());
}
Arrays.sort(a, new Comparator<node>() {
@Override
public int compare(node o1, node o2) {
return o1.f - o2.f;
}
});
long res = 0;
for(int i = 1 ; i < n ; ++i) {
res += Math.abs(a[i].pos - a[i - 1].pos);
}
out.print(res);
}
static class node{
int pos;
int f;
public node(int pos, int f) {
this.pos = pos;
this.f = f;
}
}
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 3db40e756fd7e5fbcf1645f79e2b4e32 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
static int n;
static HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
static long counter = 0;
public static void main(String[] args) {
n = sc.nextInt();
for (int i = 0; i < n; i++) map.put(sc.nextInt(), i);
for (int i = 0; i < n - 1; i++) {
counter += Math.abs(map.get(i + 1) - map.get(i + 2));
}
System.out.println(counter);
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | bd4d57f14d5b144b80a2301c10168d42 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.Scanner;
public final class HDDIsOutDatedCF {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n+1];
for(int i=1;i<=n;i++){
int index=sc.nextInt();
arr[index]=i;
}
long ans=0;
for(int i=2;i<=n;i++){
ans+= Math.abs(arr[i]-arr[i-1]);
}
System.out.println(ans);
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 59d6860dc39dd66bb0ac87fed89b0d32 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.Scanner;
public class HDD {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++){
int x=scan.nextInt();
a[x-1]=i+1;
}
long sum=0,diff;
for(int i=1;i<n;i++){
if(a[i-1]>a[i]){
diff=(long) a[i-1]- (long) a[i];
}
else{
diff= (long) a[i]- (long) a[i-1];
}
sum=sum+diff;
}
System.out.println(sum);
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 6b76fa8cd09b4ed67b5af548d6d848af | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
/**
* Created by WiNDWAY on 4/30/16.
*/
public class Codeforces_Educational_round_4_HDDIsOutdatedTechnology {
public static void main(String[] args) {
FScanner input = new FScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
int fragments = input.nextInt();
HashMap<Long, Long> map = new HashMap<>();
long index = 1;
for (int i = 0; i < fragments; i++) {
map.put(input.nextLong(), index);
index++;
}
long total = 0;
long starting = map.get(new Long(1));
for (long i = 1; i <= fragments; i++) {
long next = map.get(i);
total += Math.abs(starting - next);
starting = next;
}
out.println(total);
}
public static PrintWriter out;
public static class FScanner {
BufferedReader br;
StringTokenizer st;
public FScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | d774eda18de0fc9773c9b8c1358c4886 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.*;
public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfFragments = scanner.nextInt();
HashMap<Integer, Integer> fragments = new HashMap<Integer, Integer>();
for(int i=0;i<numberOfFragments;i++){
fragments.put(Integer.parseInt(scanner.next()), i+1);
}
int currentFragment = 1;
int currentSector = 1;
currentSector = fragments.get(currentFragment);
Long distance = 0l;
while(currentFragment != numberOfFragments){
distance += Math.abs(currentSector - fragments.get(currentFragment+1));
currentFragment++;
currentSector = fragments.get(currentFragment);
}
System.out.println(distance);
}
} | Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 0b5d17293a7a66a4e66e748ce20051ae | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.Scanner;
public class HardDisk{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int ind[] = new int[n];
int i = 0;
while(i<n){
ind[in.nextInt()-1]=i;
i++;
}
long time = 0;
for(i = 1;i<n;i++){
time+=Math.abs(ind[i]-ind[i-1]);
}
System.out.println(time);
}
} | Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | f517c3dd35c2752b8c18537c08b43911 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes |
import java.awt.Point;
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
static StringBuilder a = new StringBuilder();
public static void main(String[] args) throws IOException {
// BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//(new FileReader("input.in"));
StringBuilder out = new StringBuilder();
// StringTokenizer tk;
// tk = new StringTokenizer(in.readLine());
//Scanner Reader = new Scanner(System.in);
Reader.init(System.in);
int n=Reader.nextInt();
long []a=new long[n+1];
for (int i = 1; i < a.length; i++) {
a[Reader.nextInt()]=i;
}
long c=0;
for (int i = 1; i < a.length-1; i++) {
c+=abs(a[i+1]-a[i]);
}
System.out.println(c);
}
}
class Reader {
static StringTokenizer tokenizer;
static BufferedReader reader;
public static void init(InputStream input) throws UnsupportedEncodingException {
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
tokenizer = new StringTokenizer("");
}
public static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static String nextLine() throws IOException {
return reader.readLine();
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | f727e159729b6b1d449114d416d83e4f | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
public class HDD {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
HashMap<Integer, Integer> mapping = new HashMap<>();
for (int i = 1; i <= length; i++){
mapping.put(scanner.nextInt(), i);
}
long total = 0;
for (int i = 1; i < length; i++){
total += Math.abs(mapping.get(i + 1) - mapping.get(i));
}
System.out.print(total);
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 68a65eef5c0b79da185db96ce204a296 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
public class HDD {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
HashMap<Integer, Integer> mapping = new HashMap<>();
for (int i = 1; i <= length; i++){
mapping.put(scanner.nextInt(), i);
}
long total = 0;
for (int i = 1; i < length; i++){
total += Math.abs(mapping.get(i + 1) - mapping.get(i));
}
System.out.print(total);
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 84dd14cdf27d829d4481fabcf14b9422 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Likai
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
Pair[] pairs;
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
pairs = new Pair[n];
for (int i = 0; i < n; ++i) {
pairs[i] = new Pair();
pairs[i].pos = i;
pairs[i].val = in.nextInt();
}
Arrays.sort(pairs);
long res = 0;
for (int i = 1; i < n; ++i) {
res += Math.abs(pairs[i].pos - pairs[i - 1].pos);
}
out.println(res);
}
public class Pair implements Comparable<Pair> {
public int pos;
public int val;
public int compareTo(Pair o) {
return this.val - o.val;
}
}
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 3d75644acaa38c5c690dd916c1f26336 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes |
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n == 1) {
System.out.println("0");
return;
}
Long[] arr = new Long[n];
for (int i = 0; i < n; i++) {
arr[i] = (Long.parseUnsignedLong(sc.next()) << 32) + i;
}
Arrays.sort(arr);
Long res = Long.parseUnsignedLong("0");
for (int i = 0, k = n - 1; i < k; i++) {
int f = (int) (arr[i] & 0xFFFFFFFF);
int s = (int) (arr[i + 1] & 0xFFFFFFFF);
res += Math.abs(f - s);
}
System.out.println(res);
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 07184035d3ce81099aaef2c2f11b7dd5 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class B612 {
public static void main(String[] args) {
//3 1 2
//
Scanner s = new Scanner(System.in);
int n = s.nextInt(), index = -1;
int[] frag = new int[n], indices = new int[n];
for(int i = 0 ; i < n; i++) {
frag[i] = s.nextInt();
if(frag[i] == 1) index = i;
indices[frag[i]-1] = i;
}
long sum = 0;
for(int i = 0; i < indices.length-1; i++) {
sum += Math.abs(indices[i]-indices[i+1]);
}
System.out.println(sum);
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 43fbf1f0b6395d5f993e22b24c379098 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.Scanner;
public class HDD {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int[] input = new int[in.nextInt()];
for(int i = 0; i < input.length; i++){
input[i] = in.nextInt();
}
long retsum = HDDisOutdated(input);
System.out.println(retsum);
in.close();
}
public static long HDDisOutdated(int[] arr){
if(arr.length==1){
return 0;
}
int[] indarr = new int[arr.length];
long retsum = 0;
for(int i = 0; i < arr.length; i++){
indarr[arr[i]-1] = i;
}
for(int j = 0; j < indarr.length-1; j++){
retsum += (long) Math.abs(indarr[j+1] - indarr[j]);
}
return retsum;
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 745017fbc6cf3ebe6d2ea52a5197d6d0 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | /*
* Code Author: Sanket Udgirkar.
* DA-IICT
*/
import java.util.*;
import java.io.*;
public class Tester
{
public static long mod=(long)1e9+7;
public static void main(String[] args)
{
InputReader s=new InputReader(System.in);
OutputStream outputStream = System.out;
//PrintWriter out=new PrintWriter(outputStream);
int n=s.nextInt();
int f[] = new int[n];
int pos[] = new int[n+1];
for(int i=0; i<n; i++)
f[i]=s.nextInt();
for(int i=0; i<n; i++)
pos[f[i]]=i+1;
//for(int i=1; i<=n; i++)
//System.out.print(pos[i]+" ");
long time=0;
for(int i=1; i<n; i++)
{
//System.out.println(Math.abs(pos[i+1]-pos[i]));
time=time+Math.abs(pos[i+1]-pos[i]);
}
System.out.println(time);
//out.close();
}
static long gcd(long a,long b)
{
if(b==0)
return a;
a%=b;
return gcd(b,a);
}
static long exp(long a, long b)
{
if(b==0)
return 1;
if(b==1)
return a;
if(b==2)
return a*a;
if(b%2==0)
return exp(exp(a,b/2),2);
else
return a*exp(exp(a,(b-1)/2),2);
}
static class Pair implements Comparable<Pair>
{
long x,f;
Pair(long ii, long cc)
{
x=ii;
f=cc;
}
public int compareTo(Pair o)
{
return Long.compare(this.x, o.x);
}
}
public static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine=null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try {
fullLine=reader.readLine();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} | Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 63f32aacafca81670e4b282bed646bd2 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class codeforcesB
{
public static void main(String[]args)throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String s = br.readLine();
while (s != null)
{
int n = Integer.parseInt(s);
int x[] = new int[n];
int y[] = new int[n+1];
long l = 0;
st = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < n; i++)
{
x[i] = Integer.parseInt(st.nextToken());
y[x[i]] = i+1;
}
for(int i = 1; i < n; i++)
l = l+Math.abs(y[i] - y[i+1]);
System.out.println(l);
s = br.readLine();
}
}
} | Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | ef2a7630e8f2b93fd8ccdd42bb0cd5a6 | train_002.jsonl | 1451055600 | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1ββ€βfiββ€βn). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |aβ-βb| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class CodeForces {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Number[] parts = new Number[sc.nextInt()];
for (int i = 0; i < parts.length; i++) {
parts[i] = new Number(sc.nextInt(), i);
}
long range = 0;
Arrays.sort(parts);
for(int i = 1; i < parts.length; i++)
{
Number part = parts[i];
Number num = parts[i - 1];
part.setRange(num);
range += part.range;
}
System.out.println(range);
}
}
class Number implements Comparable<Number>{
int value;
int index;
int range;
public Number(int value, int index){
this.value = value;
this.index = index;
this.range = 0;
}
public void setRange(Number num){
if(this.value - 1 == num.value)
this.range = Math.abs(num.index - this.index);
}
@Override
public int compareTo(Number o) {
return this.value - o.value;
}
}
| Java | ["3\n3 1 2", "5\n1 3 5 4 2"] | 1 second | ["3", "10"] | NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4β+β3β+β2β+β1β=β10. | Java 8 | standard input | [
"implementation",
"math"
] | 54e2b6bea0dc6ee68366405945af50c6 | The first line contains a positive integer n (1ββ€βnββ€β2Β·105) β the number of fragments. The second line contains n different integers fi (1ββ€βfiββ€βn) β the number of the fragment written in the i-th sector. | 1,200 | Print the only integer β the number of time units needed to read the file. | standard output | |
PASSED | 0ef1025dd580d0b524569fd4fce30a44 | train_002.jsonl | 1359732600 | Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet β it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.However, his max-flow algorithm seems to have a little flaw β it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.More formally. You are given an undirected graph. For each it's undirected edge (ai, bi) you are given the flow volume ci. You should direct all edges in such way that the following conditions hold: for each vertex v (1β<βvβ<βn), sum of ci of incoming edges is equal to the sum of ci of outcoming edges; vertex with number 1 has no incoming edges; the obtained directed graph does not have cycles. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Collection;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author ocelopilli
*/
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);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
final int MAXN = 200005;
int[] u = new int[ MAXN ];
int[] v = new int[ MAXN ];
int[] w = new int[ MAXN ];
int[] c = new int[ MAXN ];
int[] ans = new int[ MAXN ];
boolean[] seen = new boolean[ MAXN ];
ArrayList< Integer >[] g = new ArrayList[ MAXN ];
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
for (int i=1; i<=n; i++) g[i] = new ArrayList<Integer>();
for (int i=0; i<m; i++)
{
u[i] = in.nextInt();
v[i] = in.nextInt();
w[i] = in.nextInt();
c[ u[i] ] += w[i];
c[ v[i] ] += w[i];
g[ u[i] ].add( i );
g[ v[i] ].add( i );
}
for (int i=2; i<n; i++) c[i] /= 2;
Queue<Integer> Q = new LinkedList<Integer>();
Q.add( 1 );
while ( !Q.isEmpty() )
{
int va = Q.poll();
for (int e : g[va])
{
if ( seen[ e ] ) continue;
seen[e] = true;
if ( u[e] == va )
{
ans[e] = 0;
c[ v[e] ] -= w[e];
if ( c[ v[e] ] == 0 ) Q.add( v[e] );
}
else
{
ans[e] = 1;
c[ u[e] ] -= w[e];
if ( c[ u[e] ] == 0 ) Q.add( u[e] );
}
}
}
for (int i=0; i<m; i++) out.println( ans[i] );
}
}
class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream in)
{
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
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 3\n3 2 10\n1 2 10\n3 1 5", "4 5\n1 2 10\n1 3 10\n2 3 5\n4 2 15\n3 4 5"] | 2 seconds | ["1\n0\n1", "0\n0\n1\n1\n0"] | NoteIn the first test case, 10 flow units pass through path , and 5 flow units pass directly from source to sink: . | Java 7 | standard input | [
"sortings",
"dfs and similar"
] | f065e8c469a5a71a9ef602b6d8bfc9e2 | The first line of input contains two space-separated integers n and m (2ββ€βnββ€β2Β·105, nβ-β1ββ€βmββ€β2Β·105), the number of vertices and edges in the graph. The following m lines contain three space-separated integers ai, bi and ci (1ββ€βai,βbiββ€βn, aiββ βbi, 1ββ€βciββ€β104), which means that there is an undirected edge from ai to bi with flow volume ci. It is guaranteed that there are no two edges connecting the same vertices; the given graph is connected; a solution always exists. | 2,100 | Output m lines, each containing one integer di, which should be 0 if the direction of the i-th edge is aiβββbi (the flow goes from vertex ai to vertex bi) and should be 1 otherwise. The edges are numbered from 1 to m in the order they are given in the input. If there are several solutions you can print any of them. | standard output | |
PASSED | b01f8347a005a3ced41a32dd145fd94e | train_002.jsonl | 1359732600 | Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet β it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.However, his max-flow algorithm seems to have a little flaw β it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.More formally. You are given an undirected graph. For each it's undirected edge (ai, bi) you are given the flow volume ci. You should direct all edges in such way that the following conditions hold: for each vertex v (1β<βvβ<βn), sum of ci of incoming edges is equal to the sum of ci of outcoming edges; vertex with number 1 has no incoming edges; the obtained directed graph does not have cycles. | 256 megabytes | import java.io.IOException;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Collection;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author George Marcus
*/
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);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int M = in.nextInt();
ArrayList<Edge>[] G = new ArrayList[N + 1];
int[] F = new int[N + 1];
int[] D = new int[M];
boolean[] v = new boolean[N + 1];
for(int i = 1; i <= N; i++)
G[i] = new ArrayList<Edge>();
for(int i = 0; i < M; i++) {
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
G[a].add(new Edge(b, c, i, 1));
G[b].add(new Edge(a, c, i, 0));
F[a] += c;
F[b] += c;
D[i] = -1;
}
for(int i = 1; i <= N; i++)
F[i] /= 2;
Queue<Integer> Q = new LinkedList<Integer>();
Q.add(1);
v[1] = true;
while(!Q.isEmpty()) {
int p = Q.remove();
for(Edge e : G[p]) {
if(D[e.id] == -1) {
D[e.id] = e.dir;
F[e.to] -= e.flow;
}
if(e.to != N && !v[e.to] && F[e.to] == 0) {
v[e.to ] = true;
Q.add(e.to);
}
}
}
for(int i = 0; i < M; i++)
out.println(1 - D[i]);
}
private class Edge {
public int to;
public int flow;
public int id;
public int dir;
private Edge(int to, int flow, int id, int dir) {
this.to = to;
this.flow = flow;
this.id = id;
this.dir = dir;
}
}
}
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 nextInt() {
return Integer.parseInt(nextString());
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
} | Java | ["3 3\n3 2 10\n1 2 10\n3 1 5", "4 5\n1 2 10\n1 3 10\n2 3 5\n4 2 15\n3 4 5"] | 2 seconds | ["1\n0\n1", "0\n0\n1\n1\n0"] | NoteIn the first test case, 10 flow units pass through path , and 5 flow units pass directly from source to sink: . | Java 7 | standard input | [
"sortings",
"dfs and similar"
] | f065e8c469a5a71a9ef602b6d8bfc9e2 | The first line of input contains two space-separated integers n and m (2ββ€βnββ€β2Β·105, nβ-β1ββ€βmββ€β2Β·105), the number of vertices and edges in the graph. The following m lines contain three space-separated integers ai, bi and ci (1ββ€βai,βbiββ€βn, aiββ βbi, 1ββ€βciββ€β104), which means that there is an undirected edge from ai to bi with flow volume ci. It is guaranteed that there are no two edges connecting the same vertices; the given graph is connected; a solution always exists. | 2,100 | Output m lines, each containing one integer di, which should be 0 if the direction of the i-th edge is aiβββbi (the flow goes from vertex ai to vertex bi) and should be 1 otherwise. The edges are numbered from 1 to m in the order they are given in the input. If there are several solutions you can print any of them. | standard output | |
PASSED | a35505748b2bdc32a5e18f14eb733b05 | train_002.jsonl | 1359732600 | Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet β it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.However, his max-flow algorithm seems to have a little flaw β it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.More formally. You are given an undirected graph. For each it's undirected edge (ai, bi) you are given the flow volume ci. You should direct all edges in such way that the following conditions hold: for each vertex v (1β<βvβ<βn), sum of ci of incoming edges is equal to the sum of ci of outcoming edges; vertex with number 1 has no incoming edges; the obtained directed graph does not have cycles. | 256 megabytes | import java.util.*;
import java.io.*;
public class FancyFence {
static String s = "4 5\n" +
"1 2 10\n" +
"1 3 10\n" +
"2 3 5\n" +
"4 2 15\n" +
"3 4 5";
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static int nextInt() {
try {
st.nextToken();
return (int) st.nval;
} catch (IOException ex) {
return 0;
}
}
public static void main(String[] args) {
int n = nextInt();
int m = nextInt();
ArrayList<ArrayList<Edge>> ar = new ArrayList<>();
for (int i=0;i<=n;i++){
ar.add(new ArrayList<Edge>());
}
int[] f = new int[n+1];
for (int c=0;c<m;c++){
int a = nextInt();
int b = nextInt();
int d = nextInt();
ar.get(a).add(new Edge(b, c, 0, d));
ar.get(b).add(new Edge(a, c, 1, d));
f[a]+=d;
f[b]+=d;
}
for (int i=1;i<=n;i++){
f[i]/=2;
}
ArrayList<Edge> so = ar.get(1);
Queue<ArrayList<Edge>> q = new LinkedList<>();
q.add(so);
int[] direction = new int[m];
boolean visited[] = new boolean[m];
while (!q.isEmpty()){
ArrayList<Edge> sv = q.poll();
for (int i=0;i<sv.size();i++){
Edge j = sv.get(i);
if (!visited[j.ca]) {
visited[j.ca] = true;
direction[j.ca] = j.da;
f[j.ba]-=j.ea;
if (j.ba!=n&&f[j.ba]==0){
q.add(ar.get(j.ba));
}
}
}
}
for (int i=0;i<m;i++){
System.out.println(direction[i]);
}
}
private static class Edge {
int ba,ca,da,ea;
Edge(int b,int c,int d,int e){
ba=b;ca=c;da=d;ea=e;
}
}
} | Java | ["3 3\n3 2 10\n1 2 10\n3 1 5", "4 5\n1 2 10\n1 3 10\n2 3 5\n4 2 15\n3 4 5"] | 2 seconds | ["1\n0\n1", "0\n0\n1\n1\n0"] | NoteIn the first test case, 10 flow units pass through path , and 5 flow units pass directly from source to sink: . | Java 7 | standard input | [
"sortings",
"dfs and similar"
] | f065e8c469a5a71a9ef602b6d8bfc9e2 | The first line of input contains two space-separated integers n and m (2ββ€βnββ€β2Β·105, nβ-β1ββ€βmββ€β2Β·105), the number of vertices and edges in the graph. The following m lines contain three space-separated integers ai, bi and ci (1ββ€βai,βbiββ€βn, aiββ βbi, 1ββ€βciββ€β104), which means that there is an undirected edge from ai to bi with flow volume ci. It is guaranteed that there are no two edges connecting the same vertices; the given graph is connected; a solution always exists. | 2,100 | Output m lines, each containing one integer di, which should be 0 if the direction of the i-th edge is aiβββbi (the flow goes from vertex ai to vertex bi) and should be 1 otherwise. The edges are numbered from 1 to m in the order they are given in the input. If there are several solutions you can print any of them. | standard output | |
PASSED | cdabf1d110898022d5dd63c95f27de8d | train_002.jsonl | 1359732600 | Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet β it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.However, his max-flow algorithm seems to have a little flaw β it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.More formally. You are given an undirected graph. For each it's undirected edge (ai, bi) you are given the flow volume ci. You should direct all edges in such way that the following conditions hold: for each vertex v (1β<βvβ<βn), sum of ci of incoming edges is equal to the sum of ci of outcoming edges; vertex with number 1 has no incoming edges; the obtained directed graph does not have cycles. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.TreeSet;
import java.lang.Integer;
import java.util.Stack;
public class flow_kp_java {
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static int nextInt() {
try {
st.nextToken();
return (int) st.nval;
} catch (IOException ex) {
return 0;
}
}
static double nextDouble() {
try {
st.nextToken();
return st.nval;
} catch (IOException ex) {
return 0;
}
}
static class Edge {
int b, c, d, i;
public Edge(int b, int c, int d, int i) {
this.b = b;
this.c = c;
this.d = d;
this.i = i;
}
}
public static void main(String[] args) {
int n = nextInt();
int m = nextInt();
ArrayList<ArrayList<Edge>> inc = new ArrayList<ArrayList<Edge>>();
for (int i = 0; i <= n; i++) {
inc.add(new ArrayList<Edge>());
}
int[] half = new int[200001];
int[] current = new int[200001];
boolean[] visited = new boolean[200001];
int[] direction = new int[200005];
Stack<Integer> q = new Stack<Integer>();
int a, b, c;
for (int i = 0; i < m; i++) {
a = nextInt();
b = nextInt();
c = nextInt();
inc.get(a).add(new Edge(b, c, 0, i));
inc.get(b).add(new Edge(a, c, 1, i));
current[a] += c;
current[b] += c;
}
for (int i = 0; i < n; i++) {
half[i] = current[i] / 2;
}
visited[1] = true;
q.push(1);
while (!q.empty()) {
int next = q.pop();
for (Edge e : inc.get(next)) {
if (!visited[e.b]) {
direction[e.i] = e.d;
current[e.b] -= e.c;
if (current[e.b] == half[e.b] && e.b != n) {
visited[e.b] = true;
q.push(e.b);
}
}
}
}
for (int i = 0; i < m; i++) {
System.out.println(direction[i]);
}
}
} | Java | ["3 3\n3 2 10\n1 2 10\n3 1 5", "4 5\n1 2 10\n1 3 10\n2 3 5\n4 2 15\n3 4 5"] | 2 seconds | ["1\n0\n1", "0\n0\n1\n1\n0"] | NoteIn the first test case, 10 flow units pass through path , and 5 flow units pass directly from source to sink: . | Java 7 | standard input | [
"sortings",
"dfs and similar"
] | f065e8c469a5a71a9ef602b6d8bfc9e2 | The first line of input contains two space-separated integers n and m (2ββ€βnββ€β2Β·105, nβ-β1ββ€βmββ€β2Β·105), the number of vertices and edges in the graph. The following m lines contain three space-separated integers ai, bi and ci (1ββ€βai,βbiββ€βn, aiββ βbi, 1ββ€βciββ€β104), which means that there is an undirected edge from ai to bi with flow volume ci. It is guaranteed that there are no two edges connecting the same vertices; the given graph is connected; a solution always exists. | 2,100 | Output m lines, each containing one integer di, which should be 0 if the direction of the i-th edge is aiβββbi (the flow goes from vertex ai to vertex bi) and should be 1 otherwise. The edges are numbered from 1 to m in the order they are given in the input. If there are several solutions you can print any of them. | standard output | |
PASSED | b4a689271adb4598f6bd87d14ccf9f80 | train_002.jsonl | 1359732600 | Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet β it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.However, his max-flow algorithm seems to have a little flaw β it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.More formally. You are given an undirected graph. For each it's undirected edge (ai, bi) you are given the flow volume ci. You should direct all edges in such way that the following conditions hold: for each vertex v (1β<βvβ<βn), sum of ci of incoming edges is equal to the sum of ci of outcoming edges; vertex with number 1 has no incoming edges; the obtained directed graph does not have cycles. | 256 megabytes | import java.io.IOException;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Collection;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author George Marcus
*/
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);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int M = in.nextInt();
ArrayList<Edge>[] G = new ArrayList[N + 1];
int[] F = new int[N + 1];
int[] D = new int[M];
boolean[] v = new boolean[N + 1];
for(int i = 1; i <= N; i++)
G[i] = new ArrayList<Edge>();
for(int i = 0; i < M; i++) {
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
G[a].add(new Edge(b, c, i, 1));
G[b].add(new Edge(a, c, i, 0));
F[a] += c;
F[b] += c;
D[i] = -1;
}
for(int i = 1; i <= N; i++)
F[i] /= 2;
Queue<Integer> Q = new LinkedList<Integer>();
Q.add(1);
v[1] = true;
while(!Q.isEmpty()) {
int p = Q.remove();
for(Edge e : G[p]) {
if(D[e.id] == -1) {
D[e.id] = e.dir;
F[e.to] -= e.flow;
}
if(e.to != N && !v[e.to] && F[e.to] == 0) {
v[e.to ] = true;
Q.add(e.to);
}
}
}
for(int i = 0; i < M; i++)
out.println(1 - D[i]);
}
private class Edge {
public int to;
public int flow;
public int id;
public int dir;
private Edge(int to, int flow, int id, int dir) {
this.to = to;
this.flow = flow;
this.id = id;
this.dir = dir;
}
}
}
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 nextInt() {
return Integer.parseInt(nextString());
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
| Java | ["3 3\n3 2 10\n1 2 10\n3 1 5", "4 5\n1 2 10\n1 3 10\n2 3 5\n4 2 15\n3 4 5"] | 2 seconds | ["1\n0\n1", "0\n0\n1\n1\n0"] | NoteIn the first test case, 10 flow units pass through path , and 5 flow units pass directly from source to sink: . | Java 7 | standard input | [
"sortings",
"dfs and similar"
] | f065e8c469a5a71a9ef602b6d8bfc9e2 | The first line of input contains two space-separated integers n and m (2ββ€βnββ€β2Β·105, nβ-β1ββ€βmββ€β2Β·105), the number of vertices and edges in the graph. The following m lines contain three space-separated integers ai, bi and ci (1ββ€βai,βbiββ€βn, aiββ βbi, 1ββ€βciββ€β104), which means that there is an undirected edge from ai to bi with flow volume ci. It is guaranteed that there are no two edges connecting the same vertices; the given graph is connected; a solution always exists. | 2,100 | Output m lines, each containing one integer di, which should be 0 if the direction of the i-th edge is aiβββbi (the flow goes from vertex ai to vertex bi) and should be 1 otherwise. The edges are numbered from 1 to m in the order they are given in the input. If there are several solutions you can print any of them. | standard output | |
PASSED | 5b3d1d8310900ec66ea8ec6ea3b4027c | train_002.jsonl | 1366385400 | There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (iβ+β1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (iβ-β1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s,βt by looking at the footprints. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int s = 0;
int t = 0;
int r = 0;
int l = 0;
String line = cin.next();
char[] path = line.toCharArray();
for (int i = 0; i < path.length; i++) {
if (path[i] == 'R') r++;
if (path[i] == 'L') l++;
}
if (l == 0) {
for (int i = 0; i < path.length; i++) {
if (path[i] == 'R') {
s = (i + 1);
break;
}
}
for (int i = 0; i < path.length; i++) {
if (path[i] == 'R') t = (i + 2);
}
} else if (r == 0) {
for (int i = 0; i < path.length; i++) {
if (path[i] == 'L') {
t = i;
break;
}
}
for (int i = 0; i < path.length; i++) {
if (path[i] == 'L') {
s = (i + 1);
}
}
} else {
for (int i = 0; i < path.length; i++) {
if (path[i] == 'R') {
s = (i + 1);
break;
}
}
for (int i = 0; i < path.length; i++) {
if (path[i] == 'L') {
t = i;
break;
}
}
}
System.out.println(s + " " + t);
}
}
| Java | ["9\n..RRLL...", "11\n.RRRLLLLL.."] | 1 second | ["3 4", "7 5"] | NoteThe first test sample is the one in the picture. | Java 7 | standard input | [
"implementation",
"greedy"
] | 3053cba2426ebd113fcd70a9b026dad0 | The first line of the input contains integer n (3ββ€βnββ€β1000). The second line contains the description of the road β the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. | 1,300 | Print two space-separated integers β the values of s and t. If there are several possible solutions you can print any of them. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.