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 | 358e8220a0ac06a7979090e1bd066e21 | train_004.jsonl | 1359732600 | Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold: thread x is not updated (it has no new messages); the list order 1, 2, ..., n changes to a1, a2, ..., an. | 256 megabytes | import java.io.*;
import java.util.*;
public class Multithreading {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(f.readLine());
int[] a = new int[n];
StringTokenizer st = new StringTokenizer(f.readLine());
for (int i = 0; i < n; i++)
a[i] = Integer.parseInt(st.nextToken());
int index = n-1;
while (index > 0 && a[index-1] < a[index])
index--;
System.out.println(index);
}
} | Java | ["5\n5 2 1 3 4", "3\n1 2 3", "4\n4 3 2 1"] | 2 seconds | ["2", "0", "3"] | NoteIn the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.In the second test case, there may be no new messages at all, since the thread order hasn't changed.In the third test case, only thread 1 can contain no new messages. | Java 7 | standard input | [
"data structures",
"implementation",
"greedy"
] | 310a0596c0a459f496b8d6b57676d25e | The first line of input contains an integer n, the number of threads (1ββ€βnββ€β105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1ββ€βaiββ€βn) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct. | 1,400 | Output a single integer β the number of threads that surely contain a new message. | standard output | |
PASSED | cdcce54bd1aca29675cdaabdaf3fce75 | train_004.jsonl | 1359732600 | Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold: thread x is not updated (it has no new messages); the list order 1, 2, ..., n changes to a1, a2, ..., an. | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
public class B {
public static void main(String [] args){
Scanner cin = new Scanner(System.in);
PrintWriter cout = new PrintWriter(System.out);
int N = cin.nextInt();
int []a = new int[N];
for (int i=0;i<N;++i)a[i] = cin.nextInt();
int i = N - 1;
while (i > 0 && a[i] > a[i-1])i--;
cout.println(i);
cout.flush();
}
} | Java | ["5\n5 2 1 3 4", "3\n1 2 3", "4\n4 3 2 1"] | 2 seconds | ["2", "0", "3"] | NoteIn the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.In the second test case, there may be no new messages at all, since the thread order hasn't changed.In the third test case, only thread 1 can contain no new messages. | Java 7 | standard input | [
"data structures",
"implementation",
"greedy"
] | 310a0596c0a459f496b8d6b57676d25e | The first line of input contains an integer n, the number of threads (1ββ€βnββ€β105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1ββ€βaiββ€βn) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct. | 1,400 | Output a single integer β the number of threads that surely contain a new message. | standard output | |
PASSED | 1dd7fb2d3b17c9fb919ced40b3a9a749 | train_004.jsonl | 1359732600 | Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold: thread x is not updated (it has no new messages); the list order 1, 2, ..., n changes to a1, a2, ..., an. | 256 megabytes | import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.File;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = IOUtils.readIntArray(in, n);
for (int i = n - 2; i >= 0; --i)
if (a[i] > a[i + 1]) {
out.print(i + 1);
return;
}
out.print(0);
}
}
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 f) {
br = new BufferedReader(new InputStreamReader(f));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void close() {
writer.close();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.nextInt();
return array;
}
}
| Java | ["5\n5 2 1 3 4", "3\n1 2 3", "4\n4 3 2 1"] | 2 seconds | ["2", "0", "3"] | NoteIn the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.In the second test case, there may be no new messages at all, since the thread order hasn't changed.In the third test case, only thread 1 can contain no new messages. | Java 7 | standard input | [
"data structures",
"implementation",
"greedy"
] | 310a0596c0a459f496b8d6b57676d25e | The first line of input contains an integer n, the number of threads (1ββ€βnββ€β105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1ββ€βaiββ€βn) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct. | 1,400 | Output a single integer β the number of threads that surely contain a new message. | standard output | |
PASSED | e44fdd9cf2b962ddab0b28078f42a8d9 | train_004.jsonl | 1359732600 | Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold: thread x is not updated (it has no new messages); the list order 1, 2, ..., n changes to a1, a2, ..., an. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Scanner;
public class B_270_Multithreading {
public void Run() throws NumberFormatException, IOException {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int n = sc.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int i = n - 1, count = n - 1;
while (i > 0 && a[i] > a[i - 1]) {
count--;
i--;
}
System.out.println(count);
}
public static void main(String[] args) throws IOException {
new B_270_Multithreading().Run();
}
}
| Java | ["5\n5 2 1 3 4", "3\n1 2 3", "4\n4 3 2 1"] | 2 seconds | ["2", "0", "3"] | NoteIn the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.In the second test case, there may be no new messages at all, since the thread order hasn't changed.In the third test case, only thread 1 can contain no new messages. | Java 7 | standard input | [
"data structures",
"implementation",
"greedy"
] | 310a0596c0a459f496b8d6b57676d25e | The first line of input contains an integer n, the number of threads (1ββ€βnββ€β105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1ββ€βaiββ€βn) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct. | 1,400 | Output a single integer β the number of threads that surely contain a new message. | standard output | |
PASSED | 84a1a276c52e82f9ec8c9fbdbcdaf4da | train_004.jsonl | 1359732600 | Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold: thread x is not updated (it has no new messages); the list order 1, 2, ..., n changes to a1, a2, ..., an. | 256 megabytes | //package Div2_165;
import java.util.Scanner;
public class B_Multithreading {
/**
* 2013/02/02
* codeforces #165(Div.2)
* B.Multithreading
* Wrong Answer
*/
static Scanner in = new Scanner(System.in);
public static void run() {
int n = in.nextInt();
int[] A = new int[n];
int out=0;
for(int a=0;a<n;a++) A[a] = in.nextInt();
for(int i=n-1;i>0;i--){
if(A[i]<A[i-1]){
out = i;
break;
}
}
System.out.println(out);
}
public static void main(String[] args) {
B_Multithreading.run();
}
}
| Java | ["5\n5 2 1 3 4", "3\n1 2 3", "4\n4 3 2 1"] | 2 seconds | ["2", "0", "3"] | NoteIn the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.In the second test case, there may be no new messages at all, since the thread order hasn't changed.In the third test case, only thread 1 can contain no new messages. | Java 7 | standard input | [
"data structures",
"implementation",
"greedy"
] | 310a0596c0a459f496b8d6b57676d25e | The first line of input contains an integer n, the number of threads (1ββ€βnββ€β105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1ββ€βaiββ€βn) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct. | 1,400 | Output a single integer β the number of threads that surely contain a new message. | standard output | |
PASSED | 025c0262c5ecf6088fc22e00f86d753a | train_004.jsonl | 1310731200 | Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Solution {
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
Scanner sc = new Scanner(inp);
// input data
int[] cnt = new int[28];
int[] x1 = new int[28];
int[] y1 = new int[28];
int[] x2 = new int[28];
int[] y2 = new int[28];
int sqCnt = 0;
int[][] sqId;
int n, m;
boolean[][] have;
void inputData() {
n = sc.nextInt();
m = sc.nextInt();
String[] map = new String[n];
for (int i=0; i<n; i++)
map[i] = sc.next();
have = new boolean[n][m];
sqId = new int[n][m];
for (int i=0; i<n; i++)
for (int j=0; j<m; j++) {
have[i][j] = map[i].charAt(j) != '.';
if (have[i][j]) {
char c = map[i].charAt(j);
int id = -1;
if (c=='A') id = 26; else if (c=='B') id = 27;
else id = c-'a';
cnt[id]++;
if (cnt[id] == 1) {
x1[id] = i; y1[id] = j;
} else {
x2[id] = i; y2[id] = j;
}
}
}
for (int i=0; i<n; i++)
Arrays.fill(sqId[i], -1);
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
if (have[i][j] && sqId[i][j] == -1) {
sqId[i][j] = sqCnt;
sqId[i+1][j] = sqCnt;
sqId[i][j+1] = sqCnt;
sqId[i+1][j+1] = sqCnt++;
}
}
// intermediate
int res = 0;
int[] cntColor = new int[7];
int[] colorForSq = new int[14];
char[][] sol;
void go(int pos, int nextColor) {
if (pos==14) {
boolean[][] memo = new boolean[7][7];
for (int i=0; i<28; i++) {
int ca = colorForSq[sqId[x1[i]][y1[i]]];
int cb = colorForSq[sqId[x2[i]][y2[i]]];
if (ca<cb) {int tmp=ca; ca=cb; cb=tmp;}
if (memo[ca][cb])
return;
memo[ca][cb] = true;
}
res++;
if (res==1) {
sol = new char[n][m];
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
if (have[i][j]) {
sol[i][j] = (char)('0'+colorForSq[sqId[i][j]]);
} else sol[i][j] = '.';
}
return;
}
for (int i=0; i < nextColor; i++)
if (cntColor[i] < 2) {
colorForSq[pos] = i;
cntColor[i]++;
go(pos+1, nextColor);
cntColor[i]--;
}
if (nextColor < 7) {
colorForSq[pos] = nextColor;
cntColor[nextColor]++;
go(pos+1, nextColor+1);
cntColor[nextColor]--;
}
}
void solve() {
go(0, 0);
}
// output data
void writeData() {
System.out.println(5040 * res);
for (int i=0; i<n; i++)
System.out.println(new String(sol[i]));
}
// ================================================== //
void solveAlternative() {
}
// ================================================== //
static void solveTask() throws Exception {
Solution sol = new Solution();
sol.inputData();
sol.solve();
sol.writeData();
}
static void stressTest() {
Random rnd = new Random();
int it = 0;
while (true) {
it++;
System.out.println("testing case #" + it);
Solution sol = new Solution();
// generate test case
Solution sol1 = new Solution();
// copy test case
sol.solve();
sol1.solveAlternative();
// compare answers
}
}
public static void main(String[] args) throws Exception {
solveTask();
// stressTest()
}
} | Java | ["8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy"] | 0.5 second | ["10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344"] | null | Java 6 | standard input | [
"implementation",
"brute force"
] | c5e83c717c4bb3db0a0da7436b77f123 | The first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists. | 2,400 | Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different. | standard output | |
PASSED | fee37ecaa5859414696fb4c5d2986953 | train_004.jsonl | 1310731200 | Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
import static java.lang.Math.*;
public class Sol implements Runnable {
final int COUNT = 28;
int n, m;
char [][] b;
int [][] anotherX, anotherY;
int [] ansColors;
int ans = 0;
void go(int [][] board, int [] left, int [] sx, int [] sy, int square, boolean [][] used) {
if (square == COUNT / 2) {
ans++;
if (ansColors == null) {
ansColors = new int[COUNT / 2];
for (int i = 0; i < COUNT / 2; i++) {
ansColors[i] = board[sy[i]][sx[i]];
}
}
return;
}
outer:
for (int color = 0; color < 7; color++) {
if (left[color] == 0 || (color > 0 && left[color - 1] == 2)) continue;
boolean ok = true;
int cnt = 0;
int [] u1 = new int[4], u2 = new int[4];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
int x = sx[square] + j;
int y = sy[square] + i;
board[y][x] = color;
int ax = anotherX[y][x];
int ay = anotherY[y][x];
int ac = board[ay][ax];
if (ac != -1) {
if (used[color][ac]) {
ok = false;
continue;
}
used[color][ac] = true;
used[ac][color] = true;
u1[cnt] = color;
u2[cnt++] = ac;
}
}
}
if (ok) {
left[color]--;
go(board, left, sx, sy, square + 1, used);
left[color]++;
}
for (int i = 0; i < cnt; i++) {
used[u1[i]][u2[i]] = false;
used[u2[i]][u1[i]] = false;
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
int x = sx[square] + j;
int y = sy[square] + i;
board[y][x] = -1;
}
}
}
}
void solve() throws Exception {
n = nextInt();
m = nextInt();
b = new char[n][];
for (int i = 0; i < n; i++) {
b[i] = nextToken().toCharArray();
}
anotherX = new int[n][m];
anotherY = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (b[i][j] != '.') {
if (i + 1 < n && b[i][j] == b[i + 1][j]) {
anotherX[i][j] = j;
anotherY[i][j] = i + 1;
anotherX[i + 1][j] = j;
anotherY[i + 1][j] = i;
} else
if (j + 1 < m && b[i][j] == b[i][j + 1]) {
anotherX[i][j] = j + 1;
anotherY[i][j] = i;
anotherX[i][j + 1] = j;
anotherY[i][j + 1] = i;
}
}
}
}
int cnt = 0;
int [] sx = new int[COUNT / 2];
int [] sy = new int[COUNT / 2];
boolean [][] used = new boolean [n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (used[i][j]) continue;
if (b[i][j] != '.') {
used[i][j] = used[i + 1][j] = used[i][j + 1] = used[i + 1][j + 1] = true;
sx[cnt] = j;
sy[cnt++] = i;
}
}
}
int [][] board = new int[n][m];
for (int i = 0; i < n; i++) {
Arrays.fill(board[i], -1);
}
int [] left = new int[7];
Arrays.fill(left, 2);
go(board, left, sx, sy, 0, new boolean[n][m]);
out.println(ans * 5040);
for (int i = 0; i < COUNT / 2; i++) {
int x = sx[i];
int y = sy[i];
b[y][x] = b[y + 1][x] = b[y][x + 1] = b[y + 1][x + 1] = (char)(ansColors[i] + '0');
}
for (int i = 0; i < n; i++) {
out.println(b[i]);
}
}
public static void main(String[] args) {
new Thread(new Sol()).start();
}
public void run() {
try {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
StringTokenizer tokenizer = new StringTokenizer("");
BufferedReader in;
PrintWriter out;
long time;
void sTime() {
time = System.currentTimeMillis();
}
long gTime() {
return System.currentTimeMillis() - time;
}
void gMemory() {
debug("Memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + " kb");
}
public void debug(Object o) {
System.err.println(o);
}
boolean seekForToken() {
while (!tokenizer.hasMoreTokens()) {
String s = null;
try {
s = in.readLine();
} catch (Exception e) {
e.printStackTrace();
}
if (s == null)
return false;
tokenizer = new StringTokenizer(s);
}
return true;
}
String nextToken() {
return seekForToken() ? tokenizer.nextToken() : null;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
BigInteger nextBig() {
return new BigInteger(nextToken());
}
}
| Java | ["8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy"] | 0.5 second | ["10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344"] | null | Java 6 | standard input | [
"implementation",
"brute force"
] | c5e83c717c4bb3db0a0da7436b77f123 | The first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists. | 2,400 | Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different. | standard output | |
PASSED | db83be64411cccbcac5ece97721ecbc6 | train_004.jsonl | 1310731200 | Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
boolean[][] c;
boolean outputed;
int[][] a;
int calc(int[] sq,int color){
int result=0;
if(color!=7){
int[] sq1=new int[14];
for(int j=0;j<14;j++){
sq1[j]=sq[j];
}
for(int i=0;i<14;i++){
if(sq1[i]==-1){
sq1[i]=color;
break;
}
}
for(int i=0;i<14;i++){
if(sq1[i]==-1){
sq1[i]=color;
result+=calc(sq1,color+1);
sq1[i]=-1;
}
}
}
else{
boolean[] b=new boolean[56];
for(int i=0;i<56;i++)b[i]=false;
boolean good=true;
for(int i=0;i<c.length&&good;i++)
for(int j=i;j<c[i].length;j++){
if(c[i][j]) {
int q=Math.max(sq[i], sq[j]);
int w=Math.min(sq[i], sq[j]);
int v=w*7+q;
if(b[v]){
good=false;
break;
}
else
b[v]=true;
}
}
if(good) {
result=1;
if(!outputed){
outputed=true;
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
if(a[i][j]!=-1)a[i][j]=sq[a[i][j]];
}
}
}
}
}
return result;
}
void solve() throws IOException {
int n=nextInt();
int m=nextInt();
String[] field=new String[n];
for(int i=0;i<n;i++)
field[i]=nextToken();
a=new int[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
a[i][j]=-1;
int k=0;
for(int i=0;i<n-1;i++){
for(int j=0;j<m-1;j++){
if(a[i][j]==-1&&field[i].charAt(j)!='.')
a[i][j]=a[i+1][j]=a[i][j+1]=a[i+1][j+1]=k++;
}
}
c=new boolean[14][14];
for(int i=0;i<14;i++)
for(int j=0;j<14;j++)
c[i][j]=false;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++){
if(field[i].charAt(j)!='.'){
if(i<n-1&&field[i].charAt(j)==field[i+1].charAt(j))
c[a[i][j]][a[i+1][j]]=c[a[i+1][j]][a[i][j]]=true;
if(j<m-1&&field[i].charAt(j)==field[i].charAt(j+1))
c[a[i][j]][a[i][j+1]]=c[a[i][j+1]][a[i][j]]=true;
}
}
int[] sq=new int[14];
for(int i=0;i<14;i++)sq[i]=-1;
out.println((long)calc(sq,0)*5040);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)
if(a[i][j]==-1)
out.print('.');
else
out.print(a[i][j]);
out.println();
}
}
public static void main(String[] args) throws IOException {
new Main().run();
}
void run() throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
reader.close();
out.flush();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy"] | 0.5 second | ["10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344"] | null | Java 6 | standard input | [
"implementation",
"brute force"
] | c5e83c717c4bb3db0a0da7436b77f123 | The first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists. | 2,400 | Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different. | standard output | |
PASSED | 20efb95d072af4d0434de7354bb6baff | train_004.jsonl | 1310731200 | Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round. | 256 megabytes | import java.util.InputMismatchException;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
import java.util.Iterator;
import java.util.Comparator;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.NavigableSet;
import java.util.Map;
import java.util.Collections;
import java.util.HashMap;
import java.util.Collection;
import java.util.ArrayList;
import java.io.*;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new TaskA();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(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 void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
abstract class ReadOnlyIterator<T> implements Iterator<T> {
public final void remove() {
throw new UnsupportedOperationException();
}
}
abstract class AbstractSequence<T> implements Sequence<T> {
protected void checkIndices(int from, int to, int size) {
if (from < 0 || to < 0 || from > size || to > size || from > to)
throw new IndexOutOfBoundsException();
}
public Iterator<T> iterator() {
return new ReadOnlyIterator<T>() {
private int index = 0;
public boolean hasNext() {
return index != size();
}
public T next() {
if (!hasNext())
throw new NoSuchElementException();
return get(index++);
}
};
}
protected class SubSequence implements Sequence<T> {
protected final int from;
protected final int to;
public SubSequence(int from, int to) {
this.from = from;
this.to = to;
}
public int size() {
return to - from;
}
public T get(int index) {
if (index < 0 || index >= size())
throw new IndexOutOfBoundsException();
return AbstractSequence.this.get(from + index);
}
public Iterator<T> iterator() {
return new ReadOnlyIterator<T>() {
private int index = from;
public boolean hasNext() {
return index != to;
}
public T next() {
if (index == to)
throw new NoSuchElementException();
return AbstractSequence.this.get(index++);
}
};
}
}
}
abstract class AbstractWritableSequence<T> extends AbstractSequence<T> implements WritableSequence<T> {
public WritableSequence<T> subSequence(int from) {
return subSequence(from, size());
}
public WritableSequence<T> subSequence(int from, int to) {
int size = size();
if (from < 0)
from += size;
if (to < 0)
to += size;
checkIndices(from, to, size);
return new WritableSubSequence(from, to);
}
protected class WritableSubSequence extends SubSequence implements WritableSequence<T>{
public WritableSubSequence(int from, int to) {
super(from, to);
}
public void set(int index, T value) {
if (index < 0 || index >= size())
throw new IndexOutOfBoundsException();
AbstractWritableSequence.this.set(from + index, value);
}
public WritableSequence<T> subSequence(int from) {
return subSequence(from, to);
}
public WritableSequence<T> subSequence(int from, int to) {
int size = size();
if (from < 0)
from += size;
if (to < 0)
to += size;
checkIndices(from, to, size);
return new WritableSubSequence(from + this.from, to + this.from);
}
}
}
abstract class ArrayWrapper<T> extends AbstractWritableSequence<T> {
public static WritableSequence<Integer> wrap(int...array) {
return new IntArrayWrapper(array);
}
protected static class IntArrayWrapper extends ArrayWrapper<Integer> {
protected final int[] array;
protected IntArrayWrapper(int[] array) {
this.array = array;
}
public int size() {
return array.length;
}
public Integer get(int index) {
return array[index];
}
public void set(int index, Integer value) {
array[index] = value;
}
}
}
interface Sequence<T> extends Iterable<T> {
public int size();
public T get(int index);
}
class SequenceUtils {
public static<T extends Comparable<T>> boolean nextPermutation(WritableSequence<T> sequence) {
for (int i = sequence.size() - 2; i >= 0; i--) {
if (sequence.get(i).compareTo(sequence.get(i + 1)) < 0) {
int index = i + 1;
for (int j = i + 2; j < sequence.size(); j++) {
if (sequence.get(i).compareTo(sequence.get(j)) >= 0)
break;
else
index = j;
}
T temp = sequence.get(i);
sequence.set(i, sequence.get(index));
sequence.set(index, temp);
sort(sequence.subSequence(i + 1));
return true;
}
}
return false;
}
public static<T extends Comparable<T>> WritableSequence<T> sort(WritableSequence<T> sequence) {
return sort(sequence, null);
}
public static<T> WritableSequence<T> sort(WritableSequence<T> sequence, Comparator<? super T> comparator) {
makeHeap(sequence, comparator);
for (int i = sequence.size() - 1; i > 0; i--) {
T temp = sequence.get(0);
sequence.set(0, sequence.get(i));
sequence.set(i, temp);
siftDown(sequence, 0, i, comparator);
}
return sequence;
}
private static<T> WritableSequence<T> makeHeap(WritableSequence<T> sequence, Comparator<? super T> comparator) {
int length = sequence.size();
for (int i = length / 2 - 1; i >= 0; i--)
siftDown(sequence, i, length, comparator);
return sequence;
}
private static<T> void siftDown(WritableSequence<T> sequence, int start, int end, Comparator<? super T> comparator) {
int root = start;
while (2 * root + 1 < end) {
int childIndex = 2 * root + 1;
if (childIndex + 1 < end && compare(sequence.get(childIndex), sequence.get(childIndex + 1), comparator) < 0)
childIndex++;
if (compare(sequence.get(childIndex), sequence.get(root), comparator) <= 0)
return;
T temp = sequence.get(root);
sequence.set(root, sequence.get(childIndex));
sequence.set(childIndex, temp);
root = childIndex;
}
}
private static<T> int compare(T first, T second, Comparator<? super T> comparator) {
if (comparator != null)
return comparator.compare(first, second);
//noinspection unchecked
return ((Comparable<? super T>)first).compareTo(second);
}
}
interface WritableSequence<T> extends Sequence<T> {
public void set(int index, T value);
public WritableSequence<T> subSequence(int from);
}
class IOUtils {
public static char[] readCharArray(InputReader in, int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++)
array[i] = in.readCharacter();
return array;
}
public static char[][] readTable(InputReader in, int rowCount, int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readCharArray(in, columnCount);
return table;
}
}
class IntegerUtils {
public static long factorial(int n) {
long result = 1;
for (int i = 2; i <= n; i++)
result *= i;
return result;
}
}
class TaskA implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int rowCount = in.readInt();
int columnCount = in.readInt();
char[][] table = IOUtils.readTable(in, rowCount, columnCount);
int[][] index = new int[rowCount][columnCount];
boolean[][] graph = new boolean[15][15];
int color = 1;
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < columnCount; j++) {
if (table[i][j] != '.' && index[i][j] == 0) {
index[i][j] = color;
index[i + 1][j] = color;
index[i][j + 1] = color;
index[i + 1][j + 1] = color++;
}
}
}
for (int i = 0; i < 28; i++) {
char symbol;
if (i < 26)
symbol = (char) ('a' + i);
else
symbol = (char) ('A' + i - 26);
outer:
for (int j = 0; j < rowCount; j++) {
for (int k = 0; k < columnCount; k++) {
if (table[j][k] == symbol) {
int otherRow = j;
int otherColumn = k;
if (j + 1 < rowCount && table[j + 1][k] == symbol)
otherRow = j + 1;
else
otherColumn = k + 1;
graph[index[j][k]][index[otherRow][otherColumn]] = graph[index[otherRow][otherColumn]][index[j][k]] = true;
break outer;
}
}
}
}
int nonDoubleCount = 0;
for (int i = 1; i <= 14; i++) {
if (!graph[i][i])
nonDoubleCount++;
}
int[] doubleIndices = new int[14 - nonDoubleCount];
int[] nonDoubleIndices = new int[nonDoubleCount];
int doubleIndex = 0;
int nonDoubleIndex = 0;
for (int i = 1; i <= 14; i++) {
if (graph[i][i])
doubleIndices[doubleIndex++] = i;
else
nonDoubleIndices[nonDoubleIndex++] = i;
}
long answer = 0;
WritableSequence<Integer> permutation = ArrayWrapper.wrap(nonDoubleIndices);
do {
boolean good = true;
for (int i = 7; i < nonDoubleIndex - 1; i++) {
if (nonDoubleIndices[i] > nonDoubleIndices[i + 1])
good = false;
}
for (int i = 0; i < 7 && good; i++) {
int firstI = i >= doubleIndex ? nonDoubleIndices[7 + i - doubleIndex] : doubleIndices[i];
int secondI = nonDoubleIndices[i];
if (i >= doubleIndex && firstI > secondI) {
good = false;
break;
}
for (int j = 0; j < 7 && good; j++) {
int firstJ = j >= doubleIndex ? nonDoubleIndices[7 + j - doubleIndex] : doubleIndices[j];
int secondJ = nonDoubleIndices[j];
if (!graph[firstI][firstJ] && !graph[firstI][secondJ] && !graph[secondI][firstJ] && !graph[secondI][secondJ])
good = false;
}
}
if (good) {
if (answer == 0) {
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < columnCount; j++) {
if (table[i][j] == '.')
continue;
for (int k = 0; k < doubleIndex; k++) {
if (index[i][j] == doubleIndices[k]) {
table[i][j] = (char) ('0' + k);
break;
}
}
for (int k = 0; k < nonDoubleIndex; k++) {
if (index[i][j] == nonDoubleIndices[k]) {
if (k < 7)
table[i][j] = (char) ('0' + k);
else
table[i][j] = (char) ('0' + doubleIndex + k - 7);
break;
}
}
}
}
}
answer++;
}
} while (SequenceUtils.nextPermutation(permutation));
answer *= IntegerUtils.factorial(7);
out.println(answer);
for (char[] row : table)
out.println(row);
}
}
| Java | ["8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy"] | 0.5 second | ["10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344"] | null | Java 6 | standard input | [
"implementation",
"brute force"
] | c5e83c717c4bb3db0a0da7436b77f123 | The first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists. | 2,400 | Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different. | standard output | |
PASSED | 3832f4c7c6a70477c50860a832ffe563 | train_004.jsonl | 1310731200 | Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class A implements Runnable {
static final int[] DX = { 1, 0, -1, 0 };
static final int[] DY = { 0, 1, 0, -1 };
void solve() {
long time = System.currentTimeMillis();
n = nextInt();
m = nextInt();
c = new char[n][m];
for (int i = 0; i < n; i++) {
c[i] = nextToken().toCharArray();
}
w = new int[n][m];
for (int i = 0; i < n; i++) {
Arrays.fill(w[i], -1);
}
char[][] d = new char[n][];
for (int i = 0; i < n; i++) {
d[i] = c[i].clone();
}
int nextOne = 0;
blockX = new int[ALL_BLOCKS];
blockY = new int[ALL_BLOCKS];
while (true) {
boolean found = false;
all: for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (d[i][j] != '.') {
if (i + 1 >= n || j + 1 >= m || d[i + 1][j] == '.'
|| d[i][j + 1] == '.' || d[i + 1][j + 1] == '.') {
throw new AssertionError();
}
w[i][j] = w[i + 1][j] = w[i][j + 1] = w[i + 1][j + 1] = nextOne;
d[i][j] = d[i + 1][j] = d[i][j + 1] = d[i + 1][j + 1] = '.';
blockX[nextOne] = i;
blockY[nextOne] = j;
found = true;
break all;
}
}
}
if (!found) {
break;
}
nextOne++;
}
boolean[][] hasEdge;
hasEdge = new boolean[ALL_BLOCKS][ALL_BLOCKS];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (c[i][j] == '.') {
continue;
}
for (int dir = 0; dir < 4; dir++) {
int x = i + DX[dir];
int y = j + DY[dir];
if (x < 0 || y < 0 || x >= n || y >= m
|| c[x][y] != c[i][j]) {
continue;
}
hasEdge[w[x][y]][w[i][j]] = hasEdge[w[i][j]][w[x][y]] = true;
}
}
}
edges = new int[ALL_BLOCKS][];
for (int i = 0; i < ALL_BLOCKS; i++) {
int cnt = 0;
for (int j = 0; j <= i; j++) {
if (hasEdge[i][j]) {
cnt++;
}
}
edges[i] = new int[cnt];
for (int j = 0, k = 0; j <= i; j++) {
if (hasEdge[i][j]) {
edges[i][k++] = j;
}
}
}
color = new int[nextOne];
Arrays.fill(color, -1);
out.println(go(0));
for (int i = 0; i < n; i++) {
out.println(new String(answer[i]));
}
System.err.println(System.currentTimeMillis() - time);
}
static int[][] edges;
final static int ALL_BLOCKS = 14;
static int[] chosen = new int[7];
static boolean[][] was = new boolean[7][7];
static int[] blockX;
static int[] blockY;
final static int[] OFFSET_X = { 0, 0, 1, 1 };
final static int[] OFFSET_Y = { 0, 1, 0, 1 };
static int n;
static int m;
static char[][] c;
static int[] color;
static int[][] w;
static char[][] answer;
static void check() {
for (int i = 0; i < 7; i++) {
for (int j = i; j < 7; j++) {
if (!was[i][j]) {
System.err.println(i + " " + j);
System.err.println(Arrays.toString(color));
throw new AssertionError();
}
}
}
}
static int go(int curBlock) {
if (curBlock == ALL_BLOCKS) {
if (answer == null) {
answer = new char[n][m];
for (int i = 0; i < n; i++) {
Arrays.fill(answer[i], '.');
}
for (int i = 0; i < ALL_BLOCKS; i++) {
for (int j = 0; j < 4; j++) {
answer[blockX[i] + OFFSET_X[j]][blockY[i] + OFFSET_Y[j]] = (char) (color[i] + '0');
}
}
}
return 1;
}
int ret = 0;
for (int i = 0; i < chosen.length; i++) {
if (curBlock == 0 && i > 0) {
ret *= 42;
break;
}
if (curBlock == 1 && i > 1) {
break;
}
if (chosen[i] == 2) {
continue;
}
color[curBlock] = i;
if (!check(curBlock)) {
color[curBlock] = -1;
continue;
}
chosen[i]++;
process(curBlock, true);
ret += go(curBlock + 1);
process(curBlock, false);
chosen[i]--;
color[curBlock] = -1;
}
return ret;
}
static boolean check(int curBlock) {
int colorWas = 0;
for (int j : edges[curBlock]) {
int c1 = color[j];
int c2 = color[curBlock];
if (((colorWas >> c1) & 1) == 1) {
return false;
}
colorWas |= 1 << c1;
if (c1 > c2) {
int t = c1;
c1 = c2;
c2 = t;
}
if (was[c1][c2]) {
return false;
}
}
return true;
}
static void process(int curBlock, boolean what) {
for (int j : edges[curBlock]) {
int c1 = color[j];
int c2 = color[curBlock];
if (c1 > c2) {
int t = c1;
c1 = c2;
c2 = t;
}
was[c1][c2] = what;
}
}
// static int go(int curBlock) {
// if (curBlock == ALL_BLOCKS) {
// return 1;
// }
// int mask = 0;
// for (int i = 0; i < chosen.length; i++) {
// mask *= 3;
// mask += chosen[i];
// }
// if (dict[curBlock][mask] >= 0) {
// return dict[curBlock][mask];
// }
// int ret = 0;
// for (int i = 0; i < chosen.length; i++) {
// if (chosen[i] == 2) {
// continue;
// }
// color[curBlock] = i;
// if (!check(curBlock)) {
// color[curBlock] = -1;
// continue;
// }
// chosen[i]++;
// process(curBlock, true);
// ret += go(curBlock + 1);
// process(curBlock, false);
// chosen[i]--;
// color[curBlock] = -1;
// }
// return dict[curBlock][mask] = ret;
// }
//
// static boolean process(int curBlock, boolean what) {
// for (int j = 0; j < 4; j++) {
// int x = blockX[curBlock] + OFFSET_X[j];
// int y = blockY[curBlock] + OFFSET_Y[j];
// int col = color[w[x][y]];
// for (int dir = 0; dir < 4; dir++) {
// int xx = x + DX[dir];
// int yy = y + DY[dir];
// if (xx >= n || yy >= m || xx < 0 || yy < 0
// || c[xx][yy] != c[x][y]) {
// continue;
// }
// int c1 = col;
// int c2 = color[w[xx][yy]];
// if (c1 == -1 || c2 == -1) {
// continue;
// }
// if (c1 > c2) {
// int t = c1;
// c1 = c2;
// c2 = t;
// }
// was[c1][c2] = what;
// }
// }
// return true;
// }
//
// static boolean check(int curBlock) {
// for (int j = 0; j < 4; j++) {
// int x = blockX[curBlock] + OFFSET_X[j];
// int y = blockY[curBlock] + OFFSET_Y[j];
// int col = color[w[x][y]];
// for (int dir = 0; dir < 4; dir++) {
// int xx = x + DX[dir];
// int yy = y + DY[dir];
// if (xx >= n || yy >= m || xx < 0 || yy < 0
// || c[xx][yy] != c[x][y]) {
// continue;
// }
// int c1 = col;
// int c2 = color[w[xx][yy]];
// if (c1 == -1 || c2 == -1) {
// continue;
// }
// if (c1 > c2) {
// int t = c1;
// c1 = c2;
// c2 = t;
// }
// if (was[c1][c2]) {
// return false;
// }
// }
// }
// return true;
// }
FastScanner sc;
PrintWriter out;
public void run() {
Locale.setDefault(Locale.US);
try {
sc = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
sc.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() {
return sc.nextInt();
}
String nextToken() {
return sc.nextToken();
}
long nextLong() {
return sc.nextLong();
}
double nextDouble() {
return sc.nextDouble();
}
BigInteger nextBigInteger() {
return sc.nextBigInteger();
}
class FastScanner extends BufferedReader {
StringTokenizer st;
boolean eof;
String buf;
String curLine;
boolean createST;
public FastScanner(String fileName) throws FileNotFoundException {
this(fileName, true);
}
public FastScanner(String fileName, boolean createST)
throws FileNotFoundException {
super(new FileReader(fileName));
this.createST = createST;
nextToken();
}
public FastScanner(InputStream stream) {
this(stream, true);
}
public FastScanner(InputStream stream, boolean createST) {
super(new InputStreamReader(stream));
this.createST = createST;
nextToken();
}
String nextLine() {
String ret = curLine;
if (createST) {
st = null;
}
nextToken();
return ret;
}
String nextToken() {
if (!createST) {
try {
curLine = readLine();
} catch (Exception e) {
eof = true;
}
return null;
}
while (st == null || !st.hasMoreTokens()) {
try {
curLine = readLine();
st = new StringTokenizer(curLine);
} catch (Exception e) {
eof = true;
break;
}
}
String ret = buf;
buf = eof ? "-1" : st.nextToken();
return ret;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
BigInteger nextBigInteger() {
return new BigInteger(nextToken());
}
public void close() {
try {
buf = null;
st = null;
curLine = null;
super.close();
} catch (Exception e) {
}
}
boolean isEOF() {
return eof;
}
}
public static void main(String[] args) {
new A().run();
}
} | Java | ["8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy"] | 0.5 second | ["10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344"] | null | Java 6 | standard input | [
"implementation",
"brute force"
] | c5e83c717c4bb3db0a0da7436b77f123 | The first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists. | 2,400 | Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different. | standard output | |
PASSED | 39cd117a212564756b67a3301888a87f | train_004.jsonl | 1310731200 | Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class Solution{
public static void main(String args[]) throws IOException{
new Doit().main();
}
}
class Doit{
public String Map[],Print[];
public int m,n;
int num[][],link[][],ANS,color[],tl,tim[][],fin[];
void DFS(int P,int col){
if (P == 15){
tl ++;
boolean could = true;
for (int i = 1;i <= 28;i ++){
int j = color[link[i][0]],k = color[link[i][1]];
if (tim[j][k] == tl) could = false; else
tim[k][j] = tim[j][k] = tl;
}
if (could){
ANS ++;
if (ANS == 1){
fin = new int[100];
for (int i = 1;i <= 14;i ++)
fin[i] = color[i];
}
}
return;
}
if (color[P] != -1) DFS(P + 1,col); else {
color[P] = col;
for (int i = P + 1;i <= 14;i ++) if (color[i] == -1){
color[i] = col;
DFS(P + 1,col + 1);
color[i] = -1;
}
color[P] = -1;
}
}
public void solve() throws IOException{
m = nextInt();
n = nextInt();
Map = new String[100];
Print = new String[100];
for (int i = 1; i <= m; i ++){
Map[i] = nextToken();
Print[i] = Map[i];
}
num = new int[100][100];
link = new int[100][3];
color = new int[100];
tim = new int[30][30];
for (int i = 1,height = 0; i <= m; i ++)
for (int j = 1; j <= n; j ++)
if (Map[i].charAt(j - 1) != '.'){
int ch = Map[i].charAt(j - 1);
int u = (ch <= 'z' && ch >= 'a') ? (ch - 'a' + 1):(ch - 'A' + 27);
if (num[i][j] == 0)
num[i][j] = num[i + 1][j] = num[i][j + 1] = num[i + 1][j + 1] = ++ height;
if (link[u][0] == 0) link[u][0] = num[i][j];
else link[u][1] = num[i][j];
}
for (int i = 1;i <= 14;i ++)
color[i] = -1;
DFS(1,0);
out.println(5040 * ANS);
for (int i = 1;i <= m;i ++){
for (int j = 1;j <= n;j ++){
char ch = Map[i].charAt(j - 1);
if (ch == '.'){
out.print(ch);
continue;
}
out.print(fin[num[i][j]]);
}
out.println();
}
}
void main() throws IOException{
reader = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
tokenizer = null;
//File fin = new File("a.in");
//reader = new BufferedReader(new InputStreamReader(new FileInputStream(fin)));
//out = new PrintWriter("a.out");
solve();
reader.close();
out.flush();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy"] | 0.5 second | ["10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344"] | null | Java 6 | standard input | [
"implementation",
"brute force"
] | c5e83c717c4bb3db0a0da7436b77f123 | The first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists. | 2,400 | Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different. | standard output | |
PASSED | 5761ab5280be928af775beb00664422e | train_004.jsonl | 1310731200 | Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class Solution{
public static void main(String args[]) throws Exception{
scanner sc = new scanner(System.in);
output out = new output(System.out);
Doit doit = new Doit();
doit.solve(sc, out);
out.close();
sc.close();
}
}
class Doit{
public String Map[],Print[];
public int m,n;
int num[][],link[][],ANS,color[],tl,tim[][],fin[];
void DFS(int P,int col){
if (P == 15){
tl ++;
boolean could = true;
for (int i = 1;i <= 28;i ++){
int j = color[link[i][0]],k = color[link[i][1]];
if (tim[j][k] == tl) could = false; else
tim[k][j] = tim[j][k] = tl;
}
if (could){
ANS ++;
if (ANS == 1){
fin = new int[100];
for (int i = 1;i <= 14;i ++)
fin[i] = color[i];
}
}
return;
}
if (color[P] != -1) DFS(P + 1,col); else {
color[P] = col;
for (int i = P + 1;i <= 14;i ++) if (color[i] == -1){
color[i] = col;
DFS(P + 1,col + 1);
color[i] = -1;
}
color[P] = -1;
}
}
public void solve(scanner sc,output out){
m = sc.nextInt();
n = sc.nextInt();
Map = new String[100];
Print = new String[100];
for (int i = 1; i <= m; i ++){
Map[i] = sc.nextString();
Print[i] = Map[i];
}
num = new int[100][100];
link = new int[100][3];
color = new int[100];
tim = new int[30][30];
for (int i = 1,height = 0; i <= m; i ++)
for (int j = 1; j <= n; j ++)
if (Map[i].charAt(j - 1) != '.'){
int ch = Map[i].charAt(j - 1);
int u = (ch <= 'z' && ch >= 'a') ? (ch - 'a' + 1):(ch - 'A' + 27);
if (num[i][j] == 0)
num[i][j] = num[i + 1][j] = num[i][j + 1] = num[i + 1][j + 1] = ++ height;
if (link[u][0] == 0) link[u][0] = num[i][j];
else link[u][1] = num[i][j];
}
for (int i = 1;i <= 14;i ++)
color[i] = -1;
DFS(1,0);
out.out.println(5040 * ANS);
for (int i = 1;i <= m;i ++){
for (int j = 1;j <= n;j ++){
char ch = Map[i].charAt(j - 1);
if (ch == '.'){
out.out.print(ch);
continue;
}
out.out.print(fin[num[i][j]]);
}
out.out.println();
}
}
}
class output{
public PrintWriter out;
public File temp;
public output(OutputStream stream){
out = new PrintWriter(stream);
}
public output(String filename){
temp = new File(filename);
try {
out = new PrintWriter(temp);
}
catch(FileNotFoundException e){
return;
}
}
public void close(){
out.close();
}
}
class scanner extends BufferedReader{
public String now;
public StringTokenizer st;
public boolean have_st, eof;
public scanner(String filename)throws Exception{
super(new FileReader(filename));
have_st = false;
}
public scanner(InputStream stream){
super(new InputStreamReader(stream));
have_st = false;
}
String nextToken(){
if (eof) return null;
String ret = null;
for (; ret == null && eof == false; ){
if (st != null && st.hasMoreTokens()){
ret = st.nextToken();
break;
}
try{
now = readLine();
st = new StringTokenizer(now);
}
catch (IOException e){
eof = true;
}
}
return ret;
}
public int nextInt(){
return Integer.parseInt(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public String nextString(){
return nextToken();
}
public void close() throws IOException{
super.close();
}
}
| Java | ["8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy"] | 0.5 second | ["10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344"] | null | Java 6 | standard input | [
"implementation",
"brute force"
] | c5e83c717c4bb3db0a0da7436b77f123 | The first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists. | 2,400 | Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different. | standard output | |
PASSED | dcf5a7e205ed6f2693b3903ebeb2c83d | train_004.jsonl | 1310731200 | Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round. | 256 megabytes | //package yandex2011.finals;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class A {
Scanner in;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int m = ni();
char[][] b = new char[n][m];
for(int i = 0;i < n;i++){
b[i] = in.next().toCharArray();
}
boolean[][] ok = new boolean[n][m];
int[][] co = new int[14][2];
int p = 0;
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
if(b[i][j] != '.' && !ok[i][j]){
co[p][0] = i;
co[p][1] = j;
p++;
for(int k = 0;k <= 1;k++){
for(int l = 0;l <= 1;l++){
ok[i+k][j+l] = true;
}
}
}
}
}
boolean[][] nei = new boolean[n][m];
int[] dr = {1,-1,0,0};
int[] dc = {0,0,-1,1};
int[][] mino = new int[28][4];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
if(b[i][j] != '.' && !nei[i][j]){
nei[i][j] = true;
for(int k = 0;k < 4;k++){
int nr = i + dr[k];
int nc = j + dc[k];
if(nr >= 0 && nr < n && nc >= 0 && nc < m && b[i][j] == b[nr][nc]){
int cod = code(b[i][j]);
mino[cod][0] = i;
mino[cod][1] = j;
mino[cod][2] = nr;
mino[cod][3] = nc;
nei[nr][nc] = true;
break;
}
}
}
}
}
filled = new char[n][m];
retf = new char[n][m];
for(int i = 0;i < n;i++){
Arrays.fill(filled[i], '.');
}
long ret = rec(b,n,m,co,0,0,new int[7], new int[14], mino);
out.println(ret*5040);
for(char[] q : retf){
out.println(new String(q));
}
}
int code(char c)
{
if(c == 'A')return 26;
if(c == 'B')return 27;
return c - 'a';
}
char[][] filled;
char[][] retf;
long rec(char[][] b, int n, int m, int[][] co, int pos, int sup, int[] used, int[] ar, int[][] mino)
{
if(pos == 14){
long f = 0;
for(int i = 0;i < 28;i++){
int q = filled[mino[i][0]][mino[i][1]] - '0';
int r = filled[mino[i][2]][mino[i][3]] - '0';
long o = 1L<<(Math.min(q,r)*7+Math.max(q,r));
if((f&o) != 0){
return 0;
}
f |= o;
}
if(retf[0][0] == 0){
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
retf[i][j] = filled[i][j];
}
}
}
return 1;
}
long u = 0;
for(int i = 0;i <= sup;i++){
if(used[i] < 2){
used[i]++;
ar[pos] = i;
for(int j = 0;j <= 1;j++){
for(int k = 0;k <= 1;k++){
filled[co[pos][0]+j][co[pos][1]+k] = (char)('0'+i);
}
}
u += rec(b,n,m,co,pos+1,sup+(i==sup&&sup<=5?1:0),used,ar, mino);
used[i]--;
}
}
return u;
}
void run() throws Exception
{
in = oj ? new Scanner(System.in) : new Scanner(INPUT);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception
{
new A().run();
}
int ni() { return Integer.parseInt(in.next()); }
long nl() { return Long.parseLong(in.next()); }
double nd() { return Double.parseDouble(in.next()); }
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy"] | 0.5 second | ["10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344"] | null | Java 6 | standard input | [
"implementation",
"brute force"
] | c5e83c717c4bb3db0a0da7436b77f123 | The first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists. | 2,400 | Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different. | standard output | |
PASSED | 62654bf91f2e9ace7d93d8b3641f75ac | train_004.jsonl | 1310731200 | Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round. | 256 megabytes | //package yandex2011.finals;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class A {
Scanner in;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int m = ni();
char[][] b = new char[n][m];
for(int i = 0;i < n;i++){
b[i] = in.next().toCharArray();
}
boolean[][] ok = new boolean[n][m];
int[][] co = new int[14][2];
int p = 0;
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
if(b[i][j] != '.' && !ok[i][j]){
co[p][0] = i;
co[p][1] = j;
p++;
for(int k = 0;k <= 1;k++){
for(int l = 0;l <= 1;l++){
ok[i+k][j+l] = true;
}
}
}
}
}
boolean[][] nei = new boolean[n][m];
int[] dr = {1,-1,0,0};
int[] dc = {0,0,-1,1};
int[][] mino = new int[28][4];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
if(b[i][j] != '.' && !nei[i][j]){
nei[i][j] = true;
for(int k = 0;k < 4;k++){
int nr = i + dr[k];
int nc = j + dc[k];
if(nr >= 0 && nr < n && nc >= 0 && nc < m && b[i][j] == b[nr][nc]){
int cod = code(b[i][j]);
mino[cod][0] = i;
mino[cod][1] = j;
mino[cod][2] = nr;
mino[cod][3] = nc;
nei[nr][nc] = true;
break;
}
}
}
}
}
filled = new char[n][m];
retf = new char[n][m];
for(int i = 0;i < n;i++){
Arrays.fill(filled[i], '.');
}
long ret = rec(b,n,m,co,0,0,new int[7], new int[14], mino);
out.println(ret*5040);
for(char[] q : retf){
out.println(new String(q));
}
}
int code(char c)
{
if(c == 'A')return 26;
if(c == 'B')return 27;
return c - 'a';
}
char[][] filled;
char[][] retf;
long rec(char[][] b, int n, int m, int[][] co, int pos, int sup, int[] used, int[] ar, int[][] mino)
{
if(pos == 14){
long f = 0;
for(int i = 0;i < 28;i++){
int q = filled[mino[i][0]][mino[i][1]] - '0';
int r = filled[mino[i][2]][mino[i][3]] - '0';
long o = 1L<<(Math.min(q,r)*7+Math.max(q,r));
if((f&o) != 0){
return 0;
}
f |= o;
}
if(retf[0][0] == 0){
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
retf[i][j] = filled[i][j];
}
}
}
return 1;
}
long u = 0;
for(int i = 0;i <= sup;i++){
if(used[i] < 2){
used[i]++;
ar[pos] = i;
for(int j = 0;j <= 1;j++){
for(int k = 0;k <= 1;k++){
filled[co[pos][0]+j][co[pos][1]+k] = (char)('0'+i);
}
}
u += rec(b,n,m,co,pos+1,sup+(i==sup&&sup<=5?1:0),used,ar, mino);
used[i]--;
}
}
return u;
}
void run() throws Exception
{
in = oj ? new Scanner(System.in) : new Scanner(INPUT);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception
{
new A().run();
}
int ni() { return Integer.parseInt(in.next()); }
long nl() { return Long.parseLong(in.next()); }
double nd() { return Double.parseDouble(in.next()); }
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy"] | 0.5 second | ["10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344"] | null | Java 6 | standard input | [
"implementation",
"brute force"
] | c5e83c717c4bb3db0a0da7436b77f123 | The first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists. | 2,400 | Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different. | standard output | |
PASSED | 6885195cb57c119378b2e6594d937eae | train_004.jsonl | 1310731200 | Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Domino implements Runnable {
int[][] adj;
int[] res;
int[] cur;
int[] rem;
int numTwos;
long numRes;
int[] have;
int[][] field;
int[][] sfield;
private void solve() throws IOException {
int height = nextInt();
int width = nextInt();
int[][] field = new int[height][width];
this.field = field;
for (int r = 0; r < height; ++r) {
String s = nextToken();
for (int c = 0; c < width; ++c) {
char ch = s.charAt(c);
if (ch >= 'a' && ch <= 'z')
field[r][c] = ch - 'a';
else if (ch >= 'A' && ch <= 'B')
field[r][c] = 26 + ch - 'A';
else
field[r][c] = -1;
}
}
int[][] sfield = new int[height][width];
this.sfield = sfield;
for (int r = 0; r < height; ++r) sfield[r] = field[r].clone();
int[][] pairs = new int[28][2];
for (int i = 0; i < 28; ++i)
Arrays.fill(pairs[i], -1);
int id = 0;
for (int r = 0; r < height; ++r)
for (int c = 0; c < width; ++c)
if (field[r][c] >= 0) {
process(field, r, c, id, pairs);
process(field, r + 1, c, id, pairs);
process(field, r, c + 1, id, pairs);
process(field, r + 1, c + 1, id, pairs);
++id;
}
if (id != 14) throw new RuntimeException();
int[] nadj = new int[14];
for (int i = 0; i < 28; ++i) {
++nadj[pairs[i][0]];
if (pairs[i][0] != pairs[i][1]) ++nadj[pairs[i][1]];
}
adj = new int[14][];
for (int i = 0; i < 14; ++i) adj[i] = new int[nadj[i]];
Arrays.fill(nadj, 0);
for (int i = 0; i < 28; ++i) {
adj[pairs[i][0]][nadj[pairs[i][0]]++] = pairs[i][1];
if (pairs[i][0] != pairs[i][1]) adj[pairs[i][1]][nadj[pairs[i][1]]++] = pairs[i][0];
}
have = new int[7 * 7];
cur = new int[14];
rem = new int[7];
Arrays.fill(rem, 2);
numRes = 0;
numTwos = 7;
rec(0, 1);
writer.println(numRes);
if (numRes == 0) while (true);
for (int r = 0; r < height; ++r)
for (int c = 0; c < width; ++c)
if (field[r][c] <= -2)
field[r][c] = res[-field[r][c] - 2];
int[][] hh = new int[7][7];
for (int r = 0; r < height; ++r)
for (int c = 0; c < width; ++c)
for (int rr = 0; rr < height; ++rr)
for (int cc = 0; cc < width; ++cc)
if ((rr != r) || (cc != c))
if (sfield[rr][cc] == sfield[r][c] && sfield[rr][cc] >= 0) {
++hh[field[rr][cc]][field[r][c]];
++hh[field[r][c]][field[rr][cc]];
}
for (int i = 0; i < 7; ++i)
for (int j = 0; j < 7; ++j) {
int need = (i == j) ? 4 : 2;
if (need != hh[i][j]) throw new RuntimeException();
}
for (int r = 0; r < height; ++r) {
for (int c = 0; c < width; ++c)
if (field[r][c] < 0) writer.print("."); else writer.print(field[r][c]);
writer.println();
}
}
void verify() {
int height = field.length;
int width = field[0].length;
int[][] field = new int[height][width];
for (int r = 0; r < height; ++r)
for (int c = 0; c < width; ++c)
field[r][c] = this.field[r][c];
for (int r = 0; r < height; ++r)
for (int c = 0; c < width; ++c)
if (field[r][c] <= -2)
field[r][c] = cur[-field[r][c] - 2];
int[][] hh = new int[7][7];
for (int r = 0; r < height; ++r)
for (int c = 0; c < width; ++c)
for (int rr = 0; rr < height; ++rr)
for (int cc = 0; cc < width; ++cc)
if ((rr != r) || (cc != c))
if (sfield[rr][cc] == sfield[r][c] && sfield[rr][cc] >= 0) {
++hh[field[rr][cc]][field[r][c]];
++hh[field[r][c]][field[rr][cc]];
}
for (int i = 0; i < 7; ++i)
for (int j = 0; j < 7; ++j) {
int need = (i == j) ? 4 : 2;
if (need != hh[i][j]) throw new RuntimeException();
}
}
private void rec(int at, long toAdd) {
if (at >= 14) {
if (res == null)
res = cur.clone();
numRes += toAdd;
//verify();
return;
}
boolean hadTwo = false;
for (int what = 0; what < 7; ++what) {
if (rem[what] <= 0) continue;
long nToAdd = toAdd;
if (rem[what] == 2) {
if (hadTwo) continue;
hadTwo = true;
nToAdd *= numTwos;
}
cur[at] = what;
boolean ok = true;
for (int x : adj[at])
if (x <= at) {
++have[what * 7 + cur[x]];
if (cur[x] != what)
++have[cur[x] * 7 + what];
}
for (int x : adj[at])
if (x <= at) {
if (have[what * 7 + cur[x]] > 1) ok = false;
}
if (ok) {
if (rem[what] == 2) --numTwos;
--rem[what];
rec(at + 1, nToAdd);
++rem[what];
if (rem[what] == 2) ++numTwos;
}
for (int x : adj[at])
if (x <= at) {
--have[what * 7 + cur[x]];
if (cur[x] != what)
--have[cur[x] * 7 + what];
}
}
}
private void process(int[][] field, int r, int c, int id, int[][] pairs) {
if (field[r][c] < 0) throw new RuntimeException();
int what = field[r][c];
field[r][c] = -(id + 2);
if (pairs[what][0] < 0) {
pairs[what][0] = id;
} else if (pairs[what][1] < 0) {
pairs[what][1] = id;
} else {
throw new RuntimeException();
}
}
public static void main(String[] args) {
new Domino().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
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);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy"] | 0.5 second | ["10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344"] | null | Java 6 | standard input | [
"implementation",
"brute force"
] | c5e83c717c4bb3db0a0da7436b77f123 | The first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists. | 2,400 | Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different. | standard output | |
PASSED | 086357101b2edcd7f9295f3fd450f264 | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.util.*;
import java.lang.*;
public class Main {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t = sc.nextInt();
int s[] = new int[n];
int d[] = new int[n];
for(int i = 0; i < n; i++) {
s[i] = sc.nextInt();
d[i] = sc.nextInt();
}
int min;
if(s[0] >= t) min = Math.abs(s[0] - t);
else {
int sum = s[0];
int dum = d[0];
while(sum < t) sum += dum;
min = Math.abs(sum - t);
}
int route = 1;
int flag = 1;
for(int i = 1; i < n; i++) {
if(t == s[i]) {
System.out.println(i + 1);
flag = 0;
break;
}
else {
if(s[i] > t && Math.abs(s[i] - t) < min) {
min = Math.abs(s[i] - t);
route = i + 1;
}
else if(s[i] < t) {
int sum = s[i];
int dum = d[i];
while(sum < t) {
sum += dum;
}
if(Math.abs(sum - t) < min) {
min = Math.abs(sum - t);
route = i + 1;
}
}
}
}
if(flag == 1) System.out.println(route);
}
} | Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | b696b2e92c3ea93ebe3ebeb163d5d33a | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | //package codeforces551;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) throws IOException {
//System.setIn(new FileInputStream(new File("A.in4")));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
while(line != null) {
StringTokenizer tok = new StringTokenizer(line);
int n = Integer.parseInt(tok.nextToken());
int t = Integer.parseInt(tok.nextToken());
int indexSmallest = 0;
int smallest = Integer.MAX_VALUE;
int index = 1;
while(n-->0) {
tok = new StringTokenizer(br.readLine());
int a = Integer.parseInt(tok.nextToken());
int d = Integer.parseInt(tok.nextToken());
if(a >= t) {
if (a<smallest) {
indexSmallest = index;
smallest = a;
}
} else {
int x = (t-a)/d;
int sum = a+(d*x);
while(sum<t) sum+=d;
if(sum<smallest) {
indexSmallest = index;
smallest = sum;
}
}
index++;
}
System.out.println(indexSmallest);
line = br.readLine();
}
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | c388cc432d42d4a388a159828527a95b | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Buses {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
String[] prin = lector.readLine().split(" ");
int bus = Integer.parseInt(prin[0]);
int tim = Integer.parseInt(prin[1]);
int bes = 0;
int act = Integer.MAX_VALUE;
int ari = 0;
int min = 0;
int i =0;
while( i<bus && act != 0 ){
prin = lector.readLine().split(" ");
ari = Integer.parseInt(prin[0]);
min = Integer.parseInt(prin[1]);
int tem = ari;
while(tem < tim){
tem += min;
}
if(tem-tim < act){
bes = i+1;
act = tem-tim;
}
i++;
}
System.out.println(bes);
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | ee2cdd014009b138d478d561fba6a1c3 | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.util.*;
public class Bus
{
public static void main(String[]args)
{
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int t=scan.nextInt();
int s=0;
int d=0;
ArrayList<Integer> ans=new ArrayList<>();
for(int i=0;i<n;i++)
{
s=scan.nextInt();
d=scan.nextInt();
while(s<t)
s+=d;
ans.add(s);
}
System.out.println(ans.indexOf(Collections.min(ans))+1);
}
} | Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 4581dbecbbf50a67fb7b42e59e67a5cc | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.util.Scanner;
public class ServalandBusA {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int serval = sc.nextInt();
int first, frequency;
int earliest = Integer.MAX_VALUE;
int index= 0;
int time;
for (int i = 1; i <= n; i++) {
first = sc.nextInt();
frequency = sc.nextInt();
if(first>=serval){
time=first;
}else{
time = (int)Math.ceil(((double)serval-first)/frequency) * frequency + first;
}
if(time<=earliest){
earliest=time;
index=i;
}
}
System.out.println(index);
}
} | Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 69bb0ae256f0a0147dd109bd877c51ee | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.concurrent.PriorityBlockingQueue;
public class ServalAndBus {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int t = sc.nextInt();
pair[] arr = new pair[n];
boolean done = false;
for (int i = 0; i < n; i++) {
arr[i] = new pair(sc.nextInt(), sc.nextInt());
// System.out.println(arr[i].fstcome +" "+ arr[i].interval);
}
int ans = 0;
long min = (long) 10e9;
for (int i = 0; i < n; i++) {
long sum = arr[i].fstcome;
if (t <= arr[i].fstcome) {
if (min > arr[i].fstcome-t) {
min = arr[i].fstcome-t;
ans = i + 1;
done = true;
}
} else {
while (t > sum) {
sum += arr[i].interval;
}
if (sum - t < min) {
min = sum - t;
ans = i + 1;
}
}
}
System.out.println(ans);
}
static class pair {
int fstcome;
int interval;
pair(int f, int i) {
fstcome = f;
interval = i;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 1e088c60c3854ed96902d805ce4a90dc | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt(),t=scan.nextInt();
int OTVET=0,mint=0;
a[] mass=new a[n];
int t1,p1;
boolean flag=true;
for(int i=0; i<n; i++){
t1=scan.nextInt();
p1=scan.nextInt();
mass[i]=new a(t1,p1);
while(mass[i].t<t)
{
mass[i].t+=mass[i].period;
}
if(mass[i].t==t)
{
OTVET=i+1;
System.out.print(OTVET);
flag=false;
break;
}
if(mint==0) {
mint = mass[i].t;
OTVET=i+1;
}
if(mint>mass[i].t) {
mint = mass[i].t;
OTVET = i + 1;
}
}
if(flag)System.out.print(OTVET);
}
}
class a {
int t;
int period;
public a(int t, int period) {
this.t = t;
this.period = period;
}
} | Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 980f5757e008f971d031083652bc7697 | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | /*
Akash Yadav
MNNIT Allahabad, Prayagraj
@P.D.Tandon
14th April 19
Welcome visitor,
I'm glad that you have reached out to my code.
I'll be happy if this code helps you in any way.
Did you notice,
Every decision you've ever taken in your life has lead you to this code.
What a wonderful world.
*/
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class TestClass{
//https://codeforces.com/problemset/problem/1153/A
public static Scanner scn = new Scanner(System.in);
public static long MOD = (long)1e9+7;
FastReader in;PrintWriter out;
boolean multipleTC = false;
void solve(int index) throws java.lang.Exception{
long N = nxtl();
long T = nxtl();
long mat = Integer.MAX_VALUE;
int ansidx = -1;
for(int i = 0; i < N; i++){
long st = nxtl();
long rep = nxtl();
//long ct = (st < T)?((((T-st)/rep)+1)*rep+st) : st;
long ct = 0;
if(st < T){
long diff = T - st;
if(diff%rep == 0)
ct = 0;
else
ct = rep - diff%rep;
} else {
ct = st - T;
}
if(ct < mat){
mat = ct;
ansidx = i+1;
}
}
joutln(ansidx);
}
////////POLICE LINE///////DO NOT CROSS///////CRIME SCENE///////////
void init() throws java.lang.Exception{
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? nxti() : 1;
for(int i = 1; i <= T; i++){solve(i);}
out.flush();
out.close();
}
public static void main (String[] args) throws java.lang.Exception{
new TestClass().init();
}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
void jout(Object o){out.print(o);}
void joutln(Object o){out.println(o);}
void jouti(Object o){out.println(o);out.flush();}
String nxt(){return in.next();}
String nxtln(){return in.nextLine();}
int nxti(){return Integer.parseInt(in.next());}
long nxtl(){return Long.parseLong(in.next());}
double nxtd(){return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
}
} | Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 18fc913b1da27bf3352610f5f8c47030 | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.awt.*;
import java.io.*;
import java.util.StringTokenizer;
public class ServalandBus {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
// InputStream inputStream = new FileInputStream(new File("test.in"));
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int tests = 1;
solve(tests, in, out);
out.close();
}
static void solve(int testNumber, InputReader in, PrintWriter out) throws IOException {
for (int ii = 1; ii <= testNumber; ii++) {
int n = in.nextInt();
int t = in.nextInt();
int ans = in.nextInt();
int ans2 = in.nextInt();
int trip = 1;
while(ans<t){
ans+=ans2;
}
for (int i = 2; i <= n; i++) {
int temp = in.nextInt();
int temp2 = in.nextInt();
if(temp>t){
if(temp<ans) {
ans = temp;
trip = i;
}
}else if(temp==t){
out.println(i);
return;
}else {
while(temp<t){
temp+=temp2;
}
if(temp<ans){
ans = temp;
trip = i;
}
}
}
System.out.println(trip);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 36d059154b25b6a0213d5c314a991769 | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.util.*;
public class jfj
{
public static void main(String []args)
{
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int t=in.nextInt();
int a[]=new int[n];
int d[]=new int[n];
int s[]=new int[n];
int i,res=0,min=1000005;
for(i=0;i<n;++i)
{
s[i]=in.nextInt();
d[i]=in.nextInt();
}
for(i=0;i<n;++i)
{
a[i]=t%d[i];
a[i]=t-a[i]+s[i];
}
for(i=0;i<n;++i)
{
while(a[i]>t && a[i]>s[i])
{
a[i]-=d[i];
}
if(a[i]<t)
a[i]+=d[i];
//System.out.println(a[i]+" "+(a[i]-d[i]));
}
for(i=0;i<n;++i)
{
if(Math.abs(a[i]-t)<min)
{
min=Math.abs(a[i]-t);
res=i+1;
}
}
System.out.println(res);
}
} | Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 37323ba1c5de75a128f6599aa514c02f | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class test1 {
public static void main(String[] args) throws IOException {
Scanner reader = new Scanner(System.in);
PrintWriter writer = new PrintWriter(System.out);
String bob[] = reader.nextLine().split(" ");
int n = Integer.parseInt(bob[0]);
int t = Integer.parseInt(bob[1]);
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
for(int i=0;i<n;i++) {
String split[] = reader.nextLine().split(" ");
a.add(Integer.parseInt(split[0]));
b.add(Integer.parseInt(split[1]));
}
int minnum = 10000000;
int minpos=0;
for(int i=0;i<n;i++) {
while(a.get(i) < t) {
a.set(i, a.get(i)+b.get(i));
}
if(minnum > a.get(i)) {
minpos = i;
minnum = a.get(i);
}
}
writer.println(minpos+1);
writer.close();
}
} | Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | e27033b64376e8eb1248c420ee0f30fd | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
@SuppressWarnings("unchecked")
public class DhakaJi {
InputStream is;
PrintWriter out;
long mod = (long)(1e9 + 7), inf = (long)(3e18);
void solve() {
//SZ = sieve(); //SZ = 1000001;
int n = ni();
int t = ni();
int min = 100000000;
int ans = 0 ;
boolean flag = false ;
for(int i=0;i<n;i++){
int s = ni() ;
int d= ni() ;
if(s==t){
min = 0 ;
ans = i+1 ;
flag = true ;
}
else if(s>t){
int temp = s-t ;
if(temp<min){
min = temp ;
ans = i+1 ;
}
}
else{
int temp = t-s ;
temp = (int )Math.ceil((double )temp/(double)d );
temp = s+temp*d ;
if(temp-t<min){
min = temp-t ;
ans = i+1 ;
}
}
}
out.println(ans);
}
//--------- Extra Template -----------
boolean isPrime(long n) {
if(n <= 1) return false;
if(n <= 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
for(long i = 5; i * i <= n; i += 6) {
if(n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
public int log2(int n){
if(n <= 0) throw new IllegalArgumentException();
return 31 - Integer.numberOfLeadingZeros(n);
}
int P[], S[], SZ, RP = 15485900;
boolean isP[];
int sieve() {
int i, j, n = RP;
isP = new boolean[n];
S = new int[n];
for(i = 3; i < n; i += 2) {
isP[i] = true;
S[i-1] = 2;
S[i] = i;
}
isP[2] = true;
S[1] = 1; //(UD)
for(i = 3; i * i <= n; i += 2) {
if( !isP[i] ) continue;
for(j = i * i; j < n; j += i) {
isP[j] = false;
if(S[j] == j) S[j] = i;
}
}
P = new int[n];
P[0] = 2;
j = 1;
for(i = 3; i < n; i += 2) {
if ( isP[i] ) P[j++] = i;
}
P = Arrays.copyOf(P, j);
return j;
}
long gcd(long a,long b){
while (a!=0 && b!=0)
{
if(a>b)
a%=b;
else
b%=a;
}
return a+b;
}
long mp(long b, long e, long mod) {
b %= mod;
long r = 1;
while(e > 0) {
if((e & 1) == 1) {
r *= b; r %= mod;
}
b *= b; b %= mod;
e >>= 1;
}
return r;
}
//---------- I/O Template ----------
public static void main(String[] args) throws Exception { new DhakaJi().run(); }
void run() throws Exception {
is = System.in;
out = new PrintWriter(System.out);
// long s = System.currentTimeMillis();
solve();
out.flush();
// tr((System.currentTimeMillis()-s)/1000+"s");
}
byte input[] = new byte[1024];
int len = 0, ptr = 0;
int readByte() {
if(ptr >= len) { ptr = 0;
try { len = is.read(input); }
catch(IOException e) { throw new InputMismatchException(); }
if(len <= 0) { return -1; }
} return input[ptr++];
}
boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); }
int skip() {
int b = readByte();
while(b != -1 && isSpaceChar(b)) { b = readByte(); }
return b;
}
char nc() { return (char)skip(); }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
String nLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
int ni() {
int n = 0, b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
if(b == -1) { return -1; } //no input
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
long nl() {
long n = 0L; int b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
double nd() { return Double.parseDouble(ns()); }
float nf() { return Float.parseFloat(ns()); }
int[] na(int n) {
int a[] = new int[n];
for(int i = 0; i < n; i++) { a[i] = ni(); }
return a;
}
char[] ns(int n) {
char c[] = new char[n];
int i, b = skip();
for(i = 0; i < n; i++) {
if(isSpaceChar(b)) { break; }
c[i] = (char)b; b = readByte();
} return i == n ? c : Arrays.copyOf(c,i);
}
// private boolean oj = System.getProperty("ORLIRE_JUDGE") != null;
// private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
} | Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 057feaf6234976085f9e7dab4ecb71cb | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author Dhruv
*/
public class CF1153A {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int t=sc.nextInt();
long arr[]=new long[n];
for(int i=0;i<n;i++){
int a=sc.nextInt();
int d = sc.nextInt();
if(a<t){
int nt=(int) Math.ceil((double)(t-a)/(double)d);
long x=a+(nt)*d;
//System.out.println("nt:"+nt+" x:"+x);
arr[i]=x-t;
}
else if(a>=t){
arr[i]=a-t;
}
}
long min=Long.MAX_VALUE;
int idx=0;
for(int i=0;i<n;i++){
if(min>arr[i]){
min=arr[i];
idx=i;
}
}
System.out.println((idx+1));
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | ac1ba2e6d7f5c4c635f8a758c3ee15b3 | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;
/**
*
* @author mazen
*/
public class AServalAndBus {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int n,t;
Scanner sc= new Scanner(System.in);
n= sc.nextInt();
t=sc.nextInt();
int s[]=new int[n];
int d[]=new int[n];
for(int i=0;i<n;i++){
s[i]=sc.nextInt();
d[i]=sc.nextInt();
}
boolean temp=true;
int mul=0;
int multiplier[]=new int[n];
for(int j=0;j<n;j++){
temp=true;
mul=s[j];
if(t<=s[j]){
multiplier[j]=mul;
}else{
while(temp){
mul=mul+d[j];
if(mul>=t){
multiplier[j]+=mul;
temp=false;
}
//mul=mul+d[j];
}}
}
int min=0;
int index=-1;
//for(int l=multiplier.length-1;l>=0;l--){
min=multiplier[0];
for(int k=multiplier.length-1;k>=0;k--){
if(min>=multiplier[k]){
min=multiplier[k];
index=k+1;
}
// }
}
System.out.println(""+index);
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 18cb90107a1e1d93421c3c1ed1aceeb8 | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;
/**
*
* @author mazen
*/
public class AServalAndBus {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int n,t;
Scanner sc= new Scanner(System.in);
n= sc.nextInt();
t=sc.nextInt();
int s[]=new int[n];
int d[]=new int[n];
for(int i=0;i<n;i++){
s[i]=sc.nextInt();
d[i]=sc.nextInt();
}
boolean temp=true;
int mul=0;
int multiplier[]=new int[n];
for(int j=0;j<n;j++){
temp=true;
mul=s[j];
if(t<=s[j]){
multiplier[j]=mul;
}else{
while(temp){
mul=mul+d[j];
if(mul>=t){
multiplier[j]+=mul;
temp=false;
}
//mul=mul+d[j];
}}
}
int min=0;
int index=-1;
for(int l=multiplier.length-1;l>=0;l--){
min=multiplier[l];
for(int k=multiplier.length-1;k>=0;k--){
if(min>=multiplier[k]){
min=multiplier[k];
index=k+1;
}
}
}
System.out.println(""+index);
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 8778b5310ce56b0e1022debac3362cfe | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.util.Scanner;
public class Main {
static class Item {
public Item(int timeArrive, int interval) {
this.timeArrive = timeArrive;
this.interval = interval;
}
public int timeArrive;
public int interval;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int t = scanner.nextInt();
Item[] items = new Item[n];
for (int i = 0; i < n; i++) {
items[i] = new Item(scanner.nextInt(), scanner.nextInt());
}
System.out.println(getNumBus(items, t));
}
public static int getNumBus(Item[] items, int t) {
Integer min = null;
Integer idx = null;
for (int i = 0; i < items.length; i++) {
if (items[i].timeArrive == t) {
return i + 1;
}
if (items[i].timeArrive - t < 0) {
int next = items[i].timeArrive - t + items[i].interval;
while (next < 0) {
next += items[i].interval;
}
if (min == null || min > next) {
min = next;
idx = i;
}
}
if (items[i].timeArrive - t > 0) {
int next = items[i].timeArrive - t;
if (min == null || min > next) {
min = next;
idx = i;
}
}
}
return idx+1;
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | a166e5eed15c06d730875163599b5143 | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;
/**
*
* @author ahmadla
*/
public class NewMain6 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in =new Scanner (System.in);
int n= in.nextInt();
int x=in.nextInt();
int min=Integer.MAX_VALUE;
int ans=0;
int temp;
for (int i = 0; i < n; i++) {
int m=in.nextInt();
int c=in.nextInt();
int fac =(int)Math.ceil((x-m)/((double)c));
if(fac>0)
temp=fac*c+m;
else
temp=m;
if( temp<min)
{
ans=i+1;
min=temp;
}
}
System.out.println(ans);
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 08d99bc097b014d4c316a1a73fa53255 | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.util.Scanner;
public class myBestFriend {
static Scanner sc= new Scanner(System.in);
public static int routen=sc.nextInt();
public static int ankunft=sc.nextInt();
public static int[] zeitpunkt=new int[routen];
public static int[] abstand=new int[routen];
public static void main(String[]args){
for(int i=0;i<routen;i++){
zeitpunkt[i]=sc.nextInt();
abstand[i]=sc.nextInt();
while(zeitpunkt[i]<ankunft) zeitpunkt[i]+=abstand[i];
}
System.out.println(welche());
}
public static int welche(){
int counter=1000000;
int stelle=1;
for(int i=0;i<routen;i++){
if(ankunft==zeitpunkt[i]){
return i+1;
}
else if(ankunft<zeitpunkt[i]&&counter>(zeitpunkt[i]-ankunft)){
counter=zeitpunkt[i]-ankunft;
stelle=i;
}
}
return stelle+1;
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | cfd1ec046eb1034d219a48acb09f875d | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes | import java.util.*;
public class A1153
{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
int n =sc.nextInt();
int t =sc.nextInt();
int arr[]=new int[n];
for(int i = 0 ;i<n;i++)
{
int s=sc.nextInt();
int d=sc.nextInt();
int j=0;
int x =s+d*j;
if(s<=t)
{while(x<t)
{
j++;
x =s+d*j;
}
}
arr[i]=x-t;
}
int min =Integer.MAX_VALUE;
int minI=-1;
for(int i = 0;i<n;i++)
{
if(arr[i]<min && arr[i]>=0)
{
min=arr[i];
minI=i;
}
}
System.out.println(minI+1);
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 011496661acac7afd0b6a62cf99ab14c | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1024 * 1024 * 2);
int v[] = readArrayLine(br.readLine(), 2);
int n = v[0], t = v[1];
int best = Integer.MAX_VALUE;
int bestI = -1;
for (int i = 0 ; i < n ; i ++) {
v = readArrayLine(br.readLine(), 2);
int si = v[0], di = v[1];
int value = getClosest(t, si, di);
if (value < best) {
best = value;
bestI = i + 1;
}
}
System.out.println(bestI);
}
private static int getClosest(int t, int si, int di) {
if (t < si) {
return si;
}
t -= si;
if (t % di == 0) {
return t + si;
}
return si + di * (t / di + 1);
}
public static int[] readArrayLine(String line, int n) {
return readArrayLine(line, n, null, 0);
}
private static int[] readArrayLine(String line, int n, int array[], int pos) {
int[] ret = array == null ? new int[n] : array;
int start = 0;
int end = line.indexOf(' ', start);
for (int i = pos; i < pos + n; i++) {
if (end > 0)
ret[i] = Integer.parseInt(line.substring(start, end));
else
ret[i] = Integer.parseInt(line.substring(start));
start = end + 1;
end = line.indexOf(' ', start);
}
return ret;
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 72d45b24d4891e37c741126c7e869980 | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 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.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int t = in.readInt();
int min = Integer.MAX_VALUE;
int mi = -1;
for (int i = 0; i < n; i++) {
int s = in.readInt();
int d = in.readInt();
int val;
if (s >= t) {
val = s - t;
} else {
int k = (t - s + d - 1) / d;
val = s + k * d - t;
}
if (val < min) {
min = val;
mi = i + 1;
}
}
out.print(mi);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void print(int i) {
writer.print(i);
}
}
static class InputReader {
private final InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 02d9e5521d450ec7ec86abb622fdf69b | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 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 Ribhav
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
A solver = new A();
solver.solve(1, in, out);
out.close();
}
static class A {
public void solve(int testNumber, FastReader s, PrintWriter out) {
int n = s.nextInt();
int t = s.nextInt();
int[] start = new int[n];
int[] time = new int[n];
for (int i = 0; i < n; i++) {
start[i] = s.nextInt();
time[i] = s.nextInt();
}
int ans = Integer.MAX_VALUE;
int currPos = 1;
for (int i = 0; i < n; i++) {
if (start[i] >= t) {
if (ans > start[i] - t) {
ans = start[i] - t;
currPos = i + 1;
}
} else {
int equiv = t - start[i];
if (equiv % time[i] == 0) {
currPos = i + 1;
break;
} else {
int num = equiv / time[i] + 2;
int timeRem = start[i] + ((num - 1) * time[i]) - t;
if (timeRem < ans) {
ans = timeRem;
currPos = i + 1;
}
}
}
}
out.println(currPos);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 032404b2d1027ea26879b47caee35a2c | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes |
import java.util.*;
public class cf {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int t=sc.nextInt();
int bus=1;
int min_bus=0;
int min=Integer.MAX_VALUE;
while(n-->0){
int si=sc.nextInt();
int di=sc.nextInt();
int x=t-si;
x=(di-x%di)%di;
if(t<si)
x=si-t;
//if(si==t)
// x=0;
if(x<min)
{
min=x;
min_bus=bus;
}
bus++;
}
System.out.println(min_bus);
}
}
| Java | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | a2ae19ec44932bf25d0fbddfbb6b064b | train_004.jsonl | 1555164300 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them. | 256 megabytes |
import java.util.*;
import java.io.* ;
public class CF_1110 {
public static void main(String[] args) throws IOException{
FastReader scn = new FastReader() ;
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)) ;
int n = scn.nextInt() , t = scn.nextInt() ;
long[] s = new long[n] , d = new long[n] ;
long ans = 0 , min = Long.MAX_VALUE ;
for(int i = 0; i < n ; i++){
s[i] = scn.nextInt() ;
d[i] = scn.nextInt() ;
long x = 0 ;
if(t > s[i]) {
x = (long)((t - s[i]) / d[i]) ;
if((t - s[i]) % d[i] != 0) x++ ;
}
long a = s[i] + x * d[i] ;
if(a < min) {
min = a ;
ans = i + 1 ;
}
}
System.out.println(ans);
}
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 | ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"] | 1 second | ["1", "3", "1"] | NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not. | Java 8 | standard input | [
"brute force",
"math"
] | 71be4cccd3b8c494ad7cc2d8a00cf5ed | The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$)Β β the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$)Β β the time when the first bus of this route arrives and the interval between two buses of this route. | 1,000 | Print one numberΒ β what bus route Serval will use. If there are several possible answers, you can print any of them. | standard output | |
PASSED | 6b34f35a3e04609966b556b0bf88e086 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class DTask {
public static void main(String[] args) {
MyInputReader in = new MyInputReader(System.in);
int n = in.nextInt();
int m = in.nextInt();
int p = in.nextInt();
long[][] arr = new long[n][m];
ArrayList<Pair>[] pos = new ArrayList[p];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int cur = in.nextInt() - 1;
arr[i][j] = cur;
ArrayList<Pair> l = pos[cur];
if (l == null) {
pos[cur] = new ArrayList<Pair>();
l = pos[cur];
}
l.add(new Pair(i, j));
}
}
Fenwick2D topLeft = new Fenwick2D(n, m);
Fenwick2D topRight = new Fenwick2D(n, m);
Fenwick2D bottomLeft = new Fenwick2D(n, m);
Fenwick2D bottomRight = new Fenwick2D(n, m);
for (int i = 0; i < pos[0].size(); i++) {
Pair cur = pos[0].get(i);
cur.score = cur.r + cur.c;
}
for (int i = 1; i < p; i++) {
//put prev to fenwick
ArrayList<Pair> prev = pos[i - 1];
for (int j = 0; j < prev.size(); j++) {
Pair cur = prev.get(j);
topLeft.update(cur.score - cur.r - cur.c, cur.r, cur.c);
topRight.update(cur.score - cur.r + cur.c, cur.r, m - cur.c - 1);
bottomRight.update(cur.score + cur.r + cur.c, n - cur.r - 1, m - cur.c - 1);
bottomLeft.update(cur.score + cur.r - cur.c, n - cur.r - 1, cur.c);
}
ArrayList<Pair> ccc = pos[i];
for (int j = 0; j < ccc.size(); j++) {
Pair c = ccc.get(j);
long a1 = topLeft.get(c.r, c.c) + c.r + c.c;
long a2 = topRight.get(c.r, m - c.c - 1) + c.r - c.c;
long a3 = bottomRight.get(n - c.r - 1, m - c.c - 1) - c.r - c.c;
long a4 = bottomLeft.get(n - c.r - 1, c.c) - c.r + c.c;
long res = Math.min(Math.min(a1, a2), Math.min(a3, a4));
c.score = res;
}
for (int j = 0; j < prev.size(); j++) {
Pair cur = prev.get(j);
topLeft.erase(Integer.MAX_VALUE, cur.r, cur.c);
topRight.erase(Integer.MAX_VALUE, cur.r, m - cur.c - 1);
bottomRight.erase(Integer.MAX_VALUE, n - cur.r - 1, m - cur.c - 1);
bottomLeft.erase(Integer.MAX_VALUE, n - cur.r - 1, cur.c);
}
}
System.out.println(pos[p - 1].get(0).score);
}
static class Pair {
int r;
int c;
long score;
public Pair(int r, int c) {
this.r = r;
this.c = c;
}
}
static class Fenwick2D {
long[][] arr;
public Fenwick2D(int n, int m) {
arr = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = Integer.MAX_VALUE;
}
}
}
public long get(int x, int y) {
long res = Integer.MAX_VALUE;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1) {
for (int j = y; j >= 0; j = (j & (j + 1)) - 1) {
res = Math.min(res, arr[i][j]);
}
}
return res;
}
public void update(long value, int x, int y) {
for (int i = x; i < arr.length; i = i | (i + 1)) {
for (int j = y; j < arr[0].length; j = j | (j + 1)) {
arr[i][j] = Math.min(value, arr[i][j]);
}
}
}
public void erase(long value, int x, int y) {
for (int i = x; i < arr.length; i = i | (i + 1)) {
for (int j = y; j < arr[0].length; j = j | (j + 1)) {
arr[i][j] = value;
}
}
}
}
static class MyInputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public MyInputReader(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());
}
long[][] next2DArray(int n, int m) {
long[][] res = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
res[i][j] = nextInt();
}
}
return res;
}
}
} | Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | d464916bf760b0b17cd2340710565de6 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by ΠΠ»ΡΠ³Π° on 23.05.2016.
*/
public class ProblemD {
class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
StreamTokenizer in;
PrintWriter out;
int N, M, P;
static final long INF = 200000000000000000L;
public static void main(String[] args) throws IOException {
new ProblemD().run();
}
void run() throws IOException
{
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
private void solve() throws IOException{
N = nextInt();
M = nextInt();
P = nextInt();
ArrayList<Pair<Integer, Integer>>[] pairs = new ArrayList[P+1];
for (int i=0;i<P+1;i++){
pairs[i] = new ArrayList<>();
}
int[][] treasures = new int[N][M];
long[][] dist = new long[N][M];
for (int i=0;i<N;i++){
for (int j=0;j<M;j++){
treasures[i][j] = nextInt();
if (treasures[i][j] == 1) dist[i][j] = i + j;
else dist[i][j] = INF;
pairs[treasures[i][j]].add(new Pair(i, j));
}
}
boolean[] hasPrev = new boolean[N];
ArrayList<Integer>[] col = new ArrayList[M];
for (int i=0;i<M;i++){
col[i] = new ArrayList<>();
}
for (int p=1;p<P;p++){
Arrays.fill(hasPrev, false);
for (int j=0;j<M;j++)
col[j].clear();
for (Pair<Integer, Integer> pp : pairs[p]){
hasPrev[pp.getLeft()] = true;
}
for (Pair<Integer, Integer> pp : pairs[p+1]){
col[pp.getRight()].add(pp.getLeft());
}
long best;
for (int i = 0;i < N;i++){
if (hasPrev[i]){
best = INF;
for (int j = 0;j < M;j++){
best++;
if (treasures[i][j] == p){
best = Math.min(best, dist[i][j]);
}
for (Integer y: col[j]){
dist[y][j] = Math.min(dist[y][j], best + Math.abs(y-i));
}
}
best = INF;
for (int j = M-1;j >= 0;j--){
best++;
if (treasures[i][j] == p){
best = Math.min(best, dist[i][j]);
}
for (Integer y: col[j]){
dist[y][j] = Math.min(dist[y][j], best + Math.abs(y-i));
}
}
}
}
}
// for (int i=0;i<N;i++){
// System.out.println(Arrays.toString(dist[i]));
// }
Pair<Integer, Integer> end = pairs[P].get(0);
out.println(dist[end.getLeft()][end.getRight()]);
}
int nextInt() throws IOException
{
in.nextToken();
return (int)in.nval;
}
String next() throws IOException
{
in.nextToken();
return in.sval;
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | d028047ec73095a77e441f719a63c94b | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main extends PrintWriter {
final Random rand = new Random(31);
final int inf = (int) 1e9;
final long linf = (long) 1e18;
final static String IO = "_std";
class Item implements Comparable<Item> {
int d, x, y;
public Item(int d, int x, int y) {
this.d = d;
this.x = x;
this.y = y;
}
@Override
public int compareTo(Item o) {
return Integer.compare(d, o.d);
}
public Point getPoint() {
return new Point(x, y);
}
}
class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int p = nextInt();
List<Point>[] xs = createAdjacencyList(p + 1);
boolean f1 = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int x = nextInt();
if (i == 0 && j == 0 && x == 1) {
f1 = true;
}
xs[x].add(new Point(i, j));
}
}
int[][] td = new int[n][m];
for (int[] i : td) {
Arrays.fill(i, inf);
}
td[0][0] = 0;
xs[0].add(new Point(0, 0));
int[] dx = new int[] {1, -1, 0, 0};
int[] dy = new int[] {0, 0, 1, -1};
int[][] d = new int[n][m];
for (int t = 1; t <= p; t++) {
if (t == 2 && !f1) {
td[0][0] = inf;
}
if (xs[t].size() * xs[t - 1].size() <= n * m * 2) {
for (Point vp : xs[t]) {
for (Point pt : xs[t - 1]) {
td[vp.x][vp.y] = min(td[vp.x][vp.y], td[pt.x][pt.y] + abs(pt.x - vp.x) + abs(pt.y - vp.y));
}
}
} else {
Item[] willBeAddInFuture = new Item[xs[t - 1].size()];
Queue<Point> q = new ArrayDeque<>();
for (int[] i : d) {
Arrays.fill(i, inf);
}
int ind = 0;
for (Point pt : xs[t - 1]) {
willBeAddInFuture[ind++] = new Item(td[pt.x][pt.y], pt.x, pt.y);
d[pt.x][pt.y] = td[pt.x][pt.y];
}
Arrays.sort(willBeAddInFuture);
int index = 0;
while (true) {
if (index == willBeAddInFuture.length) break;
q.add(willBeAddInFuture[index++].getPoint());
while (!q.isEmpty()) {
Point v = q.poll();
int di = d[v.x][v.y];
while (index < willBeAddInFuture.length && willBeAddInFuture[index].d == di + 1) {
q.add(willBeAddInFuture[index++].getPoint());
}
for (int i = 0; i < 4; i++) {
int x = v.x + dx[i];
int y = v.y + dy[i];
if (x < 0 || x >= n || y < 0 || y >= m) {
continue;
}
if (d[x][y] > di + 1) {
d[x][y] = di + 1;
q.add(new Point(x, y));
}
}
}
}
for (Point pt : xs[t]) {
td[pt.x][pt.y] = d[pt.x][pt.y];
}
}
}
println(td[xs[p].get(0).x][xs[p].get(0).y]);
}
BufferedReader in;
StringTokenizer stok;
Main() {
super(System.out);
in = new BufferedReader(new InputStreamReader(System.in));
}
Main(String fileIn, String fileOut) throws IOException {
super(fileOut);
in = new BufferedReader(new FileReader(fileIn));
}
public static void main(String[] args) throws IOException {
Main main;
if ("_std".equals(IO)) {
main = new Main();
} else if ("_iotxt".equals(IO)) {
main = new Main("input.txt", "output.txt");
} else {
main = new Main(IO + ".in", IO + ".out");
}
main.solve();
main.close();
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.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());
}
int[] nextIntArray(int len) throws IOException {
int[] a = new int[len];
for (int i = 0; i < len; i++) {
a[i] = nextInt();
}
return a;
}
int[] nextIntArraySorted(int len) throws IOException {
int[] a = nextIntArray(len);
shuffle(a);
Arrays.sort(a);
return a;
}
void shuffle(int[] a) {
for (int i = 1; i < a.length; i++) {
int x = rand.nextInt(i + 1);
int _ = a[i];
a[i] = a[x];
a[x] = _;
}
}
void shuffleAndSort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
boolean nextPermutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a) {
if (p[a] < p[a + 1])
for (int b = p.length - 1; ; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
}
return false;
}
<T> List<T>[] createAdjacencyList(int n) {
List<T>[] res = new List[n];
for (int i = 0; i < n; i++) {
res[i] = new ArrayList<>();
}
return res;
}
void println(Object... a) {
for (int i = 0; i < a.length; i++) {
if (i != 0) {
print(" ");
}
print(a[i]);
}
println();
}
} | Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | c767e7ed90803c6a858de8be80da7828 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main extends PrintWriter {
final Random rand = new Random(31);
final int inf = (int) 1e9;
final long linf = (long) 1e18;
final static String IO = "_std";
class Item implements Comparable<Item> {
int d, x, y;
public Item(int d, int x, int y) {
this.d = d;
this.x = x;
this.y = y;
}
@Override
public int compareTo(Item o) {
return Integer.compare(d, o.d);
}
public Point getPoint() {
return new Point(x, y);
}
}
class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int p = nextInt();
List<Point>[] xs = createAdjacencyList(p + 1);
boolean f1 = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int x = nextInt();
if (i == 0 && j == 0 && x == 1) {
f1 = true;
}
xs[x].add(new Point(i, j));
}
}
int[][] td = new int[n][m];
for (int[] i : td) {
Arrays.fill(i, inf);
}
td[0][0] = 0;
xs[0].add(new Point(0, 0));
int[] dx = new int[] {1, -1, 0, 0};
int[] dy = new int[] {0, 0, 1, -1};
int[][] d = new int[n][m];
for (int t = 1; t <= p; t++) {
if (t == 2 && !f1) {
td[0][0] = inf;
}
if (xs[t].size() * xs[t - 1].size() <= n * m * 2) {
for (Point vp : xs[t]) {
for (Point pt : xs[t - 1]) {
td[vp.x][vp.y] = min(td[vp.x][vp.y], td[pt.x][pt.y] + abs(pt.x - vp.x) + abs(pt.y - vp.y));
}
}
} else {
Item[] willBeAddInFuture = new Item[xs[t - 1].size()];
Queue<Point> q = new ArrayDeque<>();
for (int[] i : d) {
Arrays.fill(i, inf);
}
int ind = 0;
for (Point pt : xs[t - 1]) {
willBeAddInFuture[ind++] = new Item(td[pt.x][pt.y], pt.x, pt.y);
d[pt.x][pt.y] = td[pt.x][pt.y];
}
Arrays.sort(willBeAddInFuture);
int index = 0;
while (true) {
if (index == willBeAddInFuture.length) break;
q.add(willBeAddInFuture[index++].getPoint());
while (!q.isEmpty()) {
Point v = q.poll();
int di = d[v.x][v.y];
while (index < willBeAddInFuture.length && willBeAddInFuture[index].d <= di + 1) {
q.add(willBeAddInFuture[index++].getPoint());
}
for (int i = 0; i < 4; i++) {
int x = v.x + dx[i];
int y = v.y + dy[i];
if (x < 0 || x >= n || y < 0 || y >= m) {
continue;
}
if (d[x][y] > di + 1) {
d[x][y] = di + 1;
q.add(new Point(x, y));
}
}
}
}
for (Point pt : xs[t]) {
td[pt.x][pt.y] = d[pt.x][pt.y];
}
}
}
println(td[xs[p].get(0).x][xs[p].get(0).y]);
}
BufferedReader in;
StringTokenizer stok;
Main() {
super(System.out);
in = new BufferedReader(new InputStreamReader(System.in));
}
Main(String fileIn, String fileOut) throws IOException {
super(fileOut);
in = new BufferedReader(new FileReader(fileIn));
}
public static void main(String[] args) throws IOException {
Main main;
if ("_std".equals(IO)) {
main = new Main();
} else if ("_iotxt".equals(IO)) {
main = new Main("input.txt", "output.txt");
} else {
main = new Main(IO + ".in", IO + ".out");
}
main.solve();
main.close();
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.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());
}
int[] nextIntArray(int len) throws IOException {
int[] a = new int[len];
for (int i = 0; i < len; i++) {
a[i] = nextInt();
}
return a;
}
int[] nextIntArraySorted(int len) throws IOException {
int[] a = nextIntArray(len);
shuffle(a);
Arrays.sort(a);
return a;
}
void shuffle(int[] a) {
for (int i = 1; i < a.length; i++) {
int x = rand.nextInt(i + 1);
int _ = a[i];
a[i] = a[x];
a[x] = _;
}
}
void shuffleAndSort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
boolean nextPermutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a) {
if (p[a] < p[a + 1])
for (int b = p.length - 1; ; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
}
return false;
}
<T> List<T>[] createAdjacencyList(int n) {
List<T>[] res = new List[n];
for (int i = 0; i < n; i++) {
res[i] = new ArrayList<>();
}
return res;
}
void println(Object... a) {
for (int i = 0; i < a.length; i++) {
if (i != 0) {
print(" ");
}
print(a[i]);
}
println();
}
} | Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | 44700a522f69888d506d981563634092 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.BufferedInputStream;
import java.util.*;
/**
* Created by leen on 6/2/16.
*/
public class Main {
static int[][] DELTAS = new int[][] {
{-1, 0},
{0, -1},
{1, 0},
{0, 1}
};
public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in));
while(scan.hasNext()) {
int numRows = scan.nextInt();
int numCols = scan.nextInt();
int numTypes = scan.nextInt();
int[][] grids = new int[numRows][numCols];
ArrayList<Point>[] pointsByType = new ArrayList[numTypes + 1];
ArrayList<Point> points0 = new ArrayList<Point>(1);
points0.add(new Point(0, 0, 0));
pointsByType[0] = points0;
for(int x = 1; x <= numTypes; x++)
pointsByType[x] = new ArrayList<Point>();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
int type = scan.nextInt();
pointsByType[type].add(new Point(i, j, Integer.MAX_VALUE));
}
}
for (int t = 1; t <= numTypes; t++) {
List<Point> points = pointsByType[t];
List<Point> lastPoints = pointsByType[t - 1];
if(points.size() * lastPoints.size() <= 10 * numRows * numCols) {
for (Point p : points) {
for (Point lp : lastPoints) {
int newDist = lp.calcDistance(p) + lp.minDistance;
if (newDist < p.minDistance)
p.minDistance = newDist;
}
}
}
else {
for(int[] gridsRow : grids)
Arrays.fill(gridsRow, -1);
Queue<Point> queue = new LinkedList<Point>();
for(Point p : lastPoints) {
queue.offer(p);
grids[p.x][p.y] = p.minDistance;
}
while(!queue.isEmpty()) {
Point p = queue.poll();
for(int k = 0; k < 4; k++) {
int[] delta = DELTAS[k];
int neibourX = p.x + delta[0], neibourY = p.y + delta[1];
if(neibourX < 0 || neibourX >= numRows || neibourY < 0 || neibourY >= numCols)
continue;
int currentDistanceOfNeibour = grids[neibourX][neibourY];
if(currentDistanceOfNeibour == -1 || currentDistanceOfNeibour > p.minDistance + 1) {
grids[neibourX][neibourY] = p.minDistance + 1;
queue.offer(new Point(neibourX, neibourY, p.minDistance + 1));
}
}
}
for(Point p : points)
p.minDistance = grids[p.x][p.y];
}
}
System.out.println(pointsByType[numTypes].get(0).minDistance);
}
}
static class Point {
final int x;
final int y;
Point next;
int minDistance;
Point(int x, int y, int minDistance) {
this.x = x;
this.y = y;
this.minDistance = minDistance;
}
@Override
public int hashCode() {
return x ^ y;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Point) {
Point that = (Point) obj;
return minDistance == that.minDistance && x == that.x && y == that.y;
}
else
return false;
}
int calcDistance(Point that) {
return Math.abs(x - that.x) + Math.abs(y - that.y);
}
}
} | Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | a0cb21738a035d1a91e55575157b1558 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.BufferedInputStream;
import java.util.*;
/**
* Created by leen on 6/2/16.
*/
public class Main {
static int[][] DELTAS = new int[][] {
{-1, 0},
{0, -1},
{1, 0},
{0, 1}
};
public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in));
while(scan.hasNext()) {
int numRows = scan.nextInt();
int numCols = scan.nextInt();
int numTypes = scan.nextInt();
int[][] grids = new int[numRows][numCols];
ArrayList<Point>[] pointsByType = new ArrayList[numTypes + 1];
ArrayList<Point> points0 = new ArrayList<Point>(1);
points0.add(new Point(0, 0, 0));
pointsByType[0] = points0;
for(int x = 1; x <= numTypes; x++)
pointsByType[x] = new ArrayList<Point>();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
int type = scan.nextInt();
pointsByType[type].add(new Point(i, j, Integer.MAX_VALUE));
}
}
for (int t = 1; t <= numTypes; t++) {
List<Point> points = pointsByType[t];
List<Point> lastPoints = pointsByType[t - 1];
if(points.size() * lastPoints.size() <= 15 * numRows * numCols) {
for (Point p : points) {
for (Point lp : lastPoints) {
int newDist = lp.calcDistance(p) + lp.minDistance;
if (newDist < p.minDistance)
p.minDistance = newDist;
}
}
}
else {
for(int[] gridsRow : grids)
Arrays.fill(gridsRow, -1);
Queue<Point> queue = new LinkedList<Point>();
for(Point p : lastPoints) {
queue.offer(p);
grids[p.x][p.y] = p.minDistance;
}
while(!queue.isEmpty()) {
Point p = queue.poll();
for(int k = 0; k < 4; k++) {
int[] delta = DELTAS[k];
int neibourX = p.x + delta[0], neibourY = p.y + delta[1];
if(neibourX < 0 || neibourX >= numRows || neibourY < 0 || neibourY >= numCols)
continue;
int currentDistanceOfNeibour = grids[neibourX][neibourY];
if(currentDistanceOfNeibour == -1 || currentDistanceOfNeibour > p.minDistance + 1) {
grids[neibourX][neibourY] = p.minDistance + 1;
queue.offer(new Point(neibourX, neibourY, p.minDistance + 1));
}
}
}
for(Point p : points)
p.minDistance = grids[p.x][p.y];
}
}
System.out.println(pointsByType[numTypes].get(0).minDistance);
}
}
static class Point {
final int x;
final int y;
Point next;
int minDistance;
Point(int x, int y, int minDistance) {
this.x = x;
this.y = y;
this.minDistance = minDistance;
}
@Override
public int hashCode() {
return x ^ y;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Point) {
Point that = (Point) obj;
return minDistance == that.minDistance && x == that.x && y == that.y;
}
else
return false;
}
int calcDistance(Point that) {
return Math.abs(x - that.x) + Math.abs(y - that.y);
}
}
} | Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | f24f0c8c7ad08a2999c9010c207c8443 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.BufferedInputStream;
import java.util.*;
/**
* Created by leen on 6/2/16.
*/
public class Main {
static int[][] DELTAS = new int[][] {
{-1, 0},
{0, -1},
{1, 0},
{0, 1}
};
public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in));
while(scan.hasNext()) {
int numRows = scan.nextInt();
int numCols = scan.nextInt();
int numTypes = scan.nextInt();
int[][] grids = new int[numRows][numCols];
ArrayList<Point>[] pointsByType = new ArrayList[numTypes + 1];
ArrayList<Point> points0 = new ArrayList<Point>(1);
points0.add(new Point(0, 0, 0));
pointsByType[0] = points0;
for(int x = 1; x <= numTypes; x++)
pointsByType[x] = new ArrayList<Point>();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
int type = scan.nextInt();
pointsByType[type].add(new Point(i, j, Integer.MAX_VALUE));
}
}
for (int t = 1; t <= numTypes; t++) {
List<Point> points = pointsByType[t];
List<Point> lastPoints = pointsByType[t - 1];
if(points.size() * lastPoints.size() <= 30 * numRows * numCols) {
for (Point p : points) {
for (Point lp : lastPoints) {
int newDist = lp.calcDistance(p) + lp.minDistance;
if (newDist < p.minDistance)
p.minDistance = newDist;
}
}
}
else {
for(int[] gridsRow : grids)
Arrays.fill(gridsRow, -1);
Queue<Point> queue = new LinkedList<Point>();
for(Point p : lastPoints) {
queue.offer(p);
grids[p.x][p.y] = p.minDistance;
}
while(!queue.isEmpty()) {
Point p = queue.poll();
for(int k = 0; k < 4; k++) {
int[] delta = DELTAS[k];
int neibourX = p.x + delta[0], neibourY = p.y + delta[1];
if(neibourX < 0 || neibourX >= numRows || neibourY < 0 || neibourY >= numCols)
continue;
int currentDistanceOfNeibour = grids[neibourX][neibourY];
if(currentDistanceOfNeibour == -1 || currentDistanceOfNeibour > p.minDistance + 1) {
grids[neibourX][neibourY] = p.minDistance + 1;
queue.offer(new Point(neibourX, neibourY, p.minDistance + 1));
}
}
}
for(Point p : points)
p.minDistance = grids[p.x][p.y];
}
}
System.out.println(pointsByType[numTypes].get(0).minDistance);
}
}
static class Point {
final int x;
final int y;
Point next;
int minDistance;
Point(int x, int y, int minDistance) {
this.x = x;
this.y = y;
this.minDistance = minDistance;
}
@Override
public int hashCode() {
return x ^ y;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Point) {
Point that = (Point) obj;
return minDistance == that.minDistance && x == that.x && y == that.y;
}
else
return false;
}
int calcDistance(Point that) {
return Math.abs(x - that.x) + Math.abs(y - that.y);
}
}
} | Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | 52883cec4db26597b6af882562da0ffc | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/** Class: VanyaAndTreasure.java
* @author
* @version 1.0 <p>
* Course:
* Written / Updated: Jun 12, 2016
*
* This Class - See VanyaAndTreasure.pdf for instructions.
* VERDICT: (most likely correct but not fast enough)
* Consider a modified dynamic programming or BFS, or in the alternative
* try a tighter heuristic for A*?
*
* UPDATE: Tried a tighter heuristic for A*...not good. The time it takes to compute a tighter heuristic for A*
* might as well be used to compute all pairs shortest paths, which takes too long anyway.
*
* UPDATE 2: Dynamic programming takes too long where there are lots of rooms of chest type x and/or lots of rooms of chest type x+1.
* In this case, a sweep of all the rooms with a BFS / Dyn-programming combo is more efficient.
*
* UPDATED VERDICT: PASS
*/
public class VanyaAndTreasure {
/**
* This class describes the room at a certain (x,y) location in the grid.
* @author PP
*
*/
private class Cell implements Comparable<Cell>{
private int type; //the chest type (from 1 to p inclusive) that this cell contains.
private int row, col; //row / col index of this room cell.
private int distance;
// private int pos1D;
Cell(int type,int row, int col) {
this.type = type;
this.row = row;
this.col = col;
// this.pos1D = m * row + col;
this.distance = Integer.MAX_VALUE;
}
/* For debugging only */
@Override
public String toString() {
return String.format("(%s, %s) dist: %s", row, col, distance);
}
@Override
public int compareTo(Cell c) {
return this.distance - c.distance;
}
}
//end private class Cell
/*** BEGIN class VanyaAndTreasure ***/
/* the number of rows and columns in the table representing the palace and
* the number of different types of the chests, respectively, where
* (1 <= n, m <= 300, and 1 <= p <= n*m) */
private int n, m, p;
private Cell[][] roomArr; //Keeps track of Cell in every room at location (i,j)
private int[][] shortestDist; //Keeps track of shortest possible distance to room location at (i,j)
/* Will map each chest type (from 1 to p, inclusive) to a list of ALL rooms
* in which that chest is located.
* NOTE: the rooms will be saved in the form of a single integer that represents
* the row and column values.
*
* EXAMPLE: if a chest type 2 is located in rooms (2,3) and (1,0), and
* the rooms are in a 4x4 grid, then the array will save the following:
* chestTypeToRoomLocation[2] = {11, 4}
*
* where (2,3) is represented as 2*4+3 = 11, and
* (1,0) is represented as 1*4+0 = 4.
* */
LinkedList<Integer>[] chestTypeToRoomLocation;
HashMap<Integer, LinkedList<Integer>> chestTypeToRoomLocationsMap;
/* An Array containing Arrays of neighboring cells for rooms of given chest type x.
* neighboringCellsAscending[x] = {All Cells containing chest of type x+1} */
Cell[][] neighboringCellsAscending;
/* The goal destination Cell, which has chest type p (where p is the last integer in a given input problem). */
Cell destinationCell;
/**
* constructor.
*/
public VanyaAndTreasure() {
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
//Read the first line
String line = rd.readLine();
StringTokenizer tokenizer = new StringTokenizer(line);
this.n = Integer.parseInt(tokenizer.nextToken());
this.m = Integer.parseInt(tokenizer.nextToken());
this.p = Integer.parseInt(tokenizer.nextToken());
/* Read what this array of LinkedLists is all about near the top of this file.
* Allocating p + 1 space as we'll have the index go from 1 to p inclusive. */
this.chestTypeToRoomLocationsMap = new HashMap<>();
//Unavoidable warning; flaw of Java generics
this.chestTypeToRoomLocation = (LinkedList<Integer>[])new LinkedList<?>[this.p + 1];
/* Initialize room Array */
this.roomArr = new Cell[n][m];
/* Read the next n lines. Each line will have m entries. Use these values to
* create a 2-D array roomArr. */
for (int i = 0; i < n; i++) {
line = rd.readLine();
tokenizer = new StringTokenizer(line);
for (int j = 0; j < m; j++) {
int chestType = Integer.parseInt(tokenizer.nextToken());
this.roomArr[i][j] = new Cell(chestType, i, j); //create new room
// LinkedList<Integer> tempList = chestTypeToRoomLocationsMap.get(chestType);
LinkedList<Integer> tempList = chestTypeToRoomLocation[chestType];
/* if hashmap hasn't yet created the linkedlist associated with this chestType,
* initialize a new linked list, then add the current room to the linkedlist */
if (tempList == null) {
tempList = new LinkedList<>();
// chestTypeToRoomLocationsMap.put(chestType, tempList);
chestTypeToRoomLocation[chestType] = tempList;
}
tempList.add(i * m + j); //Add this room to the linkedlist associated with the hashmap
/* If the value we read pertains to the final chest type p, then we know
* that this is the ultimate destination, and that there is only ONE chest
* of this type. So let's save this cell for future reference. */
if (chestType == this.p) {
this.destinationCell = this.roomArr[i][j];
}
}
}
//end for i
// this.allPairsLongestPath = new int[n*m + 1][n*m + 1];
this.shortestDist = new int[n][m];
for (int i = 0; i < shortestDist.length; i++) {
Arrays.fill(shortestDist[i], 99999999);
}
// for (int[] paths: allPairsLongestPath) Arrays.fill(paths, -1);
// this.neighboringCells = new HashMap<>();
this.neighboringCellsAscending = new Cell[p][];
//Print out the final answer
System.out.println(this.shortestDistIterative());
rd.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private int shortestDistIterative() {
/* Let's initialize the "shortest" distances for rooms with chest type 1.
* Since Vanya always begins at (0,0), it's trivial to initialize these distances. */
Cell[] cellsWithChestType1 = neighboringCellsAscending[0];
if (cellsWithChestType1 == null || cellsWithChestType1.length == 0) { //if no neighbors have been initialized yet...
cellsWithChestType1 = getNeighboringCells(0, true); //invoke custom method
neighboringCellsAscending[0] = cellsWithChestType1; //and save it to the array so we don't do same computation twice
}
for (Cell cellWithChestType1 : cellsWithChestType1) {
shortestDist[cellWithChestType1.row][cellWithChestType1.col] = cellWithChestType1.row + cellWithChestType1.col;
// cellWithChestType1.distance = shortestDist[cellWithChestType1.row][cellWithChestType1.col];
}
for (int i = 1; i < p; ++i) {
Cell[] neighbors = neighboringCellsAscending[i];
if (neighbors == null) { //if no neighbors have been initialized yet...
neighbors = getNeighboringCells(i, true); //invoke custom method
neighboringCellsAscending[i] = neighbors; //and save it to the array so we don't do same computation twice
}
Cell[] prevNeighbors = neighboringCellsAscending[i - 1];
/* If there are too many of these types of rooms, a bfs is more efficient */
if (prevNeighbors.length * neighbors.length >= this.n * this.m) {
this.bfs2(prevNeighbors, neighbors);
continue; //continue to the next loop
}
/* Otherwise, this dyn. programming method is efficient enough. */
for (Cell neighbor : neighbors) {
// int shortestDistance = Integer.MAX_VALUE;
// int currDist;
for (Cell prevNeighbor : prevNeighbors) {
// currDist = shortestDist[prevNeighbor.row][prevNeighbor.col] + getDist(prevNeighbor, neighbor);
// if (currDist < shortestDistance) {
// shortestDistance = currDist;
// }
shortestDist[neighbor.row][neighbor.col] = Math.min(shortestDist[neighbor.row][neighbor.col],
shortestDist[prevNeighbor.row][prevNeighbor.col] + getDist(prevNeighbor, neighbor));
}
// shortestDist[neighbor.row][neighbor.col] = shortestDistance;
// neighbor.distance = shortestDist[neighbor.row][neighbor.col];
}
//end for Cell neighbor: neighbors
}
//end for i
return shortestDist[this.destinationCell.row][this.destinationCell.col];
}
private void bfs2(Cell[] prevNeighbors, Cell[] neighbors) {
int[][] distance = new int[n][m];
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++)
distance[i][j] = Integer.MAX_VALUE - 1;
for (Cell p : prevNeighbors)
distance[p.row][p.col] = shortestDist[p.row][p.col];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) {
if (i+1 < n) distance[i + 1][j] = Math.min(distance[i + 1][j], distance[i][j] + 1);
if (j+1 < n) distance[i][j + 1] = Math.min(distance[i][j + 1], distance[i][j] + 1);
}
for (int i = n-1; i >= 0; i--) for (int j = m-1; j >= 0; j--) {
if (i-1 >= 0) distance[i - 1][j] = Math.min(distance[i - 1][j], distance[i][j] + 1);
if (j-1 >= 0) distance[i][j - 1] = Math.min(distance[i][j - 1], distance[i][j] + 1);
}
for (Cell cell : neighbors)
shortestDist[cell.row][cell.col] = distance[cell.row][cell.col];
}
private void bfs(Cell[] prevNeighbors, Cell[] neighbors) {
// Arrays.sort(prevNeighbors);
PriorityQueue<Cell> minPQ = new PriorityQueue<Cell>(Arrays.asList(prevNeighbors));
// int[][] tmpShortestDist = new int[n][m];
// for (int[] row : tmpShortestDist) {
// Arrays.fill(row, Integer.MAX_VALUE);
// }
boolean[][] visited = new boolean[n][m];
for (int i = 0; i < this.n; i++) {
for (int j = 0; j < this.m; j++) {
if (this.roomArr[i][j].type == prevNeighbors[0].type) {
this.roomArr[i][j].distance = this.shortestDist[i][j];
visited[i][j] = true;
}
else {
this.roomArr[i][j].distance = Integer.MAX_VALUE;
}
}
}
// for (Cell prev : prevNeighbors) {
// tmpShortestDist[prev.row][prev.col] = this.shortestDist[prev.row][prev.col];
// }
// int currDistance = this.shortestDist[prevNeighbors[0].row][prevNeighbors[0].col];
int numOfCurrNeighborsVisited = 0;
// ArrayList<Cell> visited = new ArrayList<>(minPQ);
while (numOfCurrNeighborsVisited < neighbors.length) {
Cell currCell = minPQ.remove();
ArrayList<Cell> bfsNeighbors = getBFSNeighbors(currCell, visited);
for (Cell bfsNeighbor: bfsNeighbors) {
// if (visited.contains(bfsNeighbor))
// continue;
if (bfsNeighbor.distance > currCell.distance + 1) {
bfsNeighbor.distance = currCell.distance + 1;
// minPQ.remove(bfsNeighbor);
minPQ.add(bfsNeighbor);
visited[bfsNeighbor.row][bfsNeighbor.col] = true;
if (bfsNeighbor.type == neighbors[0].type) {
numOfCurrNeighborsVisited++;
}
}
}
//end for Cell
}
//end while
for (Cell neighbor : neighbors) {
this.shortestDist[neighbor.row][neighbor.col] = neighbor.distance;
}
}
//end private void bfs
private ArrayList<Cell> getBFSNeighbors(Cell currCell, boolean[][] visited) {
int row = currCell.row;
int col = currCell.col;
int maxPossibleNeighbors = 4;
// if (row - 1 < 0) maxPossibleNeighbors--;
// if (row + 1 >= this.n) maxPossibleNeighbors--;
// if (col - 1 < 0) maxPossibleNeighbors--;
// if (col + 1 >= this.m) maxPossibleNeighbors--;
ArrayList<Cell> bfsNeighbors = new ArrayList<>();
int[] rowOffset = {0, 0, 1,-1};
int[] colOffset = {1,-1, 0, 0};
for (int i = 0; i < maxPossibleNeighbors; i++) {
int neighborRow = row + rowOffset[i];
int neighborCol = col + colOffset[i];
if (neighborRow < 0 || neighborCol < 0 ||
neighborRow >= this.n || neighborCol >= this.m ||
visited[neighborRow][neighborCol] == true) {
continue;
}
Cell bfsNeighbor = this.roomArr[neighborRow][neighborCol];
bfsNeighbors.add(bfsNeighbor);
}
return bfsNeighbors;
}
// private int shortestDist(Cell cell) {
// if (cell.type < 1) throw new RuntimeException();
// if (allPairsLongestPath[0][cell.pos1D] != -1) {
// return allPairsLongestPath[0][cell.pos1D];
// }
// if (cell.type == 1) {
// allPairsLongestPath[0][cell.pos1D] = cell.row + cell.col;
// return allPairsLongestPath[0][cell.pos1D];
// }
//
//
// Cell[] neighbors = neighboringCells.get(cell.type); //get the neighbors from the hashmap above
// if (neighbors == null) { //if no neighbors have been initialized yet...
// neighbors = getNeighboringCells(cell.type, false); //invoke custom method
// neighboringCells.put(cell.type, neighbors); //and save it to the hashmap so we don't do same computation twice
// }
//
// int shortestDist = Integer.MAX_VALUE;
// for (Cell neighbor : neighbors) {
// int currDistToThisCell = getDist(cell, neighbor) + shortestDist(neighbor);
// if (currDistToThisCell < shortestDist) {
// shortestDist = currDistToThisCell;
// }
// }
//
// allPairsLongestPath[0][cell.pos1D] = shortestDist;
// return allPairsLongestPath[0][cell.pos1D];
// }
/**
* Method: getNeighboringCells
* @param chestType
* @return
*/
private Cell[] getNeighboringCells(int chestType, boolean ascending) {
/* All chests of type x - 1 can open chests of type x, so neighboring rooms of type x
* contain chests of chestType x - 1. */
LinkedList<Integer> neighborRooms = this.chestTypeToRoomLocation[ascending? chestType + 1 : chestType - 1];
if (neighborRooms == null) {
return new Cell[0];
}
Cell[] neighbors = new Cell[neighborRooms.size()];
ListIterator<Integer> iter = neighborRooms.listIterator();
for (int i = 0; i < neighbors.length; i++) {
int thisRoom = iter.next();
int thisRow = thisRoom / this.m;
int thisCol = thisRoom % this.m;
neighbors[i] = this.roomArr[thisRow][thisCol];
}
return neighbors;
}
private int getDist(Cell c1, Cell c2) {
return Math.abs(c1.row - c2.row) + Math.abs(c1.col - c2.col);
}
/**
* Method: minTotalDistToGetTreasure
* @return the minimum possible total distance Vanya has to walk
* in order to get the treasure from the chest of type this.p.
*/
// private int minTotalDistToGetTreasure() {
//
// /* This will save all neighboring cells for a given chest type for easy reference and efficiency. */
//// this.neighboringCells = new HashMap<>();
////
//// /* Might be worth it to try something like A* for this one...
//// * First set the neighbors of each chest type in all the rooms */
//// for (int i = 0; i < this.roomArr.length; i++) {
//// for (int j = 0; j < this.roomArr[i].length; j++) {
//// Cell thisCell = this.roomArr[i][j];
//// int chestType = thisCell.type;
////
//// //Set all the neighbors
//// Cell[] neighbors = neighboringCells.get(chestType); //get the neighbors from the hashmap above
//// if (neighbors == null) { //if no neighbors have been initialized yet...
//// neighbors = getNeighboringCells(chestType); //invoke custom method
//// neighboringCells.put(chestType, neighbors); //and save it to the hashmap so we don't do same computation twice
//// }
////// thisCell.neighborArr = neighbors; //set the neighbors for this cell
////
//// /* Set the estimated manhattan distance from this cell to destination cell,
//// * provided that the manhattan distance cannot be shorter than the difference
//// * between destination chest type and this chest type.
//// *
//// * For example, if this cell type == 2 and destination cell type == 5,
//// * it will take at least 3 unlocking steps to get to the destination chest.
//// * So, if the manhattan distance between this cell and destination cell is only 2,
//// * we still have to set the est. distance at 3. */
////// thisCell.estDistRemaining = Math.max(
////// this.destinationCell.type - thisCell.type,
////// Math.abs(this.destinationCell.row - thisCell.row) + Math.abs(this.destinationCell.col - thisCell.col));
//// thisCell.computeEstDist();
////
//// }
//// //end for j
//// }
// //end for i
//
// /* Since we start at the upper leftmost corner -- i.e. the location (0,0) -- we'll first get
// * the locations of all the rooms with chest type 1 in it (remember, these chest types don't need keys)
// * and set them as the initial "neighbors".
// *
// * We call the below method with parameter 0 (although technically there is no chestType with value 0)
// * because doing so will give us an array of all the cells that have chestType 1. */
//
// Cell[] initialNeighbors = this.getNeighboringCells(0);
//
// /* Now put these in a prioritylist. Since the Cell objects implement the Comparable interface,
// * they will be "sorted" from smallest to largest in the priorityqueue. */
// PriorityQueue<Cell> pq = new PriorityQueue<>(Arrays.asList(initialNeighbors));
//
// /* Testing priorityquee */
//// while (!pq.isEmpty()) {
//// System.out.println(pq.remove());
//// }
//
// Cell currRoom = null;
//
// /* Begin A* algorithm */
// HashSet<Cell> openList = new HashSet<>(pq);
// HashSet<Cell> closedList = new HashSet<>();
// while (currRoom != this.destinationCell && !pq.isEmpty()) {
// currRoom = pq.remove();
// currRoom.visited = true;
// openList.remove(currRoom);
// closedList.add(currRoom);
// Cell[] neighbors = neighboringCells.get(currRoom.type);
// for (Cell neighbor: neighbors) {
// if (!neighbor.visited && neighbor.distSoFar > currRoom.distSoFar + this.getDist(currRoom, neighbor)) {
// neighbor.distSoFar = currRoom.distSoFar + this.getDist(currRoom, neighbor);
// pq.remove(neighbor);
// pq.add(neighbor);
// openList.add(neighbor);
// }
// }
// //end for
// }
// //end while
//
// if (currRoom == this.destinationCell) {
// return currRoom.distSoFar + currRoom.estDistRemaining;
// }
// return -1;
// }
public static void main(String[] args) {
new VanyaAndTreasure();
// System.out.println(vt.minTotalDistToGetTreasure());
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | 356c346401d33952ccb9987d3108a941 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.StringTokenizer;
/** Class: VanyaAndTreasure.java
* @author
* @version 1.0 <p>
* Course:
* Written / Updated: Jun 12, 2016
*
* This Class - See VanyaAndTreasure.pdf for instructions.
* VERDICT: (most likely correct but not fast enough)
* Consider a modified dynamic programming or BFS, or in the alternative
* try a tighter heuristic for A*?
*
* UPDATE: Tried a tighter heuristic for A*...not good. The time it takes to compute a tighter heuristic for A*
* might as well be used to compute all pairs shortest paths, which takes too long anyway.
*
* UPDATE 2: Dynamic programming takes too long where there are lots of rooms of chest type x and/or lots of rooms of chest type x+1.
* In this case, a sweep of all the rooms with a BFS / Dyn-programming combo is more efficient.
*
* UPDATED VERDICT: PASS
*/
public class VanyaAndTreasure {
/**
* This class describes the room at a certain (x,y) location in the grid.
* @author PP
*
*/
private class Cell implements Comparable<Cell>{
// private int type; //the chest type (from 1 to p inclusive) that this cell contains.
private int row, col; //row / col index of this room cell.
private int distance; //Used for the original bfs() method ONLY. Has no relation to the global shortestDist[][] array!
// private int pos1D;
Cell(int type,int row, int col) {
// this.type = type;
this.row = row;
this.col = col;
// this.pos1D = m * row + col;
this.distance = Integer.MAX_VALUE;
}
/* For debugging only */
@Override
public String toString() {
return String.format("(%s, %s) dist: %s", row, col, distance);
}
@Override
public int compareTo(Cell c) {
return this.distance - c.distance;
}
}
//end private class Cell
/*** BEGIN class VanyaAndTreasure ***/
/* the number of rows and columns in the table representing the palace and
* the number of different types of the chests, respectively, where
* (1 <= n, m <= 300, and 1 <= p <= n*m) */
private int n, m, p;
private Cell[][] roomArr; //Keeps track of Cell in every room at location (i,j)
private int[][] shortestDist; //Keeps track of shortest possible distance to room location at (i,j)
/* Will map each chest type (from 1 to p, inclusive) to a list of ALL rooms
* in which that chest is located.
* NOTE: the rooms will be saved in the form of a single integer that represents
* the row and column values.
*
* EXAMPLE: if a chest type 2 is located in rooms (2,3) and (1,0), and
* the rooms are in a 4x4 grid, then the array will save the following:
* chestTypeToRoomLocation[2] = {11, 4}
*
* where (2,3) is represented as 2*4+3 = 11, and
* (1,0) is represented as 1*4+0 = 4.
* */
LinkedList<Integer>[] chestTypeToRoomLocation;
/* An Array containing Arrays of neighboring cells for rooms of given chest type x.
* neighboringCellsAscending[x] = {All Cells containing chest of type x+1} */
Cell[][] neighboringCellsAscending;
/* The goal destination Cell, which has chest type p (where p is the last integer in a given input problem). */
Cell destinationCell;
/**
* constructor.
*/
@SuppressWarnings("unchecked")
public VanyaAndTreasure() {
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
//Read the first line
String line = rd.readLine();
StringTokenizer tokenizer = new StringTokenizer(line);
this.n = Integer.parseInt(tokenizer.nextToken());
this.m = Integer.parseInt(tokenizer.nextToken());
this.p = Integer.parseInt(tokenizer.nextToken());
/* Read what this array of LinkedLists is all about near the top of this file.
* Allocating p + 1 space as we'll have the index go from 1 to p inclusive. */
//Unavoidable warning; flaw of Java generics. Used SuppressWarning() at the top of this constructor method.
this.chestTypeToRoomLocation = (LinkedList<Integer>[])new LinkedList<?>[this.p + 1];
/* Initialize room Array */
this.roomArr = new Cell[n][m];
/* Read the next n lines. Each line will have m entries. Use these values to
* create a 2-D array roomArr. */
for (int i = 0; i < n; i++) {
line = rd.readLine();
tokenizer = new StringTokenizer(line);
for (int j = 0; j < m; j++) {
int chestType = Integer.parseInt(tokenizer.nextToken());
this.roomArr[i][j] = new Cell(chestType, i, j); //create new room
LinkedList<Integer> tempList = chestTypeToRoomLocation[chestType];
/* if Array above hasn't yet created the linkedlist associated with this chestType,
* initialize a new linked list, then add the current room to the linkedlist */
if (tempList == null) {
tempList = new LinkedList<>();
chestTypeToRoomLocation[chestType] = tempList;
}
tempList.add(i * m + j); //Add this room to the linkedlist associated with the hashmap
/* If the value we read pertains to the final chest type p, then we know
* that this is the ultimate destination, and that there is only ONE chest
* of this type. So let's save this cell for future reference. */
if (chestType == this.p) {
this.destinationCell = this.roomArr[i][j];
}
}
//end for j
}
//end for i
this.shortestDist = new int[n][m];
for (int i = 0; i < shortestDist.length; i++) {
Arrays.fill(shortestDist[i], 99999999);
}
this.neighboringCellsAscending = new Cell[p][];
//Print out the final answer
System.out.println(this.shortestDistIterative());
rd.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private int shortestDistIterative() {
/* Let's initialize the "shortest" distances for rooms with chest type 1.
* Since Vanya always begins at (0,0), it's trivial to initialize these distances. */
Cell[] cellsWithChestType1 = neighboringCellsAscending[0];
if (cellsWithChestType1 == null || cellsWithChestType1.length == 0) { //if no neighbors have been initialized yet...
cellsWithChestType1 = getNeighboringCells(0, true); //invoke custom method
neighboringCellsAscending[0] = cellsWithChestType1; //and save it to the array so we don't do same computation twice
}
for (Cell cellWithChestType1 : cellsWithChestType1) {
shortestDist[cellWithChestType1.row][cellWithChestType1.col] = cellWithChestType1.row + cellWithChestType1.col;
}
for (int i = 1; i < p; ++i) {
Cell[] neighbors = neighboringCellsAscending[i];
if (neighbors == null) { //if no neighbors have been initialized yet...
neighbors = getNeighboringCells(i, true); //invoke custom method
neighboringCellsAscending[i] = neighbors; //and save it to the array so we don't do same computation twice
}
Cell[] prevNeighbors = neighboringCellsAscending[i - 1];
/* If there are too many of these types of rooms, a bfs is more efficient */
if (prevNeighbors.length * neighbors.length >= this.n * this.m) {
this.bfs2(prevNeighbors, neighbors);
/* Otherwise, this dyn. programming method is efficient enough. */
} else {
for (Cell neighbor : neighbors) {
for (Cell prevNeighbor : prevNeighbors) {
shortestDist[neighbor.row][neighbor.col] = Math.min(shortestDist[neighbor.row][neighbor.col],
shortestDist[prevNeighbor.row][prevNeighbor.col] + getDist(prevNeighbor, neighbor));
}
}
//end for Cell neighbor: neighbors
}
//end if/else
}
//end for i
return shortestDist[this.destinationCell.row][this.destinationCell.col];
}
//end private int shortestDistIterative
/**
* Method: bfs2
* @param prevNeighbors
* @param neighbors
* Efficient version of multiple-source and multiple-destination BFS. Better than bfs().
*/
private void bfs2(Cell[] prevNeighbors, Cell[] neighbors) {
/* Initialize the temporary array of shortest distances. We'll update the global array at the end of this method. */
int[][] distance = new int[n][m];
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++)
distance[i][j] = 99999999;
/* Initialize the shortest possible distances for the prev. neighboring rooms.
* We'll propagate BFS from these locations, where we KNOW we have the shortest way of reaching them. */
for (Cell p : prevNeighbors)
distance[p.row][p.col] = shortestDist[p.row][p.col];
/* We'll explore all the ways in which can move either RIGHT or DOWN, and update the temporary
* 2D array distance accordingly. Notice we're starting from the top-left corner to ensure
* we explore all possibilities. */
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) {
if (i+1 < n) distance[i + 1][j] = Math.min(distance[i + 1][j], distance[i][j] + 1);
if (j+1 < n) distance[i][j + 1] = Math.min(distance[i][j + 1], distance[i][j] + 1);
}
/* We'll now explore all the ways in which can move either LEFT or UP, and update the temporary
* 2D array distance accordingly. Note we're starting from the bottom-right corner this time. */
for (int i = n-1; i >= 0; i--) for (int j = m-1; j >= 0; j--) {
if (i-1 >= 0) distance[i - 1][j] = Math.min(distance[i - 1][j], distance[i][j] + 1);
if (j-1 >= 0) distance[i][j - 1] = Math.min(distance[i][j - 1], distance[i][j] + 1);
}
/* Now distance[i][j] contains the shortest possible distance for all cells, starting
* from any one of the cells contained in the array prevNeighbors. So we can update
* the global shortestDist array for the array of cells that we're concerned with, i.e. neighbors. */
for (Cell cell : neighbors)
shortestDist[cell.row][cell.col] = distance[cell.row][cell.col];
}
/**
* Method: bfs
* @param prevNeighbors
* @param neighbors
*
* UPDATE: not as efficient as bfs2() method.
*/
// private void bfs(Cell[] prevNeighbors, Cell[] neighbors) {
// PriorityQueue<Cell> minPQ = new PriorityQueue<Cell>(Arrays.asList(prevNeighbors));
// boolean[][] visited = new boolean[n][m];
//
// /* Initialize the distance attribute for each Cell, for purposes of this BFS only. */
// for (int i = 0; i < this.n; i++) {
// for (int j = 0; j < this.m; j++) {
// if (this.roomArr[i][j].type == prevNeighbors[0].type) {
// this.roomArr[i][j].distance = this.shortestDist[i][j];
// visited[i][j] = true;
// }
// else {
// this.roomArr[i][j].distance = Integer.MAX_VALUE;
// }
// }
// }
//
// int numOfCurrNeighborsVisited = 0;
//
// while (numOfCurrNeighborsVisited < neighbors.length) {
// Cell currCell = minPQ.remove();
// ArrayList<Cell> bfsNeighbors = getBFSNeighbors(currCell, visited);
// for (Cell bfsNeighbor: bfsNeighbors) {
// if (bfsNeighbor.distance > currCell.distance + 1) {
// bfsNeighbor.distance = currCell.distance + 1;
// minPQ.add(bfsNeighbor);
// visited[bfsNeighbor.row][bfsNeighbor.col] = true;
// if (bfsNeighbor.type == neighbors[0].type) {
// numOfCurrNeighborsVisited++;
// }
// }
// }
// //end for Cell
// }
// //end while
//
// for (Cell neighbor : neighbors) {
// this.shortestDist[neighbor.row][neighbor.col] = neighbor.distance;
// }
// }
//end private void bfs
/**
* Method: getBFSNeighbors
* @param currCell
* @param visited
* @return
* Helper method for bfs(). No longer needed.
*/
// private ArrayList<Cell> getBFSNeighbors(Cell currCell, boolean[][] visited) {
// int row = currCell.row;
// int col = currCell.col;
// int maxPossibleNeighbors = 4;
//
// ArrayList<Cell> bfsNeighbors = new ArrayList<>();
// int[] rowOffset = {0, 0, 1,-1};
// int[] colOffset = {1,-1, 0, 0};
// for (int i = 0; i < maxPossibleNeighbors; i++) {
// int neighborRow = row + rowOffset[i];
// int neighborCol = col + colOffset[i];
// if (neighborRow < 0 || neighborCol < 0 ||
// neighborRow >= this.n || neighborCol >= this.m ||
// visited[neighborRow][neighborCol] == true) {
// continue;
// }
// Cell bfsNeighbor = this.roomArr[neighborRow][neighborCol];
// bfsNeighbors.add(bfsNeighbor);
// }
// return bfsNeighbors;
// }
/**
* Method: getNeighboringCells
* @param chestType
* @return
*/
private Cell[] getNeighboringCells(int chestType, boolean ascending) {
/* All chests of type x - 1 can open chests of type x, so neighboring rooms of type x
* contain chests of chestType x - 1. */
LinkedList<Integer> neighborRooms = this.chestTypeToRoomLocation[ascending? chestType + 1 : chestType - 1];
if (neighborRooms == null) {
return new Cell[0];
}
Cell[] neighbors = new Cell[neighborRooms.size()];
ListIterator<Integer> iter = neighborRooms.listIterator();
for (int i = 0; i < neighbors.length; i++) {
int thisRoom = iter.next();
int thisRow = thisRoom / this.m;
int thisCol = thisRoom % this.m;
neighbors[i] = this.roomArr[thisRow][thisCol];
}
return neighbors;
}
private int getDist(Cell c1, Cell c2) {
return Math.abs(c1.row - c2.row) + Math.abs(c1.col - c2.col);
}
/**
* Method: minTotalDistToGetTreasure
* @return the minimum possible total distance Vanya has to walk
* in order to get the treasure from the chest of type this.p.
*
* This uses A*. However, since the heuristic is poor, this is inefficient.
* We could try to improve the heuristic, but in the time it takes to do that,
* we're better off just running the dynamic programming + bfs2() methods above.
*/
// private int minTotalDistToGetTreasure() {
//
// /* This will save all neighboring cells for a given chest type for easy reference and efficiency. */
//// this.neighboringCells = new HashMap<>();
////
//// /* Might be worth it to try something like A* for this one...
//// * First set the neighbors of each chest type in all the rooms */
//// for (int i = 0; i < this.roomArr.length; i++) {
//// for (int j = 0; j < this.roomArr[i].length; j++) {
//// Cell thisCell = this.roomArr[i][j];
//// int chestType = thisCell.type;
////
//// //Set all the neighbors
//// Cell[] neighbors = neighboringCells.get(chestType); //get the neighbors from the hashmap above
//// if (neighbors == null) { //if no neighbors have been initialized yet...
//// neighbors = getNeighboringCells(chestType); //invoke custom method
//// neighboringCells.put(chestType, neighbors); //and save it to the hashmap so we don't do same computation twice
//// }
////// thisCell.neighborArr = neighbors; //set the neighbors for this cell
////
//// /* Set the estimated manhattan distance from this cell to destination cell,
//// * provided that the manhattan distance cannot be shorter than the difference
//// * between destination chest type and this chest type.
//// *
//// * For example, if this cell type == 2 and destination cell type == 5,
//// * it will take at least 3 unlocking steps to get to the destination chest.
//// * So, if the manhattan distance between this cell and destination cell is only 2,
//// * we still have to set the est. distance at 3. */
////// thisCell.estDistRemaining = Math.max(
////// this.destinationCell.type - thisCell.type,
////// Math.abs(this.destinationCell.row - thisCell.row) + Math.abs(this.destinationCell.col - thisCell.col));
//// thisCell.computeEstDist();
////
//// }
//// //end for j
//// }
// //end for i
//
// /* Since we start at the upper leftmost corner -- i.e. the location (0,0) -- we'll first get
// * the locations of all the rooms with chest type 1 in it (remember, these chest types don't need keys)
// * and set them as the initial "neighbors".
// *
// * We call the below method with parameter 0 (although technically there is no chestType with value 0)
// * because doing so will give us an array of all the cells that have chestType 1. */
//
// Cell[] initialNeighbors = this.getNeighboringCells(0);
//
// /* Now put these in a prioritylist. Since the Cell objects implement the Comparable interface,
// * they will be "sorted" from smallest to largest in the priorityqueue. */
// PriorityQueue<Cell> pq = new PriorityQueue<>(Arrays.asList(initialNeighbors));
//
// /* Testing priorityquee */
//// while (!pq.isEmpty()) {
//// System.out.println(pq.remove());
//// }
//
// Cell currRoom = null;
//
// /* Begin A* algorithm */
// HashSet<Cell> openList = new HashSet<>(pq);
// HashSet<Cell> closedList = new HashSet<>();
// while (currRoom != this.destinationCell && !pq.isEmpty()) {
// currRoom = pq.remove();
// currRoom.visited = true;
// openList.remove(currRoom);
// closedList.add(currRoom);
// Cell[] neighbors = neighboringCells.get(currRoom.type);
// for (Cell neighbor: neighbors) {
// if (!neighbor.visited && neighbor.distSoFar > currRoom.distSoFar + this.getDist(currRoom, neighbor)) {
// neighbor.distSoFar = currRoom.distSoFar + this.getDist(currRoom, neighbor);
// pq.remove(neighbor);
// pq.add(neighbor);
// openList.add(neighbor);
// }
// }
// //end for
// }
// //end while
//
// if (currRoom == this.destinationCell) {
// return currRoom.distSoFar + currRoom.estDistRemaining;
// }
// return -1;
// }
public static void main(String[] args) {
new VanyaAndTreasure();
// System.out.println(vt.minTotalDistToGetTreasure());
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | bed3dcf2c49f1ba5279587323d1100e5 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/** Class: VanyaAndTreasure.java
* @author
* @version 1.0 <p>
* Course:
* Written / Updated: Jun 12, 2016
*
* This Class - See VanyaAndTreasure.pdf for instructions.
* VERDICT: (most likely correct but not fast enough)
* Consider a modified dynamic programming or BFS, or in the alternative
* try a tighter heuristic for A*?
*
* UPDATE: Tried a tighter heuristic for A*...
*/
public class VanyaAndTreasure {
/**
* This class describes the room at a certain (x,y) location in the grid.
* @author PP
*
*/
private class Cell implements Comparable<Cell>{
private int type; //the chest type (from 1 to p inclusive) that this cell contains.
private int row, col; //row / col index of this room cell.
// private int distSoFar; //Distance that Vanya has traveled thus far to get to this cell
// private int estDistRemaining; //Est. distance remaining from this cell to the cell containing the final chest (manhattan distance heuristic)
// private boolean visited; //Whether a chest in this cell has been visited and unlocked
// private Cell farthestParent;
// private Cell farthestNeighbor;
private int pos1D;
private int distance;
// private final int INFINITY = 999999999;
Cell(int type,int row, int col) {
this.type = type;
this.row = row;
this.col = col;
this.pos1D = m * row + col;
this.distance = Integer.MAX_VALUE;
// this.visited = false;
// this.distSoFar = INFINITY;
// this.estDistRemaining = -1;
// this.farthestParent = null;
// this.farthestNeighbor = null;
}
// private int computeEstDist() {
// if (this.estDistRemaining != -1)
// return this.estDistRemaining;
//
// this.estDistRemaining = VanyaAndTreasure.this.allPairsLongestPath[this.type][VanyaAndTreasure.this.destinationCell.type][this.pos1D];
// return this.estDistRemaining;
// if (this == VanyaAndTreasure.this.destinationCell) {
// this.estDistRemaining = 0;
// return this.estDistRemaining;
// }
//
// Cell currCell = VanyaAndTreasure.this.destinationCell;
// int tmpEstDist = 0;
// while (this.type != currCell.type - 1) {
// Cell farthestParent = currCell.getFarthestParent();
// tmpEstDist += getDist(farthestParent, currCell);
// currCell = farthestParent;
// }
// tmpEstDist += getDist(this, currCell);
//
// this.estDistRemaining = tmpEstDist;
// return this.estDistRemaining;
// }
// private Cell getFarthestParent() {
// if (this.farthestParent != null)
// return this.farthestParent;
//
//// Cell[] parents = VanyaAndTreasure.this.neighboringCells.get(this.type - 2);
//// if (parents == null) { //if no neighbors have been initialized yet...
//// parents = getNeighboringCells(this.type - 2); //invoke custom method
//// }
// LinkedList<Integer> parents = VanyaAndTreasure.this.chestTypeToRoomLocationsMap.get(this.type - 1);
//
// int maxDist = -1;
// int farthestParentLoc1D = -1;
// for (int parentLoc1D: parents) {
// int rowParent = parentLoc1D / m;
// int colParent = parentLoc1D % m;
// int dist = Math.abs(this.row - rowParent) + Math.abs(this.col - colParent);
// if (dist > maxDist) {
// maxDist = dist;
// farthestParentLoc1D = parentLoc1D;
// }
// }
//
//
// this.farthestParent = roomArr[farthestParentLoc1D / m][farthestParentLoc1D % m];
// return farthestParent;
// }
// private Cell getFarthestNeighbor() {
// Cell[] neighbors = VanyaAndTreasure.this.neighboringCells.get(this.type);
// if (neighbors == null) { //if no neighbors have been initialized yet...
// neighbors = getNeighboringCells(this.type); //invoke custom method
// neighboringCells.put(this.type, neighbors); //and save it to the hashmap so we don't do same computation twice
// }
// int maxDist = -1;
// Cell farthestNeighbor = null;
// for (Cell neighbor: neighbors) {
// int dist = getDist(neighbor, this);
// if (dist > maxDist) {
// maxDist = dist;
// farthestNeighbor = neighbor;
// }
// }
// return farthestNeighbor;
// }
@Override
public String toString() {
return String.format("(%s, %s) dist: %s", row, col, distance);
}
@Override
public int compareTo(Cell c) {
// TODO Auto-generated method stub
return this.distance - c.distance;
}
// @Override
// public int compareTo(Cell c2) {
// /* The Math.min() is to prevent the total est. distance from going over the INFINITY constant. */
// return Math.min(this.distSoFar + this.estDistRemaining, INFINITY) - Math.min(c2.distSoFar + c2.estDistRemaining, INFINITY);
//// return (this.distSoFar + this.estDistRemaining) - (c2.distSoFar + c2.estDistRemaining);
// }
}
//end private class Cell
private class Crawler implements Comparable<Crawler> {
private int row, col, distance;
Crawler(int row, int col) {
this.row = row;
this.col = col;
distance = Integer.MAX_VALUE;
}
@Override
public int compareTo(Crawler c) {
return this.distance - c.distance;
}
}
/*** BEGIN class VanyaAndTreasure ***/
/* the number of rows and columns in the table representing the palace and
* the number of different types of the chests, respectively, where
* (1 <= n, m <= 300, and 1 <= p <= n*m) */
private int n, m, p;
private Cell[][] roomArr;
// private int[][] allPairsLongestPath;
private int[][] shortestDist;
/* Will map each chest type (from 1 to p, inclusive) to a list of ALL rooms
* in which that chest is located.
* NOTE: the rooms will be saved in the form of a single integer that represents
* the row and column values.
*
* EXAMPLE: if a chest type 2 is located in rooms (2,3) and (1,0), and
* the rooms are in a 4x4 grid, then the hashmap will save the following:
* 2: [11, 4]
*
* where (2,3) is represented as 2*4+3 = 11, and
* (1,0) is represented as 1*4+0 = 4.
* */
HashMap<Integer, LinkedList<Integer>> chestTypeToRoomLocationsMap;
/* Keeps track of ALL neighbors for a particular chest type.
* For example, chest type 1 will be mapped to an array of neighboring cells which have chest type 2. */
// HashMap<Integer, Cell[]> neighboringCells;
// HashMap<Integer, Cell[]> neighboringCellsAscending;
Cell[][] neighboringCellsAscending;
/* The goal destination Cell, which has chest type p (where p is the last integer in a given input problem). */
Cell destinationCell;
/**
* constructor.
*/
public VanyaAndTreasure() {
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
//Read the first line
String line = rd.readLine();
StringTokenizer tokenizer = new StringTokenizer(line);
this.n = Integer.parseInt(tokenizer.nextToken());
this.m = Integer.parseInt(tokenizer.nextToken());
this.p = Integer.parseInt(tokenizer.nextToken());
/* Read what this hashmap is all about near the top of this file */
this.chestTypeToRoomLocationsMap = new HashMap<>();
this.roomArr = new Cell[n][m];
/* Read the next n lines. Each line will have m entries. Use these values to
* create a 2-D array roomArr. */
for (int i = 0; i < n; i++) {
line = rd.readLine();
tokenizer = new StringTokenizer(line);
for (int j = 0; j < m; j++) {
int chestType = Integer.parseInt(tokenizer.nextToken());
this.roomArr[i][j] = new Cell(chestType, i, j); //create new room
//Add this room to the hashmap
LinkedList<Integer> tempList = chestTypeToRoomLocationsMap.get(chestType);
/* if hashmap hasn't yet created the linkedlist associated with this chestType,
* initialize a new linked list, then add the current room to the linkedlist */
if (tempList == null) {
tempList = new LinkedList<>();
chestTypeToRoomLocationsMap.put(chestType, tempList);
}
tempList.add(i * m + j); //Add this room to the linkedlist associated with the hashmap
/* If the value we read pertains to the final chest type p, then we know
* that this is the ultimate destination, and that there is only ONE chest
* of this type. So let's save this cell for future reference. */
if (chestType == this.p) {
this.destinationCell = this.roomArr[i][j];
}
/* If this room contains chest type 1, then we'll initialize the distance between location (0,0)
* and this room's location (since Vanya always starts out at (0,0) and must first find rooms
* with chest type 1, might as well initialize these distances now) */
// if (chestType == 1) {
// this.roomArr[i][j].distSoFar = (this.roomArr[i][j].row - 0) + (this.roomArr[i][j].col - 0);
// }
}
}
//end for i
// this.allPairsLongestPath = new int[n*m + 1][n*m + 1];
this.shortestDist = new int[n][m];
for (int i = 0; i < shortestDist.length; i++) {
Arrays.fill(shortestDist[i], Integer.MAX_VALUE);
}
// for (int[] paths: allPairsLongestPath) Arrays.fill(paths, -1);
// this.neighboringCells = new HashMap<>();
this.neighboringCellsAscending = new Cell[p][];
// System.out.println(shortestDist(this.destinationCell));
System.out.println(shortestDistIterative());
//
// int gap = 1;
// while (gap <= p - 1) {
//
// for (int i = 1; i <= this.p; i++) {
// LinkedList<Integer> cellsA = chestTypeToRoomLocationsMap.get(i);
//
// int j = i + gap;
// if (j > this.p)
// break;
// LinkedList<Integer> cellsB = chestTypeToRoomLocationsMap.get(j);
//
// int maxDist = -1;
// for (int k: cellsA) {
// int rowA = k / m;
// int colA = k % m;
// for (int l : cellsB) {
// int rowB = l / m;
// int colB = l % m;
// if (gap == 1) {
// this.allPairsLongestPath[i][j][k] = getDist(roomArr[rowA][rowB], roomArr[rowB][colB]);
// continue;
// }
// Cell farthestParentOfB = this.roomArr[rowB][colB].getFarthestParent();
// int rowParent = farthestParentOfB.row;
// int colParent = farthestParentOfB.col;
//
// int currDist = this.allPairsLongestPath[i][j-1][k] + getDist(this.roomArr[rowParent][colParent], this.roomArr[rowB][colB]);
// if (maxDist < currDist) {
// maxDist = currDist;
// this.allPairsLongestPath[i][j][k] = maxDist;
// }
// }
// }
// }
// gap++;
// }
rd.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private int shortestDistIterative() {
Cell[] cellsWithChestType1 = neighboringCellsAscending[0];
if (cellsWithChestType1 == null || cellsWithChestType1.length == 0) { //if no neighbors have been initialized yet...
cellsWithChestType1 = getNeighboringCells(0, true); //invoke custom method
neighboringCellsAscending[0] = cellsWithChestType1; //and save it to the hashmap so we don't do same computation twice
}
for (Cell cellWithChestType1 : cellsWithChestType1) {
// allPairsLongestPath[0][cellWithChestType1.pos1D] = cellWithChestType1.row + cellWithChestType1.col;
shortestDist[cellWithChestType1.row][cellWithChestType1.col] = cellWithChestType1.row + cellWithChestType1.col;
cellWithChestType1.distance = shortestDist[cellWithChestType1.row][cellWithChestType1.col];
}
for (int i = 1; i < p; ++i) {
Cell[] neighbors = neighboringCellsAscending[i];
if (neighbors == null) { //if no neighbors have been initialized yet...
neighbors = getNeighboringCells(i, true); //invoke custom method
neighboringCellsAscending[i] = neighbors; //and save it to the hashmap so we don't do same computation twice
}
Cell[] prevNeighbors = neighboringCellsAscending[i - 1];
if (prevNeighbors.length * neighbors.length >= this.n * this.m * 2) {
this.bfs2(prevNeighbors, neighbors);
continue;
}
for (Cell neighbor : neighbors) {
int shortestDistance = Integer.MAX_VALUE;
int currDist;
for (Cell prevNeighbor : prevNeighbors) {
currDist = shortestDist[prevNeighbor.row][prevNeighbor.col] + getDist(prevNeighbor, neighbor);
// currDist = prevNeighbor.distance + getDist(prevNeighbor, neighbor);
if (currDist < shortestDistance) {
shortestDistance = currDist;
}
}
shortestDist[neighbor.row][neighbor.col] = shortestDistance;
neighbor.distance = shortestDist[neighbor.row][neighbor.col];
}
//end for Cell neighbor: neighbors
}
//end for i
return shortestDist[this.destinationCell.row][this.destinationCell.col];
}
private void bfs2(Cell[] prevNeighbors, Cell[] neighbors) {
int[][] distance = new int[n][m];
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++)
distance[i][j] = Integer.MAX_VALUE - 1;
for (Cell p : prevNeighbors)
distance[p.row][p.col] = shortestDist[p.row][p.col];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) {
if (i+1 < n) distance[i + 1][j] = Math.min(distance[i + 1][j], distance[i][j] + 1);
if (j+1 < n) distance[i][j + 1] = Math.min(distance[i][j + 1], distance[i][j] + 1);
}
for (int i = n-1; i >= 0; i--) for (int j = m-1; j >= 0; j--) {
if (i-1 >= 0) distance[i - 1][j] = Math.min(distance[i - 1][j], distance[i][j] + 1);
if (j-1 >= 0) distance[i][j - 1] = Math.min(distance[i][j - 1], distance[i][j] + 1);
}
for (Cell cell : neighbors)
shortestDist[cell.row][cell.col] = distance[cell.row][cell.col];
}
private void bfs(Cell[] prevNeighbors, Cell[] neighbors) {
// Arrays.sort(prevNeighbors);
PriorityQueue<Cell> minPQ = new PriorityQueue<Cell>(Arrays.asList(prevNeighbors));
// int[][] tmpShortestDist = new int[n][m];
// for (int[] row : tmpShortestDist) {
// Arrays.fill(row, Integer.MAX_VALUE);
// }
boolean[][] visited = new boolean[n][m];
for (int i = 0; i < this.n; i++) {
for (int j = 0; j < this.m; j++) {
if (this.roomArr[i][j].type == prevNeighbors[0].type) {
this.roomArr[i][j].distance = this.shortestDist[i][j];
visited[i][j] = true;
}
else {
this.roomArr[i][j].distance = Integer.MAX_VALUE;
}
}
}
// for (Cell prev : prevNeighbors) {
// tmpShortestDist[prev.row][prev.col] = this.shortestDist[prev.row][prev.col];
// }
// int currDistance = this.shortestDist[prevNeighbors[0].row][prevNeighbors[0].col];
int numOfCurrNeighborsVisited = 0;
// ArrayList<Cell> visited = new ArrayList<>(minPQ);
while (numOfCurrNeighborsVisited < neighbors.length) {
Cell currCell = minPQ.remove();
ArrayList<Cell> bfsNeighbors = getBFSNeighbors(currCell, visited);
for (Cell bfsNeighbor: bfsNeighbors) {
// if (visited.contains(bfsNeighbor))
// continue;
if (bfsNeighbor.distance > currCell.distance + 1) {
bfsNeighbor.distance = currCell.distance + 1;
// minPQ.remove(bfsNeighbor);
minPQ.add(bfsNeighbor);
visited[bfsNeighbor.row][bfsNeighbor.col] = true;
if (bfsNeighbor.type == neighbors[0].type) {
numOfCurrNeighborsVisited++;
}
}
}
//end for Cell
}
//end while
for (Cell neighbor : neighbors) {
this.shortestDist[neighbor.row][neighbor.col] = neighbor.distance;
}
}
//end private void bfs
private ArrayList<Cell> getBFSNeighbors(Cell currCell, boolean[][] visited) {
int row = currCell.row;
int col = currCell.col;
int maxPossibleNeighbors = 4;
// if (row - 1 < 0) maxPossibleNeighbors--;
// if (row + 1 >= this.n) maxPossibleNeighbors--;
// if (col - 1 < 0) maxPossibleNeighbors--;
// if (col + 1 >= this.m) maxPossibleNeighbors--;
ArrayList<Cell> bfsNeighbors = new ArrayList<>();
int[] rowOffset = {0, 0, 1,-1};
int[] colOffset = {1,-1, 0, 0};
for (int i = 0; i < maxPossibleNeighbors; i++) {
int neighborRow = row + rowOffset[i];
int neighborCol = col + colOffset[i];
if (neighborRow < 0 || neighborCol < 0 ||
neighborRow >= this.n || neighborCol >= this.m ||
visited[neighborRow][neighborCol] == true) {
continue;
}
Cell bfsNeighbor = this.roomArr[neighborRow][neighborCol];
bfsNeighbors.add(bfsNeighbor);
}
return bfsNeighbors;
}
// private int shortestDist(Cell cell) {
// if (cell.type < 1) throw new RuntimeException();
// if (allPairsLongestPath[0][cell.pos1D] != -1) {
// return allPairsLongestPath[0][cell.pos1D];
// }
// if (cell.type == 1) {
// allPairsLongestPath[0][cell.pos1D] = cell.row + cell.col;
// return allPairsLongestPath[0][cell.pos1D];
// }
//
//
// Cell[] neighbors = neighboringCells.get(cell.type); //get the neighbors from the hashmap above
// if (neighbors == null) { //if no neighbors have been initialized yet...
// neighbors = getNeighboringCells(cell.type, false); //invoke custom method
// neighboringCells.put(cell.type, neighbors); //and save it to the hashmap so we don't do same computation twice
// }
//
// int shortestDist = Integer.MAX_VALUE;
// for (Cell neighbor : neighbors) {
// int currDistToThisCell = getDist(cell, neighbor) + shortestDist(neighbor);
// if (currDistToThisCell < shortestDist) {
// shortestDist = currDistToThisCell;
// }
// }
//
// allPairsLongestPath[0][cell.pos1D] = shortestDist;
// return allPairsLongestPath[0][cell.pos1D];
// }
/**
* Method: getNeighboringCells
* @param chestType
* @return
*/
private Cell[] getNeighboringCells(int chestType, boolean ascending) {
/* All chests of type x - 1 can open chests of type x, so neighboring rooms of type x
* contain chests of chestType x - 1. */
LinkedList<Integer> neighborRooms = this.chestTypeToRoomLocationsMap.get(ascending? chestType + 1 : chestType - 1);
if (neighborRooms == null) {
return new Cell[0];
}
Cell[] neighbors = new Cell[neighborRooms.size()];
ListIterator<Integer> iter = neighborRooms.listIterator();
for (int i = 0; i < neighbors.length; i++) {
int thisRoom = iter.next();
int thisRow = thisRoom / this.m;
int thisCol = thisRoom % this.m;
neighbors[i] = this.roomArr[thisRow][thisCol];
}
return neighbors;
}
private int getDist(Cell c1, Cell c2) {
return Math.abs(c1.row - c2.row) + Math.abs(c1.col - c2.col);
}
/**
* Method: minTotalDistToGetTreasure
* @return the minimum possible total distance Vanya has to walk
* in order to get the treasure from the chest of type this.p.
*/
// private int minTotalDistToGetTreasure() {
//
// /* This will save all neighboring cells for a given chest type for easy reference and efficiency. */
//// this.neighboringCells = new HashMap<>();
////
//// /* Might be worth it to try something like A* for this one...
//// * First set the neighbors of each chest type in all the rooms */
//// for (int i = 0; i < this.roomArr.length; i++) {
//// for (int j = 0; j < this.roomArr[i].length; j++) {
//// Cell thisCell = this.roomArr[i][j];
//// int chestType = thisCell.type;
////
//// //Set all the neighbors
//// Cell[] neighbors = neighboringCells.get(chestType); //get the neighbors from the hashmap above
//// if (neighbors == null) { //if no neighbors have been initialized yet...
//// neighbors = getNeighboringCells(chestType); //invoke custom method
//// neighboringCells.put(chestType, neighbors); //and save it to the hashmap so we don't do same computation twice
//// }
////// thisCell.neighborArr = neighbors; //set the neighbors for this cell
////
//// /* Set the estimated manhattan distance from this cell to destination cell,
//// * provided that the manhattan distance cannot be shorter than the difference
//// * between destination chest type and this chest type.
//// *
//// * For example, if this cell type == 2 and destination cell type == 5,
//// * it will take at least 3 unlocking steps to get to the destination chest.
//// * So, if the manhattan distance between this cell and destination cell is only 2,
//// * we still have to set the est. distance at 3. */
////// thisCell.estDistRemaining = Math.max(
////// this.destinationCell.type - thisCell.type,
////// Math.abs(this.destinationCell.row - thisCell.row) + Math.abs(this.destinationCell.col - thisCell.col));
//// thisCell.computeEstDist();
////
//// }
//// //end for j
//// }
// //end for i
//
// /* Since we start at the upper leftmost corner -- i.e. the location (0,0) -- we'll first get
// * the locations of all the rooms with chest type 1 in it (remember, these chest types don't need keys)
// * and set them as the initial "neighbors".
// *
// * We call the below method with parameter 0 (although technically there is no chestType with value 0)
// * because doing so will give us an array of all the cells that have chestType 1. */
//
// Cell[] initialNeighbors = this.getNeighboringCells(0);
//
// /* Now put these in a prioritylist. Since the Cell objects implement the Comparable interface,
// * they will be "sorted" from smallest to largest in the priorityqueue. */
// PriorityQueue<Cell> pq = new PriorityQueue<>(Arrays.asList(initialNeighbors));
//
// /* Testing priorityquee */
//// while (!pq.isEmpty()) {
//// System.out.println(pq.remove());
//// }
//
// Cell currRoom = null;
//
// /* Begin A* algorithm */
// HashSet<Cell> openList = new HashSet<>(pq);
// HashSet<Cell> closedList = new HashSet<>();
// while (currRoom != this.destinationCell && !pq.isEmpty()) {
// currRoom = pq.remove();
// currRoom.visited = true;
// openList.remove(currRoom);
// closedList.add(currRoom);
// Cell[] neighbors = neighboringCells.get(currRoom.type);
// for (Cell neighbor: neighbors) {
// if (!neighbor.visited && neighbor.distSoFar > currRoom.distSoFar + this.getDist(currRoom, neighbor)) {
// neighbor.distSoFar = currRoom.distSoFar + this.getDist(currRoom, neighbor);
// pq.remove(neighbor);
// pq.add(neighbor);
// openList.add(neighbor);
// }
// }
// //end for
// }
// //end while
//
// if (currRoom == this.destinationCell) {
// return currRoom.distSoFar + currRoom.estDistRemaining;
// }
// return -1;
// }
public static void main(String[] args) {
new VanyaAndTreasure();
// System.out.println(vt.minTotalDistToGetTreasure());
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | 24fa91545a79d2c4bdef6bd88a51326c | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/** Class: VanyaAndTreasure.java
* @author
* @version 1.0 <p>
* Course:
* Written / Updated: Jun 12, 2016
*
* This Class - See VanyaAndTreasure.pdf for instructions.
* VERDICT: (most likely correct but not fast enough)
* Consider a modified dynamic programming or BFS, or in the alternative
* try a tighter heuristic for A*?
*
* UPDATE: Tried a tighter heuristic for A*...
*/
public class VanyaAndTreasure {
/**
* This class describes the room at a certain (x,y) location in the grid.
* @author PP
*
*/
private class Cell implements Comparable<Cell>{
private int type; //the chest type (from 1 to p inclusive) that this cell contains.
private int row, col; //row / col index of this room cell.
// private int distSoFar; //Distance that Vanya has traveled thus far to get to this cell
// private int estDistRemaining; //Est. distance remaining from this cell to the cell containing the final chest (manhattan distance heuristic)
// private boolean visited; //Whether a chest in this cell has been visited and unlocked
// private Cell farthestParent;
// private Cell farthestNeighbor;
private int pos1D;
private int distance;
// private final int INFINITY = 999999999;
Cell(int type,int row, int col) {
this.type = type;
this.row = row;
this.col = col;
this.pos1D = m * row + col;
this.distance = Integer.MAX_VALUE;
// this.visited = false;
// this.distSoFar = INFINITY;
// this.estDistRemaining = -1;
// this.farthestParent = null;
// this.farthestNeighbor = null;
}
// private int computeEstDist() {
// if (this.estDistRemaining != -1)
// return this.estDistRemaining;
//
// this.estDistRemaining = VanyaAndTreasure.this.allPairsLongestPath[this.type][VanyaAndTreasure.this.destinationCell.type][this.pos1D];
// return this.estDistRemaining;
// if (this == VanyaAndTreasure.this.destinationCell) {
// this.estDistRemaining = 0;
// return this.estDistRemaining;
// }
//
// Cell currCell = VanyaAndTreasure.this.destinationCell;
// int tmpEstDist = 0;
// while (this.type != currCell.type - 1) {
// Cell farthestParent = currCell.getFarthestParent();
// tmpEstDist += getDist(farthestParent, currCell);
// currCell = farthestParent;
// }
// tmpEstDist += getDist(this, currCell);
//
// this.estDistRemaining = tmpEstDist;
// return this.estDistRemaining;
// }
// private Cell getFarthestParent() {
// if (this.farthestParent != null)
// return this.farthestParent;
//
//// Cell[] parents = VanyaAndTreasure.this.neighboringCells.get(this.type - 2);
//// if (parents == null) { //if no neighbors have been initialized yet...
//// parents = getNeighboringCells(this.type - 2); //invoke custom method
//// }
// LinkedList<Integer> parents = VanyaAndTreasure.this.chestTypeToRoomLocationsMap.get(this.type - 1);
//
// int maxDist = -1;
// int farthestParentLoc1D = -1;
// for (int parentLoc1D: parents) {
// int rowParent = parentLoc1D / m;
// int colParent = parentLoc1D % m;
// int dist = Math.abs(this.row - rowParent) + Math.abs(this.col - colParent);
// if (dist > maxDist) {
// maxDist = dist;
// farthestParentLoc1D = parentLoc1D;
// }
// }
//
//
// this.farthestParent = roomArr[farthestParentLoc1D / m][farthestParentLoc1D % m];
// return farthestParent;
// }
// private Cell getFarthestNeighbor() {
// Cell[] neighbors = VanyaAndTreasure.this.neighboringCells.get(this.type);
// if (neighbors == null) { //if no neighbors have been initialized yet...
// neighbors = getNeighboringCells(this.type); //invoke custom method
// neighboringCells.put(this.type, neighbors); //and save it to the hashmap so we don't do same computation twice
// }
// int maxDist = -1;
// Cell farthestNeighbor = null;
// for (Cell neighbor: neighbors) {
// int dist = getDist(neighbor, this);
// if (dist > maxDist) {
// maxDist = dist;
// farthestNeighbor = neighbor;
// }
// }
// return farthestNeighbor;
// }
@Override
public String toString() {
return String.format("(%s, %s) dist: %s", row, col, distance);
}
@Override
public int compareTo(Cell c) {
// TODO Auto-generated method stub
return this.distance - c.distance;
}
// @Override
// public int compareTo(Cell c2) {
// /* The Math.min() is to prevent the total est. distance from going over the INFINITY constant. */
// return Math.min(this.distSoFar + this.estDistRemaining, INFINITY) - Math.min(c2.distSoFar + c2.estDistRemaining, INFINITY);
//// return (this.distSoFar + this.estDistRemaining) - (c2.distSoFar + c2.estDistRemaining);
// }
}
//end private class Cell
private class Crawler implements Comparable<Crawler> {
private int row, col, distance;
Crawler(int row, int col) {
this.row = row;
this.col = col;
distance = Integer.MAX_VALUE;
}
@Override
public int compareTo(Crawler c) {
return this.distance - c.distance;
}
}
/*** BEGIN class VanyaAndTreasure ***/
/* the number of rows and columns in the table representing the palace and
* the number of different types of the chests, respectively, where
* (1 <= n, m <= 300, and 1 <= p <= n*m) */
private int n, m, p;
private Cell[][] roomArr;
// private int[][] allPairsLongestPath;
private int[][] shortestDist;
/* Will map each chest type (from 1 to p, inclusive) to a list of ALL rooms
* in which that chest is located.
* NOTE: the rooms will be saved in the form of a single integer that represents
* the row and column values.
*
* EXAMPLE: if a chest type 2 is located in rooms (2,3) and (1,0), and
* the rooms are in a 4x4 grid, then the hashmap will save the following:
* 2: [11, 4]
*
* where (2,3) is represented as 2*4+3 = 11, and
* (1,0) is represented as 1*4+0 = 4.
* */
HashMap<Integer, LinkedList<Integer>> chestTypeToRoomLocationsMap;
/* Keeps track of ALL neighbors for a particular chest type.
* For example, chest type 1 will be mapped to an array of neighboring cells which have chest type 2. */
// HashMap<Integer, Cell[]> neighboringCells;
// HashMap<Integer, Cell[]> neighboringCellsAscending;
Cell[][] neighboringCellsAscending;
/* The goal destination Cell, which has chest type p (where p is the last integer in a given input problem). */
Cell destinationCell;
/**
* constructor.
*/
public VanyaAndTreasure() {
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
//Read the first line
String line = rd.readLine();
StringTokenizer tokenizer = new StringTokenizer(line);
this.n = Integer.parseInt(tokenizer.nextToken());
this.m = Integer.parseInt(tokenizer.nextToken());
this.p = Integer.parseInt(tokenizer.nextToken());
/* Read what this hashmap is all about near the top of this file */
this.chestTypeToRoomLocationsMap = new HashMap<>();
this.roomArr = new Cell[n][m];
/* Read the next n lines. Each line will have m entries. Use these values to
* create a 2-D array roomArr. */
for (int i = 0; i < n; i++) {
line = rd.readLine();
tokenizer = new StringTokenizer(line);
for (int j = 0; j < m; j++) {
int chestType = Integer.parseInt(tokenizer.nextToken());
this.roomArr[i][j] = new Cell(chestType, i, j); //create new room
//Add this room to the hashmap
LinkedList<Integer> tempList = chestTypeToRoomLocationsMap.get(chestType);
/* if hashmap hasn't yet created the linkedlist associated with this chestType,
* initialize a new linked list, then add the current room to the linkedlist */
if (tempList == null) {
tempList = new LinkedList<>();
chestTypeToRoomLocationsMap.put(chestType, tempList);
}
tempList.add(i * m + j); //Add this room to the linkedlist associated with the hashmap
/* If the value we read pertains to the final chest type p, then we know
* that this is the ultimate destination, and that there is only ONE chest
* of this type. So let's save this cell for future reference. */
if (chestType == this.p) {
this.destinationCell = this.roomArr[i][j];
}
/* If this room contains chest type 1, then we'll initialize the distance between location (0,0)
* and this room's location (since Vanya always starts out at (0,0) and must first find rooms
* with chest type 1, might as well initialize these distances now) */
// if (chestType == 1) {
// this.roomArr[i][j].distSoFar = (this.roomArr[i][j].row - 0) + (this.roomArr[i][j].col - 0);
// }
}
}
//end for i
// this.allPairsLongestPath = new int[n*m + 1][n*m + 1];
this.shortestDist = new int[n][m];
for (int i = 0; i < shortestDist.length; i++) {
Arrays.fill(shortestDist[i], Integer.MAX_VALUE);
}
// for (int[] paths: allPairsLongestPath) Arrays.fill(paths, -1);
// this.neighboringCells = new HashMap<>();
this.neighboringCellsAscending = new Cell[p][];
// System.out.println(shortestDist(this.destinationCell));
System.out.println(shortestDistIterative());
//
// int gap = 1;
// while (gap <= p - 1) {
//
// for (int i = 1; i <= this.p; i++) {
// LinkedList<Integer> cellsA = chestTypeToRoomLocationsMap.get(i);
//
// int j = i + gap;
// if (j > this.p)
// break;
// LinkedList<Integer> cellsB = chestTypeToRoomLocationsMap.get(j);
//
// int maxDist = -1;
// for (int k: cellsA) {
// int rowA = k / m;
// int colA = k % m;
// for (int l : cellsB) {
// int rowB = l / m;
// int colB = l % m;
// if (gap == 1) {
// this.allPairsLongestPath[i][j][k] = getDist(roomArr[rowA][rowB], roomArr[rowB][colB]);
// continue;
// }
// Cell farthestParentOfB = this.roomArr[rowB][colB].getFarthestParent();
// int rowParent = farthestParentOfB.row;
// int colParent = farthestParentOfB.col;
//
// int currDist = this.allPairsLongestPath[i][j-1][k] + getDist(this.roomArr[rowParent][colParent], this.roomArr[rowB][colB]);
// if (maxDist < currDist) {
// maxDist = currDist;
// this.allPairsLongestPath[i][j][k] = maxDist;
// }
// }
// }
// }
// gap++;
// }
rd.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private int shortestDistIterative() {
Cell[] cellsWithChestType1 = neighboringCellsAscending[0];
if (cellsWithChestType1 == null || cellsWithChestType1.length == 0) { //if no neighbors have been initialized yet...
cellsWithChestType1 = getNeighboringCells(0, true); //invoke custom method
neighboringCellsAscending[0] = cellsWithChestType1; //and save it to the hashmap so we don't do same computation twice
}
for (Cell cellWithChestType1 : cellsWithChestType1) {
// allPairsLongestPath[0][cellWithChestType1.pos1D] = cellWithChestType1.row + cellWithChestType1.col;
shortestDist[cellWithChestType1.row][cellWithChestType1.col] = cellWithChestType1.row + cellWithChestType1.col;
cellWithChestType1.distance = shortestDist[cellWithChestType1.row][cellWithChestType1.col];
}
for (int i = 1; i < p; ++i) {
Cell[] neighbors = neighboringCellsAscending[i];
if (neighbors == null) { //if no neighbors have been initialized yet...
neighbors = getNeighboringCells(i, true); //invoke custom method
neighboringCellsAscending[i] = neighbors; //and save it to the hashmap so we don't do same computation twice
}
Cell[] prevNeighbors = neighboringCellsAscending[i - 1];
if (prevNeighbors.length * neighbors.length >= this.n * this.m) {
this.bfs2(prevNeighbors, neighbors);
continue;
}
for (Cell neighbor : neighbors) {
int shortestDistance = Integer.MAX_VALUE;
int currDist;
for (Cell prevNeighbor : prevNeighbors) {
currDist = shortestDist[prevNeighbor.row][prevNeighbor.col] + getDist(prevNeighbor, neighbor);
// currDist = prevNeighbor.distance + getDist(prevNeighbor, neighbor);
if (currDist < shortestDistance) {
shortestDistance = currDist;
}
}
shortestDist[neighbor.row][neighbor.col] = shortestDistance;
neighbor.distance = shortestDist[neighbor.row][neighbor.col];
}
//end for Cell neighbor: neighbors
}
//end for i
return shortestDist[this.destinationCell.row][this.destinationCell.col];
}
private void bfs2(Cell[] prevNeighbors, Cell[] neighbors) {
int[][] distance = new int[n][m];
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++)
distance[i][j] = Integer.MAX_VALUE - 1;
for (Cell p : prevNeighbors)
distance[p.row][p.col] = shortestDist[p.row][p.col];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) {
if (i+1 < n) distance[i + 1][j] = Math.min(distance[i + 1][j], distance[i][j] + 1);
if (j+1 < n) distance[i][j + 1] = Math.min(distance[i][j + 1], distance[i][j] + 1);
}
for (int i = n-1; i >= 0; i--) for (int j = m-1; j >= 0; j--) {
if (i-1 >= 0) distance[i - 1][j] = Math.min(distance[i - 1][j], distance[i][j] + 1);
if (j-1 >= 0) distance[i][j - 1] = Math.min(distance[i][j - 1], distance[i][j] + 1);
}
for (Cell cell : neighbors)
shortestDist[cell.row][cell.col] = distance[cell.row][cell.col];
}
private void bfs(Cell[] prevNeighbors, Cell[] neighbors) {
// Arrays.sort(prevNeighbors);
PriorityQueue<Cell> minPQ = new PriorityQueue<Cell>(Arrays.asList(prevNeighbors));
// int[][] tmpShortestDist = new int[n][m];
// for (int[] row : tmpShortestDist) {
// Arrays.fill(row, Integer.MAX_VALUE);
// }
boolean[][] visited = new boolean[n][m];
for (int i = 0; i < this.n; i++) {
for (int j = 0; j < this.m; j++) {
if (this.roomArr[i][j].type == prevNeighbors[0].type) {
this.roomArr[i][j].distance = this.shortestDist[i][j];
visited[i][j] = true;
}
else {
this.roomArr[i][j].distance = Integer.MAX_VALUE;
}
}
}
// for (Cell prev : prevNeighbors) {
// tmpShortestDist[prev.row][prev.col] = this.shortestDist[prev.row][prev.col];
// }
// int currDistance = this.shortestDist[prevNeighbors[0].row][prevNeighbors[0].col];
int numOfCurrNeighborsVisited = 0;
// ArrayList<Cell> visited = new ArrayList<>(minPQ);
while (numOfCurrNeighborsVisited < neighbors.length) {
Cell currCell = minPQ.remove();
ArrayList<Cell> bfsNeighbors = getBFSNeighbors(currCell, visited);
for (Cell bfsNeighbor: bfsNeighbors) {
// if (visited.contains(bfsNeighbor))
// continue;
if (bfsNeighbor.distance > currCell.distance + 1) {
bfsNeighbor.distance = currCell.distance + 1;
// minPQ.remove(bfsNeighbor);
minPQ.add(bfsNeighbor);
visited[bfsNeighbor.row][bfsNeighbor.col] = true;
if (bfsNeighbor.type == neighbors[0].type) {
numOfCurrNeighborsVisited++;
}
}
}
//end for Cell
}
//end while
for (Cell neighbor : neighbors) {
this.shortestDist[neighbor.row][neighbor.col] = neighbor.distance;
}
}
//end private void bfs
private ArrayList<Cell> getBFSNeighbors(Cell currCell, boolean[][] visited) {
int row = currCell.row;
int col = currCell.col;
int maxPossibleNeighbors = 4;
// if (row - 1 < 0) maxPossibleNeighbors--;
// if (row + 1 >= this.n) maxPossibleNeighbors--;
// if (col - 1 < 0) maxPossibleNeighbors--;
// if (col + 1 >= this.m) maxPossibleNeighbors--;
ArrayList<Cell> bfsNeighbors = new ArrayList<>();
int[] rowOffset = {0, 0, 1,-1};
int[] colOffset = {1,-1, 0, 0};
for (int i = 0; i < maxPossibleNeighbors; i++) {
int neighborRow = row + rowOffset[i];
int neighborCol = col + colOffset[i];
if (neighborRow < 0 || neighborCol < 0 ||
neighborRow >= this.n || neighborCol >= this.m ||
visited[neighborRow][neighborCol] == true) {
continue;
}
Cell bfsNeighbor = this.roomArr[neighborRow][neighborCol];
bfsNeighbors.add(bfsNeighbor);
}
return bfsNeighbors;
}
// private int shortestDist(Cell cell) {
// if (cell.type < 1) throw new RuntimeException();
// if (allPairsLongestPath[0][cell.pos1D] != -1) {
// return allPairsLongestPath[0][cell.pos1D];
// }
// if (cell.type == 1) {
// allPairsLongestPath[0][cell.pos1D] = cell.row + cell.col;
// return allPairsLongestPath[0][cell.pos1D];
// }
//
//
// Cell[] neighbors = neighboringCells.get(cell.type); //get the neighbors from the hashmap above
// if (neighbors == null) { //if no neighbors have been initialized yet...
// neighbors = getNeighboringCells(cell.type, false); //invoke custom method
// neighboringCells.put(cell.type, neighbors); //and save it to the hashmap so we don't do same computation twice
// }
//
// int shortestDist = Integer.MAX_VALUE;
// for (Cell neighbor : neighbors) {
// int currDistToThisCell = getDist(cell, neighbor) + shortestDist(neighbor);
// if (currDistToThisCell < shortestDist) {
// shortestDist = currDistToThisCell;
// }
// }
//
// allPairsLongestPath[0][cell.pos1D] = shortestDist;
// return allPairsLongestPath[0][cell.pos1D];
// }
/**
* Method: getNeighboringCells
* @param chestType
* @return
*/
private Cell[] getNeighboringCells(int chestType, boolean ascending) {
/* All chests of type x - 1 can open chests of type x, so neighboring rooms of type x
* contain chests of chestType x - 1. */
LinkedList<Integer> neighborRooms = this.chestTypeToRoomLocationsMap.get(ascending? chestType + 1 : chestType - 1);
if (neighborRooms == null) {
return new Cell[0];
}
Cell[] neighbors = new Cell[neighborRooms.size()];
ListIterator<Integer> iter = neighborRooms.listIterator();
for (int i = 0; i < neighbors.length; i++) {
int thisRoom = iter.next();
int thisRow = thisRoom / this.m;
int thisCol = thisRoom % this.m;
neighbors[i] = this.roomArr[thisRow][thisCol];
}
return neighbors;
}
private int getDist(Cell c1, Cell c2) {
return Math.abs(c1.row - c2.row) + Math.abs(c1.col - c2.col);
}
/**
* Method: minTotalDistToGetTreasure
* @return the minimum possible total distance Vanya has to walk
* in order to get the treasure from the chest of type this.p.
*/
// private int minTotalDistToGetTreasure() {
//
// /* This will save all neighboring cells for a given chest type for easy reference and efficiency. */
//// this.neighboringCells = new HashMap<>();
////
//// /* Might be worth it to try something like A* for this one...
//// * First set the neighbors of each chest type in all the rooms */
//// for (int i = 0; i < this.roomArr.length; i++) {
//// for (int j = 0; j < this.roomArr[i].length; j++) {
//// Cell thisCell = this.roomArr[i][j];
//// int chestType = thisCell.type;
////
//// //Set all the neighbors
//// Cell[] neighbors = neighboringCells.get(chestType); //get the neighbors from the hashmap above
//// if (neighbors == null) { //if no neighbors have been initialized yet...
//// neighbors = getNeighboringCells(chestType); //invoke custom method
//// neighboringCells.put(chestType, neighbors); //and save it to the hashmap so we don't do same computation twice
//// }
////// thisCell.neighborArr = neighbors; //set the neighbors for this cell
////
//// /* Set the estimated manhattan distance from this cell to destination cell,
//// * provided that the manhattan distance cannot be shorter than the difference
//// * between destination chest type and this chest type.
//// *
//// * For example, if this cell type == 2 and destination cell type == 5,
//// * it will take at least 3 unlocking steps to get to the destination chest.
//// * So, if the manhattan distance between this cell and destination cell is only 2,
//// * we still have to set the est. distance at 3. */
////// thisCell.estDistRemaining = Math.max(
////// this.destinationCell.type - thisCell.type,
////// Math.abs(this.destinationCell.row - thisCell.row) + Math.abs(this.destinationCell.col - thisCell.col));
//// thisCell.computeEstDist();
////
//// }
//// //end for j
//// }
// //end for i
//
// /* Since we start at the upper leftmost corner -- i.e. the location (0,0) -- we'll first get
// * the locations of all the rooms with chest type 1 in it (remember, these chest types don't need keys)
// * and set them as the initial "neighbors".
// *
// * We call the below method with parameter 0 (although technically there is no chestType with value 0)
// * because doing so will give us an array of all the cells that have chestType 1. */
//
// Cell[] initialNeighbors = this.getNeighboringCells(0);
//
// /* Now put these in a prioritylist. Since the Cell objects implement the Comparable interface,
// * they will be "sorted" from smallest to largest in the priorityqueue. */
// PriorityQueue<Cell> pq = new PriorityQueue<>(Arrays.asList(initialNeighbors));
//
// /* Testing priorityquee */
//// while (!pq.isEmpty()) {
//// System.out.println(pq.remove());
//// }
//
// Cell currRoom = null;
//
// /* Begin A* algorithm */
// HashSet<Cell> openList = new HashSet<>(pq);
// HashSet<Cell> closedList = new HashSet<>();
// while (currRoom != this.destinationCell && !pq.isEmpty()) {
// currRoom = pq.remove();
// currRoom.visited = true;
// openList.remove(currRoom);
// closedList.add(currRoom);
// Cell[] neighbors = neighboringCells.get(currRoom.type);
// for (Cell neighbor: neighbors) {
// if (!neighbor.visited && neighbor.distSoFar > currRoom.distSoFar + this.getDist(currRoom, neighbor)) {
// neighbor.distSoFar = currRoom.distSoFar + this.getDist(currRoom, neighbor);
// pq.remove(neighbor);
// pq.add(neighbor);
// openList.add(neighbor);
// }
// }
// //end for
// }
// //end while
//
// if (currRoom == this.destinationCell) {
// return currRoom.distSoFar + currRoom.estDistRemaining;
// }
// return -1;
// }
public static void main(String[] args) {
new VanyaAndTreasure();
// System.out.println(vt.minTotalDistToGetTreasure());
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | 7d0090999fb128775c06d43f81ff6c82 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.StringTokenizer;
/** Class: VanyaAndTreasure.java
* @author
* @version 1.0 <p>
* Course:
* Written / Updated: Jun 12, 2016
*
* This Class - See VanyaAndTreasure.pdf for instructions.
* VERDICT: (most likely correct but not fast enough)
* Consider a modified dynamic programming or BFS, or in the alternative
* try a tighter heuristic for A*?
*
* UPDATE: Tried a tighter heuristic for A*...not good. The time it takes to compute a tighter heuristic for A*
* might as well be used to compute all pairs shortest paths, which takes too long anyway.
*
* UPDATE 2: Dynamic programming takes too long where there are lots of rooms of chest type x and/or lots of rooms of chest type x+1.
* In this case, a sweep of all the rooms with a BFS / Dyn-programming combo is more efficient.
*
* UPDATED VERDICT: PASS
*/
public class VanyaAndTreasure {
/**
* This class describes the room at a certain (x,y) location in the grid.
* @author PP
*
*/
private class Cell {
// private int type; //the chest type (from 1 to p inclusive) that this cell contains.
private int row, col; //row / col index of this room cell.
// private int distance; //Used for the original bfs() method ONLY. Has no relation to the global shortestDist[][] array!
// private int pos1D;
Cell(int type,int row, int col) {
// this.type = type;
this.row = row;
this.col = col;
// this.pos1D = m * row + col;
// this.distance = Integer.MAX_VALUE;
}
/* For debugging only */
@Override
public String toString() {
// return String.format("(%s, %s) dist: %s", row, col, distance);
return String.format("(%s, %s)", row, col);
}
// @Override
// public int compareTo(Cell c) {
// return this.distance - c.distance;
// }
}
//end private class Cell
/*** BEGIN class VanyaAndTreasure ***/
/* the number of rows and columns in the table representing the palace and
* the number of different types of the chests, respectively, where
* (1 <= n, m <= 300, and 1 <= p <= n*m) */
private int n, m, p;
private Cell[][] roomArr; //Keeps track of Cell in every room at location (i,j)
private int[][] shortestDist; //Keeps track of shortest possible distance to room location at (i,j)
/* Will map each chest type (from 1 to p, inclusive) to a list of ALL rooms
* in which that chest is located.
* NOTE: the rooms will be saved in the form of a single integer that represents
* the row and column values.
*
* EXAMPLE: if a chest type 2 is located in rooms (2,3) and (1,0), and
* the rooms are in a 4x4 grid, then the array will save the following:
* chestTypeToRoomLocation[2] = {11, 4}
*
* where (2,3) is represented as 2*4+3 = 11, and
* (1,0) is represented as 1*4+0 = 4.
* */
LinkedList<Integer>[] chestTypeToRoomLocation;
/* An Array containing Arrays of neighboring cells for rooms of given chest type x.
* neighboringCellsAscending[x] = {All Cells containing chest of type x+1} */
Cell[][] neighboringCellsAscending;
/* The goal destination Cell, which has chest type p (where p is the last integer in a given input problem). */
Cell destinationCell;
/**
* constructor.
*/
@SuppressWarnings("unchecked")
public VanyaAndTreasure() {
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
//Read the first line
String line = rd.readLine();
StringTokenizer tokenizer = new StringTokenizer(line);
this.n = Integer.parseInt(tokenizer.nextToken());
this.m = Integer.parseInt(tokenizer.nextToken());
this.p = Integer.parseInt(tokenizer.nextToken());
/* Read what this array of LinkedLists is all about near the top of this file.
* Allocating p + 1 space as we'll have the index go from 1 to p inclusive. */
//Unavoidable warning; flaw of Java generics. Used SuppressWarning() at the top of this constructor method.
this.chestTypeToRoomLocation = (LinkedList<Integer>[])new LinkedList<?>[this.p + 1];
/* Initialize room Array */
this.roomArr = new Cell[n][m];
/* Read the next n lines. Each line will have m entries. Use these values to
* create a 2-D array roomArr. */
for (int i = 0; i < n; i++) {
line = rd.readLine();
tokenizer = new StringTokenizer(line);
for (int j = 0; j < m; j++) {
int chestType = Integer.parseInt(tokenizer.nextToken());
this.roomArr[i][j] = new Cell(chestType, i, j); //create new room
LinkedList<Integer> tempList = chestTypeToRoomLocation[chestType];
/* if Array above hasn't yet created the linkedlist associated with this chestType,
* initialize a new linked list, then add the current room to the linkedlist */
if (tempList == null) {
tempList = new LinkedList<>();
chestTypeToRoomLocation[chestType] = tempList;
}
tempList.add(i * m + j); //Add this room to the linkedlist associated with the hashmap
/* If the value we read pertains to the final chest type p, then we know
* that this is the ultimate destination, and that there is only ONE chest
* of this type. So let's save this cell for future reference. */
if (chestType == this.p) {
this.destinationCell = this.roomArr[i][j];
}
}
//end for j
}
//end for i
this.shortestDist = new int[n][m];
for (int i = 0; i < shortestDist.length; i++) {
Arrays.fill(shortestDist[i], 99999999);
}
this.neighboringCellsAscending = new Cell[p][];
//Print out the final answer
System.out.println(this.shortestDistIterative());
rd.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private int shortestDistIterative() {
/* Let's initialize the "shortest" distances for rooms with chest type 1.
* Since Vanya always begins at (0,0), it's trivial to initialize these distances. */
Cell[] cellsWithChestType1 = neighboringCellsAscending[0];
if (cellsWithChestType1 == null || cellsWithChestType1.length == 0) { //if no neighbors have been initialized yet...
cellsWithChestType1 = getNeighboringCells(0, true); //invoke custom method
neighboringCellsAscending[0] = cellsWithChestType1; //and save it to the array so we don't do same computation twice
}
for (Cell cellWithChestType1 : cellsWithChestType1) {
shortestDist[cellWithChestType1.row][cellWithChestType1.col] = cellWithChestType1.row + cellWithChestType1.col;
}
for (int i = 1; i < p; ++i) {
Cell[] neighbors = neighboringCellsAscending[i];
if (neighbors == null) { //if no neighbors have been initialized yet...
neighbors = getNeighboringCells(i, true); //invoke custom method
neighboringCellsAscending[i] = neighbors; //and save it to the array so we don't do same computation twice
}
Cell[] prevNeighbors = neighboringCellsAscending[i - 1];
/* If there are too many of these types of rooms, a bfs is more efficient */
if (prevNeighbors.length * neighbors.length >= this.n * this.m) {
this.bfs2(prevNeighbors, neighbors);
/* Otherwise, this dyn. programming method is efficient enough. */
} else {
for (Cell neighbor : neighbors) {
for (Cell prevNeighbor : prevNeighbors) {
shortestDist[neighbor.row][neighbor.col] = Math.min(shortestDist[neighbor.row][neighbor.col],
shortestDist[prevNeighbor.row][prevNeighbor.col] + getDist(prevNeighbor, neighbor));
}
}
//end for Cell neighbor: neighbors
}
//end if/else
}
//end for i
return shortestDist[this.destinationCell.row][this.destinationCell.col];
}
//end private int shortestDistIterative
/**
* Method: bfs2
* @param prevNeighbors
* @param neighbors
* Efficient version of multiple-source and multiple-destination BFS. Better than bfs().
*/
private void bfs2(Cell[] prevNeighbors, Cell[] neighbors) {
/* Initialize the temporary array of shortest distances. We'll update the global array at the end of this method. */
int[][] distance = new int[n][m];
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++)
distance[i][j] = 99999999;
/* Initialize the shortest possible distances for the prev. neighboring rooms.
* We'll propagate BFS from these locations, where we KNOW we have the shortest way of reaching them. */
for (Cell p : prevNeighbors)
distance[p.row][p.col] = shortestDist[p.row][p.col];
/* We'll explore all the ways in which can move either RIGHT or DOWN, and update the temporary
* 2D array distance accordingly. Notice we're starting from the top-left corner to ensure
* we explore all possibilities. */
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) {
if (i+1 < n) distance[i + 1][j] = Math.min(distance[i + 1][j], distance[i][j] + 1);
if (j+1 < n) distance[i][j + 1] = Math.min(distance[i][j + 1], distance[i][j] + 1);
}
/* We'll now explore all the ways in which can move either LEFT or UP, and update the temporary
* 2D array distance accordingly. Note we're starting from the bottom-right corner this time. */
for (int i = n-1; i >= 0; i--) for (int j = m-1; j >= 0; j--) {
if (i-1 >= 0) distance[i - 1][j] = Math.min(distance[i - 1][j], distance[i][j] + 1);
if (j-1 >= 0) distance[i][j - 1] = Math.min(distance[i][j - 1], distance[i][j] + 1);
}
/* Now distance[i][j] contains the shortest possible distance for all cells, starting
* from any one of the cells contained in the array prevNeighbors. So we can update
* the global shortestDist array for the array of cells that we're concerned with, i.e. neighbors. */
for (Cell cell : neighbors)
shortestDist[cell.row][cell.col] = distance[cell.row][cell.col];
}
/**
* Method: bfs
* @param prevNeighbors
* @param neighbors
*
* UPDATE: not as efficient as bfs2() method.
*/
// private void bfs(Cell[] prevNeighbors, Cell[] neighbors) {
// PriorityQueue<Cell> minPQ = new PriorityQueue<Cell>(Arrays.asList(prevNeighbors));
// boolean[][] visited = new boolean[n][m];
//
// /* Initialize the distance attribute for each Cell, for purposes of this BFS only. */
// for (int i = 0; i < this.n; i++) {
// for (int j = 0; j < this.m; j++) {
// if (this.roomArr[i][j].type == prevNeighbors[0].type) {
// this.roomArr[i][j].distance = this.shortestDist[i][j];
// visited[i][j] = true;
// }
// else {
// this.roomArr[i][j].distance = Integer.MAX_VALUE;
// }
// }
// }
//
// int numOfCurrNeighborsVisited = 0;
//
// while (numOfCurrNeighborsVisited < neighbors.length) {
// Cell currCell = minPQ.remove();
// ArrayList<Cell> bfsNeighbors = getBFSNeighbors(currCell, visited);
// for (Cell bfsNeighbor: bfsNeighbors) {
// if (bfsNeighbor.distance > currCell.distance + 1) {
// bfsNeighbor.distance = currCell.distance + 1;
// minPQ.add(bfsNeighbor);
// visited[bfsNeighbor.row][bfsNeighbor.col] = true;
// if (bfsNeighbor.type == neighbors[0].type) {
// numOfCurrNeighborsVisited++;
// }
// }
// }
// //end for Cell
// }
// //end while
//
// for (Cell neighbor : neighbors) {
// this.shortestDist[neighbor.row][neighbor.col] = neighbor.distance;
// }
// }
//end private void bfs
/**
* Method: getBFSNeighbors
* @param currCell
* @param visited
* @return
* Helper method for bfs(). No longer needed.
*/
// private ArrayList<Cell> getBFSNeighbors(Cell currCell, boolean[][] visited) {
// int row = currCell.row;
// int col = currCell.col;
// int maxPossibleNeighbors = 4;
//
// ArrayList<Cell> bfsNeighbors = new ArrayList<>();
// int[] rowOffset = {0, 0, 1,-1};
// int[] colOffset = {1,-1, 0, 0};
// for (int i = 0; i < maxPossibleNeighbors; i++) {
// int neighborRow = row + rowOffset[i];
// int neighborCol = col + colOffset[i];
// if (neighborRow < 0 || neighborCol < 0 ||
// neighborRow >= this.n || neighborCol >= this.m ||
// visited[neighborRow][neighborCol] == true) {
// continue;
// }
// Cell bfsNeighbor = this.roomArr[neighborRow][neighborCol];
// bfsNeighbors.add(bfsNeighbor);
// }
// return bfsNeighbors;
// }
/**
* Method: getNeighboringCells
* @param chestType
* @return
*/
private Cell[] getNeighboringCells(int chestType, boolean ascending) {
/* All chests of type x - 1 can open chests of type x, so neighboring rooms of type x
* contain chests of chestType x - 1. */
LinkedList<Integer> neighborRooms = this.chestTypeToRoomLocation[ascending? chestType + 1 : chestType - 1];
if (neighborRooms == null) {
return new Cell[0];
}
Cell[] neighbors = new Cell[neighborRooms.size()];
ListIterator<Integer> iter = neighborRooms.listIterator();
for (int i = 0; i < neighbors.length; i++) {
int thisRoom = iter.next();
int thisRow = thisRoom / this.m;
int thisCol = thisRoom % this.m;
neighbors[i] = this.roomArr[thisRow][thisCol];
}
return neighbors;
}
private int getDist(Cell c1, Cell c2) {
return Math.abs(c1.row - c2.row) + Math.abs(c1.col - c2.col);
}
/**
* Method: minTotalDistToGetTreasure
* @return the minimum possible total distance Vanya has to walk
* in order to get the treasure from the chest of type this.p.
*
* This uses A*. However, since the heuristic is poor, this is inefficient.
* We could try to improve the heuristic, but in the time it takes to do that,
* we're better off just running the dynamic programming + bfs2() methods above.
*/
// private int minTotalDistToGetTreasure() {
//
// /* This will save all neighboring cells for a given chest type for easy reference and efficiency. */
//// this.neighboringCells = new HashMap<>();
////
//// /* Might be worth it to try something like A* for this one...
//// * First set the neighbors of each chest type in all the rooms */
//// for (int i = 0; i < this.roomArr.length; i++) {
//// for (int j = 0; j < this.roomArr[i].length; j++) {
//// Cell thisCell = this.roomArr[i][j];
//// int chestType = thisCell.type;
////
//// //Set all the neighbors
//// Cell[] neighbors = neighboringCells.get(chestType); //get the neighbors from the hashmap above
//// if (neighbors == null) { //if no neighbors have been initialized yet...
//// neighbors = getNeighboringCells(chestType); //invoke custom method
//// neighboringCells.put(chestType, neighbors); //and save it to the hashmap so we don't do same computation twice
//// }
////// thisCell.neighborArr = neighbors; //set the neighbors for this cell
////
//// /* Set the estimated manhattan distance from this cell to destination cell,
//// * provided that the manhattan distance cannot be shorter than the difference
//// * between destination chest type and this chest type.
//// *
//// * For example, if this cell type == 2 and destination cell type == 5,
//// * it will take at least 3 unlocking steps to get to the destination chest.
//// * So, if the manhattan distance between this cell and destination cell is only 2,
//// * we still have to set the est. distance at 3. */
////// thisCell.estDistRemaining = Math.max(
////// this.destinationCell.type - thisCell.type,
////// Math.abs(this.destinationCell.row - thisCell.row) + Math.abs(this.destinationCell.col - thisCell.col));
//// thisCell.computeEstDist();
////
//// }
//// //end for j
//// }
// //end for i
//
// /* Since we start at the upper leftmost corner -- i.e. the location (0,0) -- we'll first get
// * the locations of all the rooms with chest type 1 in it (remember, these chest types don't need keys)
// * and set them as the initial "neighbors".
// *
// * We call the below method with parameter 0 (although technically there is no chestType with value 0)
// * because doing so will give us an array of all the cells that have chestType 1. */
//
// Cell[] initialNeighbors = this.getNeighboringCells(0);
//
// /* Now put these in a prioritylist. Since the Cell objects implement the Comparable interface,
// * they will be "sorted" from smallest to largest in the priorityqueue. */
// PriorityQueue<Cell> pq = new PriorityQueue<>(Arrays.asList(initialNeighbors));
//
// /* Testing priorityquee */
//// while (!pq.isEmpty()) {
//// System.out.println(pq.remove());
//// }
//
// Cell currRoom = null;
//
// /* Begin A* algorithm */
// HashSet<Cell> openList = new HashSet<>(pq);
// HashSet<Cell> closedList = new HashSet<>();
// while (currRoom != this.destinationCell && !pq.isEmpty()) {
// currRoom = pq.remove();
// currRoom.visited = true;
// openList.remove(currRoom);
// closedList.add(currRoom);
// Cell[] neighbors = neighboringCells.get(currRoom.type);
// for (Cell neighbor: neighbors) {
// if (!neighbor.visited && neighbor.distSoFar > currRoom.distSoFar + this.getDist(currRoom, neighbor)) {
// neighbor.distSoFar = currRoom.distSoFar + this.getDist(currRoom, neighbor);
// pq.remove(neighbor);
// pq.add(neighbor);
// openList.add(neighbor);
// }
// }
// //end for
// }
// //end while
//
// if (currRoom == this.destinationCell) {
// return currRoom.distSoFar + currRoom.estDistRemaining;
// }
// return -1;
// }
public static void main(String[] args) {
new VanyaAndTreasure();
// System.out.println(vt.minTotalDistToGetTreasure());
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | 70ef74d57dcd950f2fff59c76ec5d687 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.util.*;
import java.io.*;
public class Scarlet {
private static final int INFINITY = 1000000007;
public static void main(String[] args) throws IOException
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
private static void solve(FastScanner in, PrintWriter out)
{
int n = in.nextInt(), m = in.nextInt(), levels = in.nextInt();
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
grid[i][j] = in.nextInt();
List<List<Point>> byLevel = new ArrayList<>();
for (int i = 0; i <= levels; i++)
byLevel.add(new ArrayList<>());
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
byLevel.get(grid[i][j]).add(new Point(i, j));
int[][] distance = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
distance[i][j] = INFINITY;
for (Point p : byLevel.get(1))
distance[p.row][p.column] = p.row + p.column;
for (int level = 1; level < levels; level++)
update(n, m, grid, level, byLevel.get(level), byLevel.get(level+1), distance);
Point p = byLevel.get(levels).get(0);
out.println(distance[p.row][p.column]);
}
private static void update(int n, int m, int[][] grid, int level, List<Point> sources, List<Point> targets, int[][] distance)
{
boolean[] active = new boolean[n];
for (Point p : sources)
active[p.row] = true;
ArrayList<Integer>[] byColumn = new ArrayList[m];
for(int j=0; j<m; ++j) byColumn[j] = new ArrayList<>();
for (Point p : targets)
byColumn[p.column].add(p.row);
for(int row = 0; row < n; row++) if (active[row])
{
int d = INFINITY;
for (int column = 0; column < m; column++)
{
d++;
if (grid[row][column] == level) d = Math.min(d, distance[row][column]);
if (byColumn[column].isEmpty()) continue;
for (int targetRow : byColumn[column])
distance[targetRow][column] = Math.min(distance[targetRow][column], d+Math.abs(targetRow-row));
}
d = INFINITY;
for (int column = m-1; column >= 0; column--)
{
d++;
if (grid[row][column] == level) d = Math.min(d, distance[row][column]);
if (byColumn[column].isEmpty()) continue;
for (int targetRow : byColumn[column])
distance[targetRow][column] = Math.min(distance[targetRow][column], d+Math.abs(targetRow-row));
}
}
}
private static class Point
{
int row;
int column;
Point (int row, int column)
{
this.row = row;
this.column = column;
}
}
private static class FastScanner
{
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream stream)
{
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try { tokenizer = new StringTokenizer(reader.readLine()); }
catch (IOException e) { throw new RuntimeException(e); }
}
return tokenizer.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | ad3df0996c87b23907eb36741ef4e69a | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.abs;
public class D2 {
private static final int INFINITY = (300+300)*300*300;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt(), m = in.nextInt(), p = in.nextInt();
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
grid[i][j] = in.nextInt();
out.println(solve(n, m, p, grid));
out.close();
}
private static int solve(int n, int m, int levels, int[][] grid)
{
List<List<Point>> byLevel = new ArrayList<>();
for (int i = 0; i <= levels; i++)
byLevel.add(new ArrayList<>());
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
byLevel.get(grid[i][j]).add(new Point(i, j));
int[][] distance = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
distance[i][j] = INFINITY;
for (Point p : byLevel.get(1))
distance[p.row][p.column] = p.row + p.column;
for (int level = 1; level < levels; level++)
update(n, m, grid, level, byLevel.get(level), byLevel.get(level+1), distance);
Point p = byLevel.get(levels).get(0);
return distance[p.row][p.column];
}
private static void update(int n, int m, int[][] grid, int level, List<Point> sources, List<Point> targets, int[][] distance)
{
boolean[] active = new boolean[n];
for (Point p : sources)
active[p.row] = true;
List<List<Integer>> byColumn = new ArrayList<>();
for (int i = 0; i < m; i++) byColumn.add(new ArrayList<>());
for (Point p : targets) byColumn.get(p.column).add(p.row);
for (int row = 0; row < n; row++) if (active[row])
{
int d = INFINITY;
for (int column = 0; column < m; column++)
{
d++;
if (grid[row][column] == level) d = Math.min(d, distance[row][column]);
for (int targetRow : byColumn.get(column))
distance[targetRow][column] = Math.min(distance[targetRow][column], d + abs(row - targetRow));
}
d = INFINITY;
for (int column = m-1; column >= 0; column--)
{
d++;
if (grid[row][column] == level) d = Math.min(d, distance[row][column]);
for (int targetRow : byColumn.get(column))
distance[targetRow][column] = Math.min(distance[targetRow][column], d + abs(row - targetRow));
}
}
}
private static class Point
{
int row;
int column;
Point (int row, int column)
{
this.row = row;
this.column = column;
}
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | 024881c4df19ae738735807f4db9c935 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.util.*;
import java.io.*;
public class Scarlet {
private static final int N = 1005;
private static final int INFINITY = 1000000007;
public static void main(String[] args) throws IOException
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
private static void solve(FastScanner in, PrintWriter out)
{
int n = in.nextInt(), m = in.nextInt(), levels = in.nextInt();
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
grid[i][j] = in.nextInt();
ArrayList<Point>[] byLevel = new ArrayList[N*N];
for (int i = 1; i <= levels; i++)
byLevel[i] = new ArrayList<>();
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
byLevel[grid[i][j]].add(new Point(i, j));
int[][] distance = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
distance[i][j] = INFINITY;
for (Point p : byLevel[1])
distance[p.row][p.column] = p.row + p.column;
for (int level = 1; level < levels; level++)
update(n, m, grid, level, byLevel[level], byLevel[level+1], distance);
Point p = byLevel[levels].get(0);
out.println(distance[p.row][p.column]);
}
private static void update(int n, int m, int[][] grid, int level, ArrayList<Point> sources, ArrayList<Point> targets, int[][] distance)
{
boolean[] active = new boolean[N];
for (Point p : sources)
active[p.row] = true;
ArrayList<Integer>[] byColumn = new ArrayList[N];
for(int j=0; j<m; ++j) byColumn[j] = new ArrayList<>(0);
for (Point p : targets)
byColumn[p.column].add(p.row);
for(int row = 0; row < n; row++) if (active[row])
{
int d = INFINITY;
for (int column = 0; column < m; column++)
{
d++;
if (grid[row][column] == level) d = Math.min(d, distance[row][column]);
for (int targetRow : byColumn[column])
distance[targetRow][column] = Math.min(distance[targetRow][column], d+Math.abs(targetRow-row));
}
d = INFINITY;
for (int column = m-1; column >= 0; column--)
{
d++;
if (grid[row][column] == level) d = Math.min(d, distance[row][column]);
for (int targetRow : byColumn[column])
distance[targetRow][column] = Math.min(distance[targetRow][column], d+Math.abs(targetRow-row));
}
}
}
private static class Point
{
int row;
int column;
Point (int row, int column)
{
this.row = row;
this.column = column;
}
}
private static class FastScanner
{
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream stream)
{
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try { tokenizer = new StringTokenizer(reader.readLine()); }
catch (IOException e) { throw new RuntimeException(e); }
}
return tokenizer.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | c27daae71adfcbba4885add6a5094df5 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.abs;
import static java.lang.Math.min;
public class D1 {
private final static int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
public static void main(String[] args) {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
int p = in.nextInt();
int[][] grid = new int[n][m];
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++)
grid[i][j] = in.nextInt();
out.println(solve(n, m, p, grid));
out.close();
}
private static int solve(int n, int m, int levels, int[][] grid) {
List<List<Point>> byLevel = new ArrayList<>();
for (int i = 0; i <= levels; i++)
byLevel.add(new ArrayList<>());
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++)
byLevel.get(grid[i][j]).add(new Point(i, j));
int[][] distance = new int[n][m];
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++)
distance[i][j] = Integer.MAX_VALUE;
for (Point p : byLevel.get(1)) {
distance[p.row][p.column] = p.row + p.column;
}
for (int level = 1; level < levels; level++) {
List<Point> source = byLevel.get(level);
List<Point> target = byLevel.get(level+1);
if (source.size() * target.size() > n*m) bfs(n, m, source, target, distance);
else dag(source, target, distance);
}
Point p = byLevel.get(levels).get(0);
return distance[p.row][p.column];
}
private static void dag(List<Point> source, List<Point> target, int[][] distance) {
for (Point p : source) for (Point q : target) {
int d = abs(p.column-q.column) + abs(p.row-q.row);
distance[q.row][q.column] = min(distance[q.row][q.column], distance[p.row][p.column] + d);
}
}
private static void bfs(int n, int m, List<Point> source, List<Point> target, int[][] globalDistance) {
int[][] distance = new int[n][m];
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++)
distance[i][j] = Integer.MAX_VALUE - 10000;
for (Point p : source)
distance[p.row][p.column] = globalDistance[p.row][p.column];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) {
if (i+1 < n) distance[i + 1][j] = Math.min(distance[i + 1][j], distance[i][j]+1);
if (j+1 < n) distance[i][j + 1] = Math.min(distance[i][j + 1], distance[i][j]+1);
}
for (int i = n-1; i >= 0; i--) for (int j = m-1; j >= 0; j--) {
if (i-1 >= 0) distance[i - 1][j] = Math.min(distance[i - 1][j], distance[i][j]+1);
if (j-1 >= 0) distance[i][j - 1] = Math.min(distance[i][j - 1], distance[i][j]+1);
}
for (Point point : target)
globalDistance[point.row][point.column] = distance[point.row][point.column];
}
private static class Point {
int row;
int column;
Point (int row, int column) {
this.row = row;
this.column = column;
}
}
private static class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try { tokenizer = new StringTokenizer(reader.readLine()); }
catch (IOException e) { throw new RuntimeException(e); }
}
return tokenizer.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | d4fde0ad3919c59fdef0cd6defa9a54d | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.util.*;
import java.io.*;
public class Scarlet {
public static void main(String[] args) throws IOException{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
private static final int N = 1005;
private static final int oo = 1000000007;
private static class Task {
public void solve(InputReader in, PrintWriter out) {
int m = in.nextInt(), n = in.nextInt(), p = in.nextInt();
int[][] a = new int[N][N], f = new int[N][N];
ArrayList<pair>[] color = new ArrayList[N*N];
for(int i=1; i<=p; ++i) color[i] = new ArrayList<>();
for(int i=1; i<=m; ++i) for(int j=1; j<=n; ++j) {
a[i][j] = in.nextInt();
if (a[i][j] == 1) f[i][j] = i+j-2;
else f[i][j] = oo;
color[a[i][j]].add(new pair(i,j));
}
for(int k = 1; k<p; ++k) {
boolean[] exist = new boolean[N];
for(int i=0; i<color[k].size(); ++i) {
pair pr = color[k].get(i);
exist[pr.F] = true;
}
ArrayList<Integer>[] col = new ArrayList[N];
for(int j=1; j<=n; ++j) col[j] = new ArrayList<>(0);
for(int i=0; i<color[k+1].size(); ++i) {
pair pr = color[k+1].get(i);
col[pr.S].add(pr.F);
}
for(int i=1; i<=m; ++i) if (exist[i]) {
int best = oo;
for(int j=1; j<=n; ++j) {
++best;
if (a[i][j] == k) best = Math.min(best, f[i][j]);
for(int l=0; l<col[j].size(); ++l) {
int x = col[j].get(l);
f[x][j] = Math.min(f[x][j], best+Math.abs(x-i));
}
}
best = oo;
for(int j=n; j>=1; --j) {
++best;
if (a[i][j] == k) best = Math.min(best, f[i][j]);
for(int l=0; l<col[j].size(); ++l) {
int x = col[j].get(l);
f[x][j] = Math.min(f[x][j], best+Math.abs(x-i));
}
}
}
}
for(int i=1; i<=m; ++i) for(int j=1; j<=n; ++j)
if (a[i][j] == p) out.println(f[i][j]);
}
static class pair {
int F, S;
pair(int F, int S) {
this.F = F;
this.S = S;
}
}
}
private static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | 34ff2ecc7f7647d2fbf81c42bf0bdae6 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.util.*;
import java.io.*;
public class Scarlet {
private static final int N = 1005;
private static final int INFINITY = 1000000007;
public static void main(String[] args) throws IOException
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
private static void solve(FastScanner in, PrintWriter out)
{
int n = in.nextInt(), m = in.nextInt(), levels = in.nextInt();
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
grid[i][j] = in.nextInt();
ArrayList<Point>[] byLevel = new ArrayList[N*N];
for (int i = 1; i <= levels; i++)
byLevel[i] = new ArrayList<>();
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
byLevel[grid[i][j]].add(new Point(i, j));
int[][] distance = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
distance[i][j] = INFINITY;
for (Point p : byLevel[1])
distance[p.row][p.column] = p.row + p.column;
for (int level = 1; level < levels; level++)
update(n, m, grid, level, byLevel[level], byLevel[level+1], distance);
Point p = byLevel[levels].get(0);
out.println(distance[p.row][p.column]);
}
private static void update(int n, int m, int[][] grid, int level, ArrayList<Point> sources, ArrayList<Point> targets, int[][] distance)
{
boolean[] exist = new boolean[N];
for(int i=0; i<sources.size(); ++i) {
Point pr = sources.get(i);
exist[pr.row] = true;
}
ArrayList<Integer>[] col = new ArrayList[N];
for(int j=0; j<m; ++j) col[j] = new ArrayList<>(0);
for(int i=0; i<targets.size(); ++i) {
Point pr = targets.get(i);
col[pr.column].add(pr.row);
}
for(int i=0; i<n; ++i) if (exist[i]) {
int d = INFINITY;
for(int j=0; j<m; ++j) {
++d;
if (grid[i][j] == level) d = Math.min(d, distance[i][j]);
for(int l=0; l<col[j].size(); ++l) {
int x = col[j].get(l);
distance[x][j] = Math.min(distance[x][j], d+Math.abs(x-i));
}
}
d = INFINITY;
for(int j=m-1; j>=0; --j) {
++d;
if (grid[i][j] == level) d = Math.min(d, distance[i][j]);
for(int l=0; l<col[j].size(); ++l) {
int x = col[j].get(l);
distance[x][j] = Math.min(distance[x][j], d+Math.abs(x-i));
}
}
}
}
private static class Point
{
int row;
int column;
Point (int row, int column)
{
this.row = row;
this.column = column;
}
}
private static class FastScanner
{
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream stream)
{
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try { tokenizer = new StringTokenizer(reader.readLine()); }
catch (IOException e) { throw new RuntimeException(e); }
}
return tokenizer.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | e630973c02e31be09ae0c31fe0940454 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.util.*;
import java.io.*;
public class Scarlet {
private static final int N = 1005;
private static final int oo = 1000000007;
public static void main(String[] args) throws IOException
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
private static void solve(FastScanner in, PrintWriter out)
{
int m = in.nextInt(), n = in.nextInt(), p = in.nextInt();
int[][] a = new int[N][N], f = new int[N][N];
ArrayList<Point>[] color = new ArrayList[N*N];
for(int i=1; i<=p; ++i) color[i] = new ArrayList<>();
for(int i=1; i<=m; ++i) for(int j=1; j<=n; ++j) {
a[i][j] = in.nextInt();
if (a[i][j] == 1) f[i][j] = i+j-2;
else f[i][j] = oo;
color[a[i][j]].add(new Point(i,j));
}
for(int k = 1; k<p; ++k) {
boolean[] exist = new boolean[N];
for(int i=0; i<color[k].size(); ++i) {
Point pr = color[k].get(i);
exist[pr.row] = true;
}
ArrayList<Integer>[] col = new ArrayList[N];
for(int j=1; j<=n; ++j) col[j] = new ArrayList<>(0);
for(int i=0; i<color[k+1].size(); ++i) {
Point pr = color[k+1].get(i);
col[pr.column].add(pr.row);
}
for(int i=1; i<=m; ++i) if (exist[i]) {
int best = oo;
for(int j=1; j<=n; ++j) {
++best;
if (a[i][j] == k) best = Math.min(best, f[i][j]);
for(int l=0; l<col[j].size(); ++l) {
int x = col[j].get(l);
f[x][j] = Math.min(f[x][j], best+Math.abs(x-i));
}
}
best = oo;
for(int j=n; j>=1; --j) {
++best;
if (a[i][j] == k) best = Math.min(best, f[i][j]);
for(int l=0; l<col[j].size(); ++l) {
int x = col[j].get(l);
f[x][j] = Math.min(f[x][j], best+Math.abs(x-i));
}
}
}
}
for(int i=1; i<=m; ++i) for(int j=1; j<=n; ++j)
if (a[i][j] == p) out.println(f[i][j]);
}
private static class Point
{
int row;
int column;
Point (int row, int column) {
this.row = row;
this.column = column;
}
}
private static class FastScanner
{
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream stream)
{
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try { tokenizer = new StringTokenizer(reader.readLine()); }
catch (IOException e) { throw new RuntimeException(e); }
}
return tokenizer.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | 9ab0e966ee1a3541dbceab8b035a2dd0 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.abs;
public class D2 {
private static final int INFINITY = (300+300)*300*300;
private static final int N = 300;
public static void main(String[] args)
{
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt(), m = in.nextInt(), p = in.nextInt();
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
grid[i][j] = in.nextInt();
out.println(solve(n, m, p, grid));
out.close();
}
private static int solve(int n, int m, int levels, int[][] grid)
{
List<Point>[] byLevel = new ArrayList[levels+1];
for (int i = 1; i <= levels; i++) byLevel[i] = new ArrayList<>();
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
byLevel[grid[i][j]].add(new Point(i, j));
int[][] distance = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
distance[i][j] = Integer.MAX_VALUE;
for (Point p : byLevel[1])
distance[p.row][p.column] = p.row + p.column;
for (int level = 1; level < levels; level++)
update(n, m, grid, level, byLevel[level], byLevel[level+1], distance);
Point p = byLevel[levels].get(0);
return distance[p.row][p.column];
}
private static void update(int n, int m, int[][] grid, int level, List<Point> sources, List<Point> targets, int[][] distance)
{
boolean[] active = new boolean[N];
for (Point p : sources)
active[p.row] = true;
List<Integer>[] byColumn = new ArrayList[N];
for (int i = 0; i < m; i++) byColumn[i] = new ArrayList<>();
for (Point p : targets) byColumn[p.column].add(p.row);
for (int row = 0; row < n; row++) if (active[row])
{
int d = INFINITY;
for (int column = 0; column < m; column++)
{
d++;
if (grid[row][column] == level) d = Math.min(d, distance[row][column]);
for (int targetRow : byColumn[column])
distance[targetRow][column] = Math.min(distance[targetRow][column], d + abs(row - targetRow));
}
d = INFINITY;
for (int column = m-1; column >= 0; column--)
{
d++;
if (grid[row][column] == level) d = Math.min(d, distance[row][column]);
for (int targetRow : byColumn[column])
distance[targetRow][column] = Math.min(distance[targetRow][column], d + abs(row - targetRow));
}
}
}
private static class Point
{
int row;
int column;
Point (int row, int column)
{
this.row = row;
this.column = column;
}
}
private static class FastScanner
{
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream stream)
{
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try { tokenizer = new StringTokenizer(reader.readLine()); }
catch (IOException e) { throw new RuntimeException(e); }
}
return tokenizer.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | d031e11cde14d3d684a96c7f8a7b74f4 | train_004.jsonl | 1464798900 | Vanya is in the palace that can be represented as a grid nβΓβm. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xββ€βpβ-β1 contains a key that can open any chest of type xβ+β1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1,β1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,βc1) (the cell in the row r1 and column c1) and (r2,βc2) is equal to |r1β-βr2|β+β|c1β-βc2|. | 256 megabytes | import java.util.*;
import java.io.*;
public class Scarlet {
private static final int N = 1005;
private static final int INFINITY = 1000000007;
public static void main(String[] args) throws IOException
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
private static void solve(FastScanner in, PrintWriter out)
{
int n = in.nextInt(), m = in.nextInt(), levels = in.nextInt();
int[][] grid = new int[N][N], distance = new int[N][N];
ArrayList<Point>[] byLevel = new ArrayList[N*N];
for(int i=1; i<=levels; ++i) byLevel[i] = new ArrayList<>();
for(int i=1; i<=n; ++i) for(int j=1; j<=m; ++j)
{
grid[i][j] = in.nextInt();
if (grid[i][j] == 1) distance[i][j] = i+j-2;
else distance[i][j] = INFINITY;
byLevel[grid[i][j]].add(new Point(i,j));
}
for (int level = 1; level < levels; level++)
update(n, m, grid, level, byLevel[level], byLevel[level+1], distance);
Point p = byLevel[levels].get(0);
out.println(distance[p.row][p.column]);
}
private static void update(int n, int m, int[][] grid, int level, ArrayList<Point> sources, ArrayList<Point> targets, int[][] distance)
{
boolean[] exist = new boolean[N];
for(int i=0; i<sources.size(); ++i) {
Point pr = sources.get(i);
exist[pr.row] = true;
}
ArrayList<Integer>[] col = new ArrayList[N];
for(int j=1; j<=m; ++j) col[j] = new ArrayList<>(0);
for(int i=0; i<targets.size(); ++i) {
Point pr = targets.get(i);
col[pr.column].add(pr.row);
}
for(int i=1; i<=n; ++i) if (exist[i]) {
int d = INFINITY;
for(int j=1; j<=m; ++j) {
++d;
if (grid[i][j] == level) d = Math.min(d, distance[i][j]);
for(int l=0; l<col[j].size(); ++l) {
int x = col[j].get(l);
distance[x][j] = Math.min(distance[x][j], d+Math.abs(x-i));
}
}
d = INFINITY;
for(int j=m; j>=1; --j) {
++d;
if (grid[i][j] == level) d = Math.min(d, distance[i][j]);
for(int l=0; l<col[j].size(); ++l) {
int x = col[j].get(l);
distance[x][j] = Math.min(distance[x][j], d+Math.abs(x-i));
}
}
}
}
private static class Point
{
int row;
int column;
Point (int row, int column)
{
this.row = row;
this.column = column;
}
}
private static class FastScanner
{
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream stream)
{
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try { tokenizer = new StringTokenizer(reader.readLine()); }
catch (IOException e) { throw new RuntimeException(e); }
}
return tokenizer.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
}
}
| Java | ["3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3", "3 3 9\n1 3 5\n8 9 7\n4 6 2", "3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12"] | 1.5 seconds | ["5", "22", "11"] | null | Java 8 | standard input | [
"dp",
"graphs",
"data structures",
"shortest paths"
] | 5bc36edc3bf279550cf0250ea7c5a680 | The first line of the input contains three integers n, m and p (1ββ€βn,βmββ€β300,β1ββ€βpββ€βnΒ·m)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1ββ€βaijββ€βp)Β β the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arcβ=βx). Also, it's guaranteed that there is exactly one chest of type p. | 2,300 | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. | standard output | |
PASSED | a8c5a010e1bc28de8a1e3496d50d477a | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
public class Escape {
public static void main(String[] args) {
PrintWriter cout = new PrintWriter(System.out);
Scanner sc = new Scanner(System.in);
String input = sc.next();
int[] arr = new int[input.length()];
int l=0,r=input.length()-1;
int n = input.length();
for(int i=0;i<n;i++){
if(input.charAt(i) == 'l'){
arr[r--] = i+1;
}
else{
//arr[l] = i+1; l++;
cout.println(i+1);
}
}
for(int i=r+1;i<n;i++){
cout.println(arr[i]);
}
cout.flush();
}
} | Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | a848e8d8ee581380133a6cb947fac7db | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.lang.*;
import java.io.*;
import java.util.*;
public class Escape {
public static void main(String[] args) throws java.lang.Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(in, out);
out.close();
}
}
class TaskA {
public void solve(InputReader in, PrintWriter out) {
String s = in.next();
int len = s.length();
int ln = 0, rn = 0;
int[] l = new int[len];
int[] r = new int[len];
int i, j, k;
for (i=0; i<len; ++i) {
if (s.charAt(i) == 'l') {
l[ln++] = i + 1;
} else {
r[rn++] = i + 1;
}
}
for (i=0; i<rn; ++i)
out.println(r[i]);
for (i=ln-1; i>=0; --i)
out.println(l[i]);
}
}
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());
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 06b8587b2f20ba2d6c40bb3a7a93b00f | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Main {
public static void main(String[] args) throws IOException{
Scanner k = new Scanner(System.in);
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
String str=input.readLine();
int right=0;
int left=str.length()-1;
int[] array=new int[str.length()];
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i)=='r') {
out.println(i+1);
right++;
}
else {
array[left]=i+1;
left--;
}
}
for (int i = right; i < array.length; i++) {
out.println(array[i]);
}
out.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 9e79af6d557779d43c2330d75d85b78a | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class escapefromstone {
public static void main(String[] args) throws IOException {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
String x=in.readLine();
int a[]=new int[x.length()];
int count=0;
for (int i = 0; i < x.length(); i++) {
if(x.charAt(i)=='r'){
out.println(i+1);
}
else{
a[count]=i+1;
count++;
}
}
for (int i = count-1; i >=0; i--) {
out.println(a[i]);
}
out.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 8579e854f513490e35ee2ce1cf574fe9 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes |
import java.io.DataInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Hashtable;
public class C {
public static void main(String[] args) throws Exception {
C obj = new C();
Parsedoubt in = obj. new Parsedoubt(System.in);
StringBuffer sb = new StringBuffer();
String s = in.nextString();
solve(sb , s);
System.out.println(sb);
}
public static void solve(StringBuffer sb , String s){
/*
int l = s.length();
double[] data = new double[l];
Hashtable<Double , Integer> table = new Hashtable<Double , Integer>();
double start =0;
double end = 1;
for(int j=0; j<l; j++){
if(s.charAt(j) == 'l'){
end = (start + end)/2;
data[j] = end;
table.put(end, j);
}
else{
start = (start + end)/2;
data[j] = start;
table.put(start, j);
}
}
Arrays.sort(data);
for(int j=0; j<l; j++){
int temp = table.get(data[j]);
sb.append((temp+1) + "\n");
}
* */
int l = s.length();
int start = 0;
int end = l-1;
Hashtable<Integer , Integer> table = new Hashtable<Integer , Integer>();
for(int j=0; j<l; j++){
if(s.charAt(j) == 'l'){
table.put(end, j);
end--;
}
else{
table.put(start, j);
start++;
}
}
for(int j=0; j<l; j++){
int temp = table.get(j);
sb.append((temp+1) + "\n");
}
}
class Parsedoubt {
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parsedoubt(InputStream in) {
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception {
StringBuffer sb = new StringBuffer("");
byte c = read();
while (c <= ' ') {
c = read();
}
do {
sb.append((char) c);
c = read();
} while (c > ' ');
return sb.toString();
}
public char nextChar() throws Exception {
byte c = read();
while (c <= ' ') {
c = read();
}
return (char) c;
}
public int nextInt() throws Exception {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws Exception {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws Exception {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws Exception {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 0f808caa25852ba286d559b32a79d1a1 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class P264A {
P264A(FastScanner in, PrintWriter out) throws Exception {
ArrayDeque<Integer> left = new ArrayDeque<Integer>();
ArrayDeque<Integer> right = new ArrayDeque<Integer>();
String str = in.next();
for (int i=0; i<str.length(); i++) {
if (str.charAt(i) == 'l')
right.offerFirst(i+1);
else
left.offerLast(i+1);
}
while(!left.isEmpty())
out.println(left.pollFirst());
while(!right.isEmpty())
out.println(right.pollFirst());
}
public static void main(String[] args) throws Exception {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new P264A(in,out);
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) throws Exception {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer(br.readLine().trim());
}
public String next() throws Exception {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine().trim());
return next();
}
return st.nextToken();
}
public double nextDouble() throws Exception {
return Double.parseDouble(next());
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
public String nextLine() throws Exception {
return br.readLine().trim();
}
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | d605ff72d873d09e8b67cb71fc53b859 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
public class CF264A {
public static void main(String[] args) throws Exception {
new CF264A().solve();
}
private void solve() throws Exception {
Scanner sc = new Scanner(System.in);
String s = sc.next();
int n = s.length();
char[] cs = new char[n];
s.getChars(0, n, cs, 0);
// Deque<Integer> stack = new ArrayDeque<>(n);
int[] loc = new int[n];
int r = n-1;
int l = 0;
for (int i = 0; i < n; i++) {
char c = cs[i];
if (c == 'l') {
loc[i] = r--;
} else {
loc[i] = l++;
}
}
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
ans[loc[i]] = i+1;
}
StringBuilder sb = new StringBuilder(5*n);
for (int i = 0; i < n; i++) {
sb.append(ans[i]).append("\n");
}
System.out.print(sb);
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 05293729e59e6491b33c912a9a6f5409 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
public class B {
static int N;
static PrintWriter out;
public static void main(String[] args) {
MScanner sc = new MScanner();
out = new PrintWriter(System.out);
String in = sc.next();
// Node root = new Node(1);
// Node cur = root;
// N = in.length();
// for(int a=0;a<in.length();a++){
// if(in.charAt(a)=='l'){
// cur.child=new Node(a+2);
// cur.dir=-1;
// }
// else{
// cur.child = new Node(a+2);
// cur.dir=1;
// }
// cur = cur.child;
// }
char[] c = in.toCharArray();
LinkedList<Integer> Q = new LinkedList<Integer>();
Q.add(0);
while(!Q.isEmpty()){
int i= Q.poll();
// System.err.println(i);
if(i==c.length)continue;
if(c[i]=='l'){
Q.addFirst(i);
Q.addFirst(i+1);
c[i]='x';
continue;
}
out.println(i+1);
if(c[i]=='r'){
Q.addFirst(i+1);
}
}
// root.traverse();
out.close();
}
private static void traverse(int i, char[] c) {
}
static class Node{
int index,dir;
Node child;
Node(int a){
index = a;
child = null;
dir = 0;
}
public void traverse() {
if(dir==-1)
child.traverse();
if(index!=N+1)
out.println(index);
if(dir==1)
child.traverse();
}
}
static class MScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public MScanner() {
stream = System.in;
// stream = new FileInputStream(new File("dec.in"));
}
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++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextInt(int N) {
int[] ret = new int[N];
for (int a = 0; a < N; a++)
ret[a] = nextInt();
return ret;
}
int[][] nextInt(int N, int M) {
int[][] ret = new int[N][M];
for (int a = 0; a < N; a++)
ret[a] = nextInt(M);
return ret;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLong(int N) {
long[] ret = new long[N];
for (int a = 0; a < N; a++)
ret[a] = nextLong();
return ret;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDouble(int N) {
double[] ret = new double[N];
for (int a = 0; a < N; a++)
ret[a] = nextDouble();
return ret;
}
String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
String[] next(int N) {
String[] ret = new String[N];
for (int a = 0; a < N; a++)
ret[a] = next();
return ret;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
String[] nextLine(int N) {
String[] ret = new String[N];
for (int a = 0; a < N; a++)
ret[a] = nextLine();
return ret;
}
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 11f1bfe08daa73fab3822abfca10a0c1 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Ardi{
public static long mod = 1000000007;
public static void main(String args[]) throws IOException{
BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
String tmp = lector.readLine();
int res[] = new int[tmp.length()];
int pun = 0,pun2 =res.length-1;
for(int n = 0;n<res.length;n++)
if(tmp.charAt(n)=='l')res[pun2--]=n+1;
else res[pun++]=n+1;
StringBuilder ress=new StringBuilder("");
for(int n = 0;n<res.length;n++)ress.append(res[n]+"\n");
System.out.println(ress.substring(0,ress.length()-1));
}
}
class p implements Comparable{
public int a;
public p(int a){
this.a = a;
}
public String toString(){
return "";
}
public int compareTo(Object o){
p pp = (p)o;
return (int)Math.signum(a-pp.a);
}
} | Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | fdda2f92cf17163ca193b27b21258fdd | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.util.*;
import java.io.*;
public class EscapeFromStones
{
public static void main(String[] args) throws IOException
{
FastScanner in = new FastScanner();
BufferedWriter out = new BufferedWriter(new PrintWriter(System.out));
String s = in.next();
ArrayList<Integer> left = new ArrayList<Integer>();
for(int x = 0; x < s.length(); x++)
{
if(s.charAt(x) == 'r')
{
out.write("" + (x + 1));
out.newLine();
}
else
{
left.add(x + 1);
}
}
for(int z = left.size() - 1; z >= 0; z--)
{
out.write("" + left.get(z));
out.newLine();
}
out.close();
}
}
class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
public FastScanner(File f) throws IOException
{
br = new BufferedReader(new FileReader(f));
st = new StringTokenizer("");
}
public String next() throws IOException
{
if(st.hasMoreTokens())
{
return st.nextToken();
}
else
{
st = new StringTokenizer(br.readLine());
return next();
}
}
public int nextInt() throws IOException
{
if(st.hasMoreTokens())
{
return Integer.parseInt(st.nextToken());
}
else
{
st = new StringTokenizer(br.readLine());
return nextInt();
}
}
} | Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 7ae4a81eceaa88c7de0a1f72940db084 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class A264 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char escapes[] = in.next().toCharArray();
int length = escapes.length;
int[] stones = new int[length];
int left = 0;
int right = length - 1;
for (int i = 0; i < length; ++i) {
if (escapes[i] == 'l') {
stones[right--] = i + 1;
} else {
stones[left++] = i + 1;
}
}
PrintWriter writer = new PrintWriter(System.out);
for (int j : stones) {
writer.println(j);
}
writer.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 05659efdad2a2678e976790a9525041c | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.util.List;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.io.BufferedWriter;
import java.util.Locale;
import java.util.ListIterator;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.LinkedList;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Jacob Jiang
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
char[] s = in.nextCharArray();
List<Integer> list = new LinkedList<Integer>();
int cur = 0;
ListIterator<Integer> iterator = list.listIterator();
for (char c : s) {
if (c == 'l') {
iterator.add(++cur);
iterator.previous();
} else {
iterator.add(++cur);
}
}
for (Integer item : list) {
out.println(item);
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char[] nextCharArray() {
return next().toCharArray();
}
}
class OutputWriter {
private PrintWriter writer;
public OutputWriter(OutputStream stream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(Object x) {
writer.println(x);
}
public void close() {
writer.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 8f7898a4cf8374eabeb2badfc2212204 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.*;
public class EscapeFromStones {
public static void main(String[] args) throws IOException {
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
String s = buff.readLine();
buff.close();
int[] arr = new int[s.length()];
int left = 0, right = s.length()-1;
for (int i=0;i<s.length();i++){
if (s.charAt(i) == 'l'){
arr[right] = i+1;
right--;
}
else {
arr[left] = i+1;
left++;
}
}
for (int i=0;i<arr.length;i++)
out.println(arr[i]);
out.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 87d0cbdf9f30fa1055e4690aaba80bd1 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.*;
import java.util.*;
public class A264
{
public static void main(String[] args)
{
int i, f, l;
String S = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
try {
S = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int[] X = new int[S.length()];
f=0;
l=S.length()-1;
for(i=0; i<S.length(); i++)
{
if(S.charAt(i) == 'r')
{
X[f] = i+1;
f++;
}
else if(S.charAt(i) == 'l')
{
X[l] = i+1;
l--;
}
}
for(i=0; i<S.length(); i++)
out.println(X[i]);
out.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 7a8696c10b2a2628bee1e9da8f9ffcd4 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.util.*;
import java.io.*;
public class A264
{
public static void main(String[] args) throws IOException {
BufferedReader input =new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
String s = input.readLine();
String h="";
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='r')
out.println(i+1);
}
for(int i=s.length()-1;i>=0;i--)
{
if(s.charAt(i)!='r')
out.println(i+1);
}
out.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 7b8547753678f0506c09c0781587f324 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class EFS {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
String x = in.readLine();
int [] z = new int [x.length()];
int l =0;
for(int i =0;i<x.length();i++){
if(x.charAt(i)=='r')
out.println(i+1);
if(x.charAt(i)=='l'){
z[l]=i+1;
l++;
}
}
for(int i =l-1;i>=0;i--){
out.println(z[i]);
}
out.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | f1b7870ce8c7b955808da0c8c9140a0f | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class EscapeFromStonessssssss {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
String s = in.readLine();
int[] a = new int[s.length()];
int tracer = 0 ;
for (int i = 0; i < a.length; i++) {
if(s.charAt(i)=='r'){
out.println(i+1);
}
else{
a[tracer]=i+1;
tracer++;
}
}
for (int i = tracer-1; i >-1; i--) {
out.println(a[i]);
}
out.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 2ce33895db8e5fd8047aa84589ddbf76 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
*
* @author utp
*/
public class CodeO
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
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 int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextDouble();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public String[] nextStringArray(int n)
{
String[] vals = new String[n];
for(int i = 0; i < n; i++)
vals[i] = next();
return vals;
}
Integer nextInteger()
{
String s = next();
if(s == null)
return null;
return Integer.parseInt(s);
}
int[][] nextIntMatrix(int n, int m)
{
int[][] ans = new int[n][];
for(int i = 0; i < n; i++)
ans[i] = nextIntArray(m);
return ans;
}
static <T> T fill(T arreglo, int val)
{
if(arreglo instanceof Object[])
{
Object[] a = (Object[]) arreglo;
for(Object x : a)
fill(x, val);
}
else if(arreglo instanceof int[])
Arrays.fill((int[]) arreglo, val);
else if(arreglo instanceof double[])
Arrays.fill((double[]) arreglo, val);
else if(arreglo instanceof long[])
Arrays.fill((long[]) arreglo, val);
return arreglo;
}
<T> T[] nextObjectArray(Class <T> clazz, int size)
{
@SuppressWarnings("unchecked")
T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size);
try
{
Constructor <T> constructor = clazz.getConstructor(Scanner.class, Integer.TYPE);
for(int i = 0; i < result.length; i++)
result[i] = constructor.newInstance(this, i);
return result;
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
}
static class Nodo
{
Nodo siguiente;
int numero;
Nodo(int n, Nodo s)
{
numero = n;
siguiente = s;
}
}
static class ListaEnlacada
{
Nodo cabeza = new Nodo(0, null);
Nodo current;
ListaEnlacada()
{
current = cabeza;
}
void agregarDerecha(int n)
{
current.siguiente = new Nodo(n, current.siguiente);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
ListaEnlacada lista = new ListaEnlacada();
int i = 1;
for(char c : sc.next().toCharArray())
{
lista.agregarDerecha(i++);
if(c != 'l')
lista.current = lista.current.siguiente;
}
StringBuilder sb = new StringBuilder();
for(Nodo actual = lista.cabeza.siguiente; actual != null; actual = actual.siguiente)
{
sb.append(actual.numero);
sb.append('\n');
}
System.out.print(sb.toString());
System.out.flush();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 0e2aca4d1d9bb1dbf624279a5397a1f2 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
public class Prob264A {
public static void main(String[] Args) {
Scanner scan = new Scanner(System.in);
LinkedList<Integer> ll = new LinkedList<Integer>();
char[] arr = scan.next().toCharArray();
for (int i = arr.length; i > 0; i--)
if (arr[i - 1] == 'l')
ll.addLast(i);
else
ll.addFirst(i);
Iterator<Integer> iter = ll.iterator();
StringBuffer sb = new StringBuffer();
while (iter.hasNext())
sb.append("" + iter.next() + '\n');
System.out.println(sb);
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 593c65b6ae9b4c6ffac71dbdd1f3a5b9 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
public class hals {
static class node{
int val;
node left,right;
public node(int val){
this.val=val;
left=null;
right=null;
}
}
static void traverse(node h){
Stack<node> s = new Stack<node>();
StringBuilder st = new StringBuilder();
while(true){
while(h!=null){
s.push(h);
h=h.left;
}
if(s.isEmpty())break;
st.append(s.peek().val+"\n");
h = s.pop().right;
}
System.out.println(st);
}
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
node header = new node(1);
node now = header;
int curr = 1;
for(int i=0;i<s.length()-1;i++){
if(s.charAt(i)=='l'){
now.left = new node(++curr);
now = now.left;
}
else{
now.right = new node(++curr);
now = now.right;
}
}
traverse(header);
}
} | Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | bb48b0b1e3e89bddb515f3e00fbc349a | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
String s = in.next();
int n = s.length();
int[] answer = new int[n];
int left = 0;
int right = n;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == 'r') {
answer[left++] = i + 1;
} else {
answer[--right] = i + 1;
}
}
for (int i : answer) {
out.println(i);
}
}
}
class FastScanner extends BufferedReader {
boolean isEOF;
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
if (isEOF && ret < 0) {
throw new InputMismatchException();
}
isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
while (!isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= -1 && c <= 32;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | b0030cd4dfb4d364b41e4d3efad6b20c | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.*;
public class _264A_Escape_from_Stones {
public static void main(String[] args) throws Exception {
String s = new BufferedReader(new InputStreamReader(System.in))
.readLine();
int i = 0, j = s.length(), k = 0, Q[] = new int[j];
while (i < j)
if ('l' != s.charAt(k++))
Q[i++] = k;
else
Q[--j] = k;
PrintWriter o=new PrintWriter(System.out);
for (int e : Q)
o.println(e);
o.close();
}
} | Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | cf7ba78f8454d15adab3684853dabeb9 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes |
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class Main {
static class DList<V> {
DNode<V> head;
DNode<V> current;
static class DNode<V> {
V value;
DNode<V> prev;
DNode<V> next;
public String toString()
{
return (prev != null? String.valueOf(prev.value) : "/") + value + (next != null? String.valueOf(next.value) : "/");
}
}
void prepand(V value)
{
DNode<V> newNod = new DNode<V>();
newNod.value = value;
newNod.next = current;
if(current != null)
{
newNod.prev = current.prev;
current.prev = newNod;
}
if(newNod.prev == null)
{
head = newNod;
}
else
{
newNod.prev.next = newNod;
}
current = newNod;
}
void appand(V value)
{
DNode<V> newNod = new DNode<V>();
newNod.value = value;
newNod.prev = current;
if(current != null)
{
if(current.next != null)
current.next.prev = newNod;
newNod.next = current.next;
current.next = newNod;
}
else
{
head = newNod;
}
current = newNod;
}
}
public static void solve(FastScanner fscan, BufferedWriter bw) throws IOException {
double l = 0;
double r = 100000000;
double mid = (l + r) / 2.0;
DList<Integer> list = new DList<Integer>();
list.appand(1);
String s = fscan.nextString();
for (int i = 1; i < s.length(); i++) {
if(s.charAt(i-1) == 'l')
{
r = mid;
list.prepand(i+1);
}
else
{
l = mid;
list.appand(i+1);
}
mid = (l + r) / mid;
}
DList.DNode<Integer> d = list.head;
while(d != null )
{
bw.append(String.valueOf(d.value) + "\n");
d = d.next;
}
}
/**************** ENTER HERE ********************/
public static void main(String[] args) throws Exception {
if(args.length != 0){
test();
return;
}
FastScanner fscan = new FastScanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
solve(fscan,bw);
bw.close();
}
/**** Test Static test cases **/
public static void test() throws IOException{
String testcase[] = new String[]{};
String answer[] = new String[]{};
for (int i = 0; i < testcase.length; i++) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
FastScanner fscan = new FastScanner(new ByteArrayInputStream(testcase[i].getBytes()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(result));
solve(fscan, bw);
String r = new String(result.toByteArray());
if(! r.equals(answer[i])){
String q = testcase[i];
String a = answer[i];
System.err.println("Wrong Answer on test:"+(i+1));
System.err.println("Q:"+q);
System.err.println("A:"+a);
System.err.println("R:"+r);
}
}
}
}
class FastScanner {
InputStream is;
byte buff[] = new byte[1024];
int currentChar = -1;
int buffChars = 0;
public FastScanner(InputStream inputStream) {
is = inputStream;
}
public boolean hasNext() throws IOException {
return currentChar == -1 || buffChars > 0;
}
public char nextChar() throws IOException {
// if we already have that next char read, just return else input
if (currentChar == -1 || currentChar >= buffChars) {
currentChar = 0;
buffChars = is.read(buff);
}
if (buffChars <= 0) {
throw new RuntimeException("No char found...");
}
int ch;
while (isSpace(ch = nextCharAsInt()))
;
return (char) ch;
}
public int nextCharAsInt() throws IOException {
// if we already have that next char read, just return else input
if (currentChar == -1 || currentChar >= buffChars) {
currentChar = 0;
buffChars = is.read(buff);
}
if (buffChars <= 0) {
return -1;
}
return (char) buff[currentChar++];
}
public String nextLine() throws IOException {
StringBuilder bldr = new StringBuilder();
int ch;
while (isLineEnd(ch = nextCharAsInt()))
// ignore empty lines ???
;
do {
bldr.append((char) ch);
} while (!isLineEnd(ch = nextCharAsInt()));
return bldr.toString();
}
public String nextString() throws IOException {
StringBuilder bldr = new StringBuilder();
int ch;
while (isSpace(ch = nextCharAsInt()))
;
do {
bldr.append((char) ch);
} while (!isSpace(ch = nextCharAsInt()));
return bldr.toString();
}
public int nextInt() throws IOException {
// considering ASCII files--> 8 bit chars, unicode files has 16 bit
// chars (byte1 then byte2)
int result = 0;
int sign = 1;
int ch;
while (isSpace(ch = nextCharAsInt()))
;
if (ch == '-') {
sign = -1;
ch = nextCharAsInt();
}
do {
if (ch < '0' || ch > '9')
throw new NumberFormatException("Found '" + ch
+ "' while parsing for int.");
result *= 10;
result += ch - '0';
} while (!isSpace(ch = nextCharAsInt()));
return sign * result;
}
public long nextLong() throws IOException {
// considering ASCII files--> 8 bit chars, unicode files has 16 bit
// chars (byte1 then byte2)
long result = 0;
int sign = 1;
int ch;
while (isSpace(ch = nextCharAsInt()))
;
if (ch == '-') {
sign = -1;
ch = nextCharAsInt();
}
do {
if (ch < '0' || ch > '9')
throw new NumberFormatException("Found '" + ch
+ "' while parsing for int.");
result *= 10;
result += ch - '0';
} while (!isSpace(ch = nextCharAsInt()));
return sign * result;
}
private boolean isLineEnd(int ch) {
return ch == '\n' || ch == '\r' || ch == -1;
}
private boolean isSpace(int ch) {
return ch == '\n' || ch == ' ' || ch == '\t' || ch == '\r' || ch == -1;
}
public void close() throws IOException {
is.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 324bd8104f1335b5510aa47a6f7e9a96 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
FastScanner in;
PrintWriter out;
final String fileName = "A".toLowerCase();
void solve() {
String s = in.next();
Deque<Integer> d = new ArrayDeque<>();
int n = s.length();
d.add(n);
for (int i = s.length() - 2; i >= 0; i--) {
if (s.charAt(i) == 'l') {
d.addLast(i + 1);
} else {
d.addFirst(i + 1);
}
}
for (int i : d) {
out.println(i);
}
}
void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
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(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new A().run();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 7c1e259877523e2f5895463dc2b98ee4 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | //package TestOnly.Div1A_162.Code1;
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 solve() throws IOException
{
String input = in.next();
int size = input.length();
int left[] = new int[size];
int right[] = new int[size];
int leftIndex = 0;
int rightIndex = 0;
for (int i = 0; i < input.length(); i++)
{
char ch = input.charAt(i);
if (ch == 'l')
{
left[leftIndex++] = i + 1;
} else
{
right[rightIndex++] = i + 1;
}
}
for (int i = 0; i < rightIndex; i++)
{
out.println(right[i]);
}
for (int i = leftIndex - 1; i >= 0; i--)
{
out.println(left[i]);
}
}
public void run()
{
try
{
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
class FastScanner
{
BufferedReader br;
StringTokenizer st;
FastScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreTokens())
{
try
{
st = new StringTokenizer(br.readLine());
} catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
}
public static void main(String[] arg)
{
new Main().run();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 861243218c868b02b21df002319c5a36 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class A implements Runnable {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
static Random rnd;
void solve() throws IOException {
String s = nextToken();
int n = s.length(), l = 0, r = n - 1;
int[] ans = new int[n];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == 'r') {
ans[l++] = i;
} else {
ans[r--] = i;
}
}
for (int i = 0; i < n; i++) {
out.println(ans[i] + 1);
}
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
final String className = this.getClass().getName().toLowerCase();
try {
in = new BufferedReader(new FileReader(className + ".in"));
out = new PrintWriter(new FileWriter(className + ".out"));
// in = new BufferedReader(new FileReader("input.txt"));
// out = new PrintWriter(new FileWriter("output.txt"));
} catch (FileNotFoundException e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
rnd = new Random();
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(42);
}
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | fd6279f56eb66a9c6aa2543331de9de0 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class EscapeFromStones {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
String s = f.readLine();
int[] a = new int[s.length()];
int[] b = new int[s.length()];
int i1 = 0;
int i2 = 0;
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == 'r')
a[i1++] = i+1;
else
b[i2++] = i+1;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < i1; i++)
sb.append(a[i]+"\n");
for (int i = i2-1; i >= 0; i--)
sb.append(b[i]+"\n");
System.out.println(sb);
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 407def246617f3daefca1aa535399093 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String[] args) throws IOException
{
MyScanner in = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
String s = in.nextLine();
Node list1 = null;
Node list2 = null;
Node head = null;
for (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == 'l')
{
Node n = new Node();
n.data = i + 1;
n.next = null;
n.prev = list1;
list1 = n;
}
else if (s.charAt(i) == 'r')
{
Node n = new Node();
n.data = i + 1;
n.next = null;
n.prev = list2;
if (list2 == null)
head = n;
else
list2.next = n;
list2 = n;
}
}
while (head != null)
{
out.println(head.data);
head = head.next;
}
while (list1 != null)
{
out.println(list1.data);
list1 = list1.prev;
}
out.close();
}
}
class Node
{
int data;
Node next;
Node prev;
}
class MyScanner
{
/*
int n = sc.nextInt(); // read input as integer
long k = sc.nextLong(); // read input as long
double d = sc.nextDouble(); // read input as double
String str = sc.next(); // read input as String
String s = sc.nextLine(); // read whole line as String
*/
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 | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | a3ada6239e26b570bb3105610a07605c | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
static void solve() throws IOException {
String s = nextToken();
Deque<Integer> deque = new ArrayDeque<>();
for (int i = s.length() - 1; i >= 0; --i) {
if (s.charAt(i) == 'l') {
deque.addLast(i);
} else {
deque.addFirst(i);
}
}
for (int i : deque) {
out.println(i + 1);
}
}
static BufferedReader br;
static PrintWriter out;
static StringTokenizer st;
public static void main(String[] args) throws Exception {
if (new File("a.in").exists()) {
br = new BufferedReader(new FileReader("a.in"));
} else {
br = new BufferedReader(new InputStreamReader(System.in));
}
out = new PrintWriter(System.out);
solve();
out.close();
}
static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 4bdd74bdddb5b57b76fdcf018c52ca85 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | //package codeforces.contests.cf162;
import java.io.*;
public class ProblemA {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));
int[] readInts() throws IOException {
String[] strings = reader.readLine().split(" ");
int[] ints = new int[strings.length];
for(int i = 0; i < ints.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
return ints;
}
long[] readLongs() throws IOException {
String[] strings = reader.readLine().split(" ");
long[] longs = new long[strings.length];
for(int i = 0; i < longs.length; i++) {
longs[i] = Long.parseLong(strings[i]);
}
return longs;
}
void solve() throws IOException {
String s = reader.readLine();
int[] a = new int[s.length()];
int n = 0;
for(int i = 1; i <= s.length(); i++) {
if(s.charAt(i - 1) == 'r') {
writer.println(i);
}
else {
a[n++] = i;
}
}
for(int i = n - 1; i >= 0; i--) {
writer.println(a[i]);
}
writer.flush();
}
public static void main(String[] args) throws IOException {
new ProblemA().solve();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 2d38887af58bb9eb3c0c9e84e82f8fa3 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
public class palin {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String str = scan.next();
int loc[] = new int[str.length()], l = 0, r = str.length() - 1;
if (str.charAt(0) == 'r') {
loc[l] = 1;
l++;
} else {
loc[r] = 1;
r--;
}
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) != str.charAt(i)) {
if (str.charAt(i - 1) == 'r') {
loc[r] = i + 1;
r--;
} else {
loc[l] = i + 1;
l++;
}
} else {
if (str.charAt(i - 1) == 'r') {
loc[l] = i + 1;
l++;
} else {
loc[r] = i + 1;
r--;
}
}
}
for (int i = 0; i < loc.length; i++) {
out.println(loc[i]);
}
out.flush();
}
} | Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 837a75e1853e2705515604f8f4bc5daa | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
public class palin {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
PrintWriter cout = new PrintWriter(System.out);
char[] c = scan.next().toCharArray();
int r = c.length - 1, l = 0;
int[] a = new int[c.length];
for (int i = 0; i < c.length; i++) {
if (c[i] == 'l') {
a[r] = i + 1;
r--;
} else {
cout.println(i + 1);
}
}
for (int i = r + 1; i < a.length; i++) {
cout.println(a[i]);
}
cout.flush();
}
} | Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 17b3b0d2a453e65c69938ce9569a675f | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import static java.lang.Math.*;
import java.io.*;
import java.util.*;
import java.math.*;
public class Main{
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String next() {
while (st==null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (Exception e) {}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
class ListNode{
int value;
ListNode prev, next;
public ListNode(int value){
this.value = value;
}
ListNode append(ListNode node){
if(this.next == null) this.next = node;
else {
ListNode temp = this.next;
this.next = node;
node.next = temp;
temp.prev = node;
}
node.prev = this;
return node;
}
ListNode prepend(ListNode node){
if(this.prev == null) this.prev = node;
else {
ListNode temp = this.prev;
this.prev = node;
node.prev = temp;
temp.next = node;
}
node.next = this;
return node;
}
}
public void run()throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
String s = next();
ListNode node = null;
for(int i = 0; i < s.length(); ++i){
if(node == null){
node = new ListNode(i + 1);
}
else{
ListNode ln = new ListNode(i + 1);
if(s.charAt(i - 1) == 'l') node = node.prepend(ln);
else node = node.append(ln);
}
}
ListNode head = node;
while(head.prev != null) head = head.prev;
while(head != null){
out.println(head.value);
head = head.next;
}
out.close();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
} | Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 6a6178df40ca46130647a3178fc97181 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes |
import java.util.*;
import java.io.*;
public class escape{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
int n = s.length();
int[] a = new int[n];
int x=0, y = n-1;
for(int i=0; i<n; i++){
if(s.charAt(i) == 'l')
a[y--] = i+1;
else
a[x++] = i+1;
}
PrintWriter out = new PrintWriter(System.out);
for(int j : a)
out.println(j);
out.close();
}
} | Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | 97699b316cf1bf7b15b5caa6e059c7f8 | train_004.jsonl | 1358686800 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,β1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [kβ-βd,βkβ+βd] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [kβ-βd,βk]. If she escapes to the right, her new interval will be [k,βkβ+βd].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class escape{
public static void main(String[] args) throws IOException{
BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));
String s=cin.readLine();
int n = s.length();
int[] a = new int[n];
int x=0, y = n-1;
for(int i=0; i<n; i++){
if(s.charAt(i) == 'l')
a[y--] = i+1;
else
a[x++] = i+1;
}
PrintWriter cout=new PrintWriter(System.out);
for(int j : a)
cout.println(j);
cout.close();
}
}
| Java | ["llrlr", "rrlll", "lrlrr"] | 2 seconds | ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"] | NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1. | Java 7 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"two pointers"
] | 9d3c0f689ae1e6215448463def55df32 | The input consists of only one line. The only line contains the string s (1ββ€β|s|ββ€β106). Each character in s will be either "l" or "r". | 1,200 | Output n lines β on the i-th line you should print the i-th stone's number from the left. | standard output | |
PASSED | a1991aa53e30d6ec8aaa87086ed474e3 | train_004.jsonl | 1267117200 | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. | 64 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Winner {
static BufferedReader in;
static StringTokenizer st = new StringTokenizer("");
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int wheel = nextInt();
Map<String, Integer> map = new HashMap<>();
String[] name = new String[wheel];
int[] score = new int[wheel];
for (int i = 0; i < wheel; i++) {
name[i] = nextString();
score[i] = nextInt();
if (!map.containsKey(name[i])) {
map.put(name[i], score[i]);
} else {
map.put(name[i], map.get(name[i]) + score[i]);
}
}
int max = 0;
for (Integer x : map.values()) {
max = Math.max(max, x);
}
Set<String> winners = new HashSet<String>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() >= max) {
winners.add(entry.getKey());
}
}
map.clear();
String res = null;
for (int i = 0; i < wheel; i++) {
if (!map.containsKey(name[i])) {
map.put(name[i], score[i]);
} else {
map.put(name[i], map.get(name[i]) + score[i]);
}
if (map.get(name[i]) >= max && winners.contains(name[i])) {
res = name[i];
break;
}
}
out.println(res);
out.flush();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static String nextString() throws IOException {
return String.valueOf(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
} | Java | ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"] | 1 second | ["andrew", "andrew"] | null | Java 8 | standard input | [
"implementation",
"hashing"
] | c9e9b82185481951911db3af72fd04e7 | The first line contains an integer number n (1βββ€ββnβββ€ββ1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. | 1,500 | Print the name of the winner. | standard output | |
PASSED | a09e57f3096335e481a6fdee3c2eeba6 | train_004.jsonl | 1267117200 | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. | 64 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Winner {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out, true);
int wheel = Integer.parseInt(br.readLine());
Map<String, Integer> map = new Hashtable<String, Integer>();
int max = Integer.MIN_VALUE;
String[] names = new String[wheel];
int[] scores = new int[wheel];
String[] tokens;
for (int i = 0; i < wheel; i++) {
tokens = br.readLine().split(" ");
String name = tokens[0];
int score = Integer.parseInt(tokens[1]);
Integer lookUpScore = map.get(name);
if (lookUpScore != null) {
score += lookUpScore;
}
names[i] = name;
scores[i] = score;
map.put(name, score);
}
for (String key : map.keySet()) {
if (map.get(key) > max) {
max = map.get(key);
}
}
for (int i = 0; i < wheel; i++) {
if (scores[i] >= max && map.get(names[i]) == max) {
out.println(names[i]);
break;
}
}
}
} | Java | ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"] | 1 second | ["andrew", "andrew"] | null | Java 8 | standard input | [
"implementation",
"hashing"
] | c9e9b82185481951911db3af72fd04e7 | The first line contains an integer number n (1βββ€ββnβββ€ββ1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. | 1,500 | Print the name of the winner. | standard output | |
PASSED | 241ae27b64d89627cac62711e85dc2e4 | train_004.jsonl | 1267117200 | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. | 64 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Winner {
static BufferedReader in;
static StringTokenizer st = new StringTokenizer("");
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int wheel = nextInt();
Map<String, Integer> map = new HashMap<>();
String[] name = new String[wheel];
int[] score = new int[wheel];
for (int i = 0; i < wheel; i++) {
name[i] = nextString();
score[i] = nextInt();
if (!map.containsKey(name[i])) {
map.put(name[i], score[i]);
} else {
map.put(name[i], map.get(name[i]) + score[i]);
}
}
int max = 0;
for (Integer x : map.values()) {
max = Math.max(max, x);
}
Set<String> winners = new HashSet<String>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() >= max) {
winners.add(entry.getKey());
}
}
map.clear();
String res = null;
for (int i = 0; i < wheel; i++) {
if (!map.containsKey(name[i])) {
map.put(name[i], score[i]);
} else {
map.put(name[i], map.get(name[i]) + score[i]);
}
if (map.get(name[i]) >= max && winners.contains(name[i])) {
res = name[i];
break;
}
}
out.println(res);
out.flush();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static String nextString() throws IOException {
return String.valueOf(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
} | Java | ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"] | 1 second | ["andrew", "andrew"] | null | Java 8 | standard input | [
"implementation",
"hashing"
] | c9e9b82185481951911db3af72fd04e7 | The first line contains an integer number n (1βββ€ββnβββ€ββ1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. | 1,500 | Print the name of the winner. | standard output | |
PASSED | 00878b420ba19350c86d61d572fb53fc | train_004.jsonl | 1267117200 | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. | 64 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Winner {
static BufferedReader in;
static StringTokenizer st = new StringTokenizer("");
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int wheel = nextInt();
Map<String, Integer> map = new HashMap<>();
String[] name = new String[wheel];
int[] score = new int[wheel];
for (int i = 0; i < wheel; i++) {
name[i] = next();
score[i] = nextInt();
if (!map.containsKey(name[i])) {
map.put(name[i], score[i]);
} else {
map.put(name[i], map.get(name[i]) + score[i]);
}
}
int max = 0;
for (Integer x : map.values()) {
max = Math.max(max, x);
}
Set<String> winners = new HashSet<String>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() >= max) {
winners.add(entry.getKey());
}
}
map.clear();
String res = null;
for (int i = 0; i < wheel; i++) {
if (!map.containsKey(name[i])) {
map.put(name[i], score[i]);
} else {
map.put(name[i], map.get(name[i]) + score[i]);
}
if (map.get(name[i]) >= max && winners.contains(name[i])) {
res = name[i];
break;
}
}
out.println(res);
out.flush();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
} | Java | ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"] | 1 second | ["andrew", "andrew"] | null | Java 8 | standard input | [
"implementation",
"hashing"
] | c9e9b82185481951911db3af72fd04e7 | The first line contains an integer number n (1βββ€ββnβββ€ββ1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. | 1,500 | Print the name of the winner. | standard output | |
PASSED | acf3b79dd48fe682ba3d9fa59681dd66 | train_004.jsonl | 1267117200 | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. | 64 megabytes | //package CR0002;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class A {
private void solve() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt(), max = Integer.MIN_VALUE, score[] = new int[n];
;
String[] name = new String[n];
Map<String, Integer> total = new TreeMap<>(), curr = new TreeMap<>();
for (int i = 0; i < n; i++) {
name[i] = next();
score[i] = nextInt();
Integer x = total.get(name[i]);
if (x == null) x = 0;
x += score[i];
total.put(name[i], x);
}
for (int i = 0; i < n; i++) {
int x = total.get(name[i]);
if (max < x) max = x;
}
for (int i = 0; i < n; i++) {
Integer x = curr.get(name[i]);
if (x == null) x = 0;
x += score[i];
if (x >= max && total.get(name[i]).compareTo(max) == 0) {
out.println(name[i]);
break;
}
curr.put(name[i], x);
}
out.close();
}
public static void main(String[] args) {
new A().solve();
}
private BufferedReader br;
private StringTokenizer st;
private PrintWriter out;
private String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
private Integer nextInt() {
return Integer.parseInt(next());
}
private Long nextLong() {
return Long.parseLong(next());
}
private Double nextDouble() {
return Double.parseDouble(next());
}
}
| Java | ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"] | 1 second | ["andrew", "andrew"] | null | Java 8 | standard input | [
"implementation",
"hashing"
] | c9e9b82185481951911db3af72fd04e7 | The first line contains an integer number n (1βββ€ββnβββ€ββ1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. | 1,500 | Print the name of the winner. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.