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 | 60ef2bd04f8f7e83b271c465c8db65be | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static InputReader scn = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public static void main(String[] args) {
int t = scn.nextInt();
while (t-- > 0)
solve();
out.close();
}
public static void solve() {
int n = scn.nextInt();
int q = scn.nextInt();
int[] arr = scn.readArrays(n);
if (n == 1) {
out.println(arr[0]);
return;
}
long ans = 0;
ArrayList<Integer> list = new ArrayList<>();
int val = 1;
for (int i = 0; i < n - 1; i++) {
if (val == 1) {
if (arr[i] >= arr[i + 1]) {
list.add(arr[i]);
val = 0;
}
} else {
if (arr[i] <= arr[i + 1]) {
list.add(arr[i]);
val = 1;
}
}
if (i == n - 2) {
if (val == 1) {
if (arr[i] <= arr[i + 1]) {
list.add(arr[i + 1]);
val = 0;
}
}
}
}
int l = list.size();
for (int i = 0; i < l; i++) {
if (i % 2 == 0) {
ans += list.get(i);
} else {
if (i != l - 1)
ans -= list.get(i);
}
}
// out.println(list);
out.println(ans);
}
public static int firstOccurence1(int array1[], int low, int high, int x, int n) {
if (low <= high) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > array1[mid - 1]) && array1[mid] == x)
return mid;
else if (x > array1[mid])
return firstOccurence(array1, (mid + 1), high, x, n);
else
return firstOccurence(array1, low, (mid - 1), x, n);
}
return -1;
}
public static int qSort(int arr[]) {
int n = arr.length;
int cnt = 0;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/*
* Move elements of arr[0..i-1], that are greater than key, to one position
* ahead of their current position
*/
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
cnt += j - i + 1;
arr[j + 1] = key;
}
return Math.abs(cnt);
}
public static HashMap<Integer, Integer> CountFrequencies(int[] arr) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
int a = arr[i];
if (map.containsKey(a)) {
map.put(a, map.get(a) + 1);
} else {
map.put(a, 1);
}
}
return map;
}
public static int countPrimeFactors(int n) {
int count = 0;
while (n % 2 == 0) {
n = n / 2;
count++;
}
for (int i = 3; i <= Math.sqrt(n); i = i + 2) {
while (n % i == 0) {
n = n / i;
count++;
}
}
if (n > 2)
count++;
return (count);
}
public static int max(int a, int b) {
if (a >= b)
return a;
return b;
}
public static int min(int a, int b) {
if (a <= b)
return a;
return b;
}
public static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static boolean isPrime(long n) {
if (n < 2)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
long sqrtN = (long) Math.sqrt(n) + 1;
for (long i = 6L; i <= sqrtN; i += 6) {
if (n % (i - 1) == 0 || n % (i) + 1 == 0)
return false;
}
return true;
}
public static int[] SieveOfEratosthenes(int[] arr) {
int n = arr.length;
for (long i = 3; i < n; i = i + 2) {
arr[(int) i] = 1;
}
for (long i = 3; i < n; i = i + 2) {
if (arr[(int) i] == 1) {
for (long j = (long) i * i; j < n; j = j + i) {
arr[(int) j] = 0;
}
}
}
arr[2] = 1;
arr[0] = arr[1] = 0;
return arr;
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
public static ArrayList<String> printPermutn(String str, String ans, ArrayList<String> list) {
if (str.length() == 0) {
list.add(ans);
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
String ros = str.substring(0, i) + str.substring(i + 1);
printPermutn(ros, ans + ch, list);
}
return list;
}
public static int binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
public static int firstOccurence(int array1[], int low, int high, int x, int n) {
if (low <= high) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > array1[mid - 1]) && array1[mid] == x)
return mid;
else if (x > array1[mid])
return firstOccurence(array1, (mid + 1), high, x, n);
else
return firstOccurence(array1, low, (mid - 1), x, n);
}
return -1;
}
public static int lastOccurence(int array2[], int low, int high, int x, int n) {
if (low <= high) {
int mid = low + (high - low) / 2;
if ((mid == n - 1 || x < array2[mid + 1]) && array2[mid] == x)
return mid;
else if (x < array2[mid])
return lastOccurence(array2, low, (mid - 1), x, n);
else
return lastOccurence(array2, (mid + 1), high, x, n);
}
return -1;
}
static final Random random = new Random();
static void ruffleSort(int[] a) {
int n = a.length;// shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int[] readArrays(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
}
return arr;
}
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 long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return nextLine();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
// writer.print(1);
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | ad3f4ccb076e77902563f2f6544ff014 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class zizo {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-- > 0) {
int n = sc.nextInt(), q = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++)
arr[i] = sc.nextInt();
int prev = 0, idx = 0;
long ans = 0l;
while(true) {
int max = findMax(idx, arr);
if(idx == arr.length) {
ans+=arr[prev];
break;
}
else {
ans+=arr[max];
idx = max + 1;
// System.out.println("max " + arr[max] + " idx " + idx);
}
int min = findMin(idx, arr);
if(idx == arr.length)
break;
else {
ans-=arr[min];
idx = min + 1;
prev = min;
// System.out.println("min " + arr[min] + " idx " + idx);
}
}
System.out.println(ans);
}
out.flush();
out.close();
}
public static int findMax(int s, int[] arr) {
for(int i = s; i < arr.length - 1; i++)
if(arr[i] > arr[i + 1])
return i;
return arr.length - 1;
}
public static int findMin(int s, int[] arr) {
for(int i = s; i < arr.length - 1; i++)
if(arr[i] < arr[i + 1])
return i;
return arr.length - 1;
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException{return Double.parseDouble(next());}
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 2c47490637ac00cb8b9532c987d28c64 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.Scanner;
public class T9 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int t=s.nextInt();
for(int k=0;k<t;k++) {
int n=s.nextInt();
int q=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
}
long ans=a[0];
for(int i=1;i<n;i++) {
ans=ans+Math.max(0,(a[i]-a[i-1]));
}
System.out.println(ans);
}
}
}
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | bad6faadcde81b1310cd84b237130b4b | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.Scanner;
import java.util.Stack;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int t = sc.nextInt();
for (int zz = 0; zz < t; zz++) {
int len = sc.nextInt();
int q = sc.nextInt();
Stack<Integer>stack = new Stack<>();
long sum = 0;
for (int i = 0;i < len;i++){
int ai = sc.nextInt();
if(stack.size() == 0){
stack.add(ai);
sum += ai;
continue;
}
if(stack.size() % 2 == 0){
if(ai < stack.peek()){
sum += stack.pop();
sum -= ai;
stack.add(ai);
}else{
sum += ai;
stack.add(ai);
}
}else{
if(ai > stack.peek()){
sum += ai;
sum -= stack.pop();
stack.add(ai);
}else{
sum -=ai;
stack.add(ai);
}
}
}
if(stack.size() % 2 == 0){
sum += stack.peek();
}
System.out.println(sum);
}
}
private static int[]readArr(int n){
int[]ans = new int[n];
for(int i = 0;i < n;i++){
ans[i] = sc.nextInt();
}
return ans;
}
}
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | d7fdfc0699b09578412e88c4ac17ca7d | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes |
// Problem: C1. Pokémon Army (easy version)
// Contest: Codeforces - Codeforces Round #672 (Div. 2)
// URL: http://codeforces.com/contest/1420/problem/C1
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)
import java.io.*;
import java.util.*;
public class Main {
private static PrintWriter pw = new PrintWriter(System.out);
private static InputReader sc = new InputReader();
private static final int intmax = Integer.MAX_VALUE, intmin = Integer.MIN_VALUE;
static class Pair{
int first, second;
Pair(int first, int second){
this.first = first;
this.second = second;
}
}
static class InputReader{
private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer tk;
private void next()throws IOException{
while(tk == null || !tk.hasMoreTokens())
tk = new StringTokenizer(r.readLine());
}
private int nextInt()throws IOException{
next();
return Integer.parseInt(tk.nextToken());
}
private long nextLong()throws IOException{
next();
return Long.parseLong(tk.nextToken());
}
private String readString()throws IOException{
next();
return tk.nextToken();
}
private double nextDouble()throws IOException{
next();
return Double.parseDouble(tk.nextToken());
}
private int[] intArray(int n)throws IOException{
next();
int arr[] = new int[n];
for(int i=0; i<n; i++)
arr[i] = nextInt();
return arr;
}
private long[] longArray(int n)throws IOException{
next();
long arr[] = new long[n];
for(int i=0; i<n; i++)
arr[i] = nextLong();
return arr;
}
}
public static void main(String args[])throws IOException{
int t = sc.nextInt();
while(t-->0) solve();
pw.flush();
pw.close();
}
private static int get(int arr[], int index){
if(index < 0 || index >= arr.length)
return 0;
return arr[index];
}
private static void solve()throws IOException{
int n = sc.nextInt(), q = sc.nextInt(), a[] = sc.intArray(n), i = 0;
long ans = n, sum = 0;
while(i + 1< n && a[i + 1] > a[i])
i++;
while(i < n){
if(get(a, i-1) < get(a, i) && get(a, i) > get(a, i + 1))
sum += a[i];
else if(get(a, i-1) > get(a, i) && get(a, i) < get(a, i + 1))
sum -= a[i];
i++;
ans = Math.max(ans, sum);
}
pw.println(+ans);
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 59ef9f6b61620eddd89e925a5aa3b9c2 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes |
// Problem: C1. Pokémon Army (easy version)
// Contest: Codeforces - Codeforces Round #672 (Div. 2)
// URL: http://codeforces.com/contest/1420/problem/C1
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)
import java.io.*;
import java.util.*;
public class Main {
private static PrintWriter pw = new PrintWriter(System.out);
private static InputReader sc = new InputReader();
private static final int intmax = Integer.MAX_VALUE, intmin = Integer.MIN_VALUE;
static class Pair{
int first, second;
Pair(int first, int second){
this.first = first;
this.second = second;
}
}
static class InputReader{
private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer tk;
private void next()throws IOException{
while(tk == null || !tk.hasMoreTokens())
tk = new StringTokenizer(r.readLine());
}
private int nextInt()throws IOException{
next();
return Integer.parseInt(tk.nextToken());
}
private long nextLong()throws IOException{
next();
return Long.parseLong(tk.nextToken());
}
private String readString()throws IOException{
next();
return tk.nextToken();
}
private double nextDouble()throws IOException{
next();
return Double.parseDouble(tk.nextToken());
}
private int[] intArray(int n)throws IOException{
next();
int arr[] = new int[n];
for(int i=0; i<n; i++)
arr[i] = nextInt();
return arr;
}
private long[] longArray(int n)throws IOException{
next();
long arr[] = new long[n];
for(int i=0; i<n; i++)
arr[i] = nextLong();
return arr;
}
}
public static void main(String args[])throws IOException{
int t = sc.nextInt();
while(t-->0) solve();
pw.flush();
pw.close();
}
private static void solve()throws IOException{
int n = sc.nextInt(), q = sc.nextInt(), a[] = sc.intArray(n);
long ans = 0;
for(int i = 0; i < n; i++){
if(i > 0 && i + 1 < n && a[i - 1] > a[i] && a[i] < a[i +1])
ans -= a[i];
else{
int prev = (i == 0)?0:a[i - 1], next = (i == n - 1)?0:a[i + 1];
if(prev < a[i] && a[i] > next)
ans += a[i];
}
}
pw.println(+ans);
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 7ee480f0f47e6d84fdb410f9671854bc | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn=new Scanner(System.in);
int t=scn.nextInt();
while(t-->0){
int n=scn.nextInt();
int q =scn.nextInt();
int []arr =new int[n];
for(int i=0;i<n;i++){
arr[i]=scn.nextInt();
}
if(n==1){
System.out.println(arr[0]);
continue;
}
long ans=0;
long max =0;
boolean f=false;
for(int i=0;i<n;i++){
if(i+1<arr.length && i>0){
if(arr[i]>arr[i-1] && arr[i]>arr[i+1]){
ans+=arr[i];
// System.out.println(ans+"Sa"+i+"dadjs"+arr[i]);
f=true;
}
if(arr[i]<arr[i-1] && arr[i]<arr[i+1] && f){
ans-=arr[i];
}
// max=Math.max(max, ans);
}else{
if(i>0){
if(arr[i-1]<arr[i]){
ans+=arr[i];
f =true;
}
if(arr[i-1]>arr[i] && f){
ans-=arr[i];
}
}else{
//System.out.println(i);
if(i+1<arr.length){
if(arr[i+1]<arr[i]){
ans+=arr[i];
f=true;
}
if(arr[i+1]>arr[i] && f){
ans-=arr[i];
}
}
}
}
max=Math.max(ans, max);
// System.out.println(ans+"ds"+i+"dsd"+max);
}
System.out.println(max);
}
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 42bc8d511693def3e52a289b533fe95c | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.*;
import java.io.*;
public class C_PokemonArmy_HardVersion {
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static final PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
private static StringTokenizer st;
private static int readInt() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());
}
public static void main(String[] args) throws IOException {
int T = readInt();
while (T-- > 0) {
solve();
}
pw.close();
}
private static void solve() throws IOException {
long res = 0;
int n = readInt();
int q = readInt();
long[] a = new long[n + 2];
a[0] = 0;
a[n + 1] = 0;
for (int i = 1; i <= n; i++) {
a[i] = readInt();
}
for (int i = 1; i <= n; i++) {
if (a[i] >= a[i - 1]) res += a[i] - a[i - 1];
}
pw.println(res);
for (int i = 0; i < q; i++) {
int l = readInt();
int r = readInt();
if (r == l + 1) {
if (a[l] - a[l - 1] > 0) res -= a[l] - a[l - 1];
if (a[l + 1] - a[l] > 0) res -= a[l + 1] - a[l];
if (a[l + 2] - a[l + 1] > 0) res -= a[l + 2] - a[l + 1];
if (a[l + 1] - a[l - 1] > 0) res += a[l + 1] - a[l - 1];
if (a[l] - a[l + 1] > 0) res += a[l] - a[l + 1];
if (a[l + 2] - a[l] > 0) res += a[l + 2] - a[l];
} else if ( r > l + 1){
if (a[l] - a[l - 1] > 0) res -= a[l] - a[l - 1];
if (a[l + 1] - a[l] > 0) res -= a[l + 1] - a[l];
if (a[r] - a[l - 1] > 0) res += a[r] - a[l - 1];
if (a[l + 1] - a[r] > 0) res += a[l + 1] - a[r];
if (a[r] - a[r - 1] > 0) res -= a[r] - a[r - 1];
if (a[r + 1] - a[r] > 0) res -= a[r + 1] - a[r];
if (a[l] - a[r - 1] > 0) res += a[l] - a[r - 1];
if (a[r + 1] - a[l] > 0) res += a[r + 1] - a[l];
}
long tmp = a[l];
a[l] = a[r];
a[r] = tmp;
pw.println(res);
}
}
}
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 139a152761ddddd175c235810160bb08 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
static long go(int i, long[][] dp, int pos, int[] arr) {
if(i == arr.length) {
return 0;
}
if(dp[i][pos] != -1) {
return dp[i][pos];
}
long skip = go(i + 1, dp, pos, arr);//skip
long take;
if(pos == 0) {
take = arr[i] + go(i + 1, dp, 1, arr);
} else {
take = go(i + 1, dp, 0, arr) - arr[i];
}
dp[i][pos] = Math.max(skip, take);
return dp[i][pos];
}
public static void main(String[] args) {
FastReader reader = new FastReader();
int tests = reader.nextInt();
for(int test = 1; test <= tests; test++) {
int n = reader.nextInt();
int q = reader.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++) arr[i] = reader.nextInt();
long[][] dp = new long[n][2];
for(int i =0; i < n; i++) {
Arrays.fill(dp[i], -1);
}
System.out.println(go(0, dp, 0, arr));
}
}
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 | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 5e7fa60333c43dc01da0bc0260f2e8e4 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.*;
import java.io.*;
public class C {
public static void main(String[] args) throws IOException {
Reader sc=new Reader();
Print pr=new Print();
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int q=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
int status[]=new int[n];
long ans=0;
if(n==1) {
ans+=a[0];
status[0]=1;
}
else
for(int i=0;i<n;i++) {
if(i==0) {
if(a[i+1]<a[i]) {
status[i]=1;
ans+=a[i];
}
}
else if(i==n-1) {
if(a[i]>a[i-1]) {
status[i]=1;
ans+=a[i];
}
}
else {
if(a[i+1]>a[i] && a[i-1]>a[i]){
status[i]=-1;
ans-=a[i];
}
else if(a[i+1]<a[i] && a[i-1]<a[i]) {
status[i]=1;
ans+=a[i];
}
}
}
pr.printLine(ans+"");
while(q-->0) {
int l=sc.nextInt()-1;
int r=sc.nextInt()-1;
if(l==r) {
pr.printLine(ans+"");
continue;
}
ArrayList<Integer> list=new ArrayList<Integer>();
if(l!=0)
list.add(l-1);
list.add(l);
if(l!=n-1 && l!=r-1)
list.add(l+1);
if(r!=0 && r>l+2)
list.add(r-1);
list.add(r);
if(r!=n-1)
list.add(r+1);
for(Integer i:list) {
ans-=(status[i]*a[i]);
status[i]=0;
}
int temp=a[l];
a[l]=a[r];
a[r]=temp;
for(Integer i:list) {
if(i==0) {
if(a[i+1]<a[i]) {
status[i]=1;
ans+=a[i];
}
}
else if(i==n-1) {
if(a[i]>a[i-1]) {
status[i]=1;
ans+=a[i];
}
}
else {
if(a[i+1]>a[i] && a[i-1]>a[i]){
status[i]=-1;
ans-=a[i];
}
else if(a[i+1]<a[i] && a[i-1]<a[i]) {
status[i]=1;
ans+=a[i];
}
}
}
pr.printLine(ans+"");
}
}
pr.close();
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din; private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() { din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; }
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; }
public String readLine() throws IOException { int cnt = 0, c;
byte[] buf = new byte[64]; while ((c = read()) != -1) { if (c == '\n')
break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); }
public int nextInt() throws IOException {
int ret = 0; byte c = read(); while (c <= ' ') c = read();
boolean neg = (c == '-'); if (neg) c = read(); do {
ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret; return ret; }
public long nextLong() throws IOException { long ret = 0; byte c = read();
while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read();
do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret; return ret; }
public double nextDouble() throws IOException { double ret = 0,
div = 1; byte c = read(); while (c <= ' ') c = read();
boolean neg = (c == '-'); if (neg) c = read(); do {
ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9');
if (c == '.') { while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10); } } if (neg) return -ret;
return ret; }
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1; }
private byte read() throws IOException { if (bufferPointer == bytesRead)
fillBuffer(); return buffer[bufferPointer++]; }
public void close() throws IOException { if (din == null) return;
din.close(); }
}
static class Print {
private final BufferedWriter bw;
public Print() {
bw=new BufferedWriter(new OutputStreamWriter(System.out)); }
public void print(String str)throws IOException { bw.append(str); }
public void printLine(String str)throws IOException { print(str);
bw.append("\n"); }
public void close()throws IOException { bw.close(); }
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 7c099cb492d93f38735879febc7591fe | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | //package codeforces_464_div2;
import java.util.Scanner;
public class C_ {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0) {
int n = sc.nextInt();
int q = sc.nextInt();
int[] a = new int[n];
for(int i=0; i<n; i++) a[i] = sc.nextInt();
long[][] dp = new long[a.length][2];
for(int i=0; i<a.length; i++) {
dp[i][0] = -1;
dp[i][1] = -1;
}
long ans = find(0, 1, a, dp); // sign=1 for positive and 0 for negative
System.out.println(ans);
}
}
public static long find(int idx, int sign, int[] a, long[][] dp) {
if(idx >= a.length)
return 0;
if(dp[idx][sign] != -1)
return dp[idx][sign];
long x = 0;
long y = 0;
if(sign == 1) {
x = a[idx] + find(idx + 1, 0, a, dp);
y = find(idx + 1, 1, a, dp);
}
else {
x = -a[idx] + find(idx+1, 1, a, dp);
y = find(idx+1, 0, a, dp);
}
return dp[idx][sign] = Math.max(x, y);
}
}
//()()
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | dc2e35b0767bcce3892139ca129ab1a7 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// Scanner sc=new Scanner(System.in);
FastReader sc=new FastReader();
Writer w=new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();int q=sc.nextInt();
long[] a=new long[n];long[][] dp=new long[n][2];
// HashMap<Long,Integer> map=new HashMap<>();
for(int i=0;i<n;i++){
a[i]=sc.nextLong();
}
dp[0][0]=a[0];
for(int i=1;i<n;i++){
dp[i][0]=Math.max(Math.max(dp[i-1][1]+a[i],a[i]),dp[i-1][0]);
dp[i][1]=Math.max(dp[i-1][0]-a[i],dp[i-1][1]);
}
System.out.println(Math.max(dp[n-1][1],dp[n-1][0]));
}
w.flush();
w.close();
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 1331471e19cbabfadb3790ac98dc4876 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.*;
import java.awt.image.BandedSampleModel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.Scanner;
public class C {
public static void main(String args[])
{
//ArrayList<Integer> list=new ArrayList();
Scanner sc=new Scanner(System.in);
int cases = sc.nextInt();
for(int i=0;i<cases;i++)
{
boolean inc=true;
long plus=0;
long minus=0;
int count=0;
long last=0;
int n = sc.nextInt();
int swap=sc.nextInt();
long arr[] = new long[n];
for(int j=0;j<n;j++)
{
arr[j]=sc.nextLong();
}
for(int j=1;j<n;j++)
{
if(inc&&j==n-1&&arr[j]>=arr[j-1])
{
plus=plus+arr[j];
inc=false;
count++;
}
else
if(inc&&(arr[j]<arr[j-1]))
{
plus=plus+arr[j-1];
inc=false;
count++;
}
else if(!inc&&arr[j]>arr[j-1])
{
inc=true;
minus=minus+arr[j-1];
last=arr[j];
count++;
}
}
long ans=0;
if(n==1)
{
ans=(arr[0]);
}
else
if(count%2==0)
{
ans=ans+plus-minus+last;
}
else
{
ans=ans+plus-minus;
}
System.out.println(ans);
}
}
}
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 13f41472b5f0dcfe586b5074cdb13d06 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.io.*;
import java.util.*;
public class Pc{
public static void main(String[] args) throws IOException{
FastReader sc = new FastReader();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out),"ASCII"),512);
int t = sc.nextInt();
while(t-- > 0){
int n = sc.nextInt();
int q = sc.nextInt();
int[] a = new int[n];
long[] odd = new long[n];
long[] even = new long[n];
for(int i=0;i<n;i++) a[i] = sc.nextInt();
odd[0] = a[0];
even[0] = 0;
long maxo = a[0];
long maxe = 0;
for(int i=1;i<n;i++){
odd[i] = maxe + a[i];
even[i] = maxo - a[i];
maxo = Math.max(odd[i], maxo);
maxe = Math.max(even[i], maxe);
}
long op = 0;
for(int i=0;i<n;i++) op = Math.max(op, odd[i]);
out.write(op + "");
out.write('\n');
}
out.flush();
}
}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}
catch (IOException e){
e.printStackTrace();
}
return str;
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 1387ab23287086ec70fd187e06198444 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | /*
Modassir_Ali
algo.java
*/
import java.util.*;
import java.io.*;
import java.util.Stack ;
import java.util.HashSet;
import java.util.HashMap;
public class C_CF672D2
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int ni()throws IOException{return sc.nextInt();}
static long nl()throws IOException{return sc.nextLong();}
static int[][] nai2(int n,int m)throws IOException{int a[][] = new int[n][m];for(int i=0;i<n;i++)for(int j=0;j<m;j++)a[i][j] = ni();return a;}
static int[] nai(int N,int start)throws IOException{int[]A=new int[N+start];for(int i=start;i!=(N+start);i++){A[i]=ni();}return A;}
static Integer[] naI(int N,int start)throws IOException{Integer[]A=new Integer[N+start];for(int i=start;i!=(N+start);i++){A[i]=ni();}return A;}
static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
static void print(int arr[]){for(int i=0;i<arr.length;i++)out.print(arr[i]+" ");out.println();}
static void print(long arr[]){for(int i=0;i<arr.length;i++)out.print(arr[i]+" ");out.println();}
static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} // return the number of set bits.
static boolean isPrime(int number){if(number==1) return false;if (number == 2 || number == 3){return true;}if (number % 2 == 0) {return false;}int sqrt = (int) Math.sqrt(number) + 1;for(int i = 3; i < sqrt; i += 2){if (number % i == 0){return false;}}return true;}
static boolean isPrime(long number){if(number==1) return false;if (number == 2 || number == 3){return true;}if (number % 2 == 0) {return false;}long sqrt = (long) Math.sqrt(number) + 1;for(int i = 3; i < sqrt; i += 2){if (number % i == 0){return false;}}return true;}
static int power(int n,int p){if(p==0)return 1;int a = power(n,p/2);a = a*a;int b = p & 1;if(b!=0){a = n*a;}return a;}
static long power(long n,long p){if(p==0)return 1;long a = power(n,p/2);a = a*a;long b = p & 1;if(b!=0){a = n*a;}return a;}
static void reverse(int[] a) {int b;for (int i = 0, j = a.length - 1; i < j; i++, j--) {b = a[i];a[i] = a[j];a[j] = b;}}
static void reverse(long[] a) {long b;for (int i = 0, j = a.length - 1; i < j; i++, j--) {b = a[i];a[i] = a[j];a[j] = b;}}
static void swap(int a[],int i,int j){a[i] = a[i] ^ a[j];a[j] = a[j] ^ a[i];a[i] = a[i] ^ a[j];}
static void swap(long a[],int i,int j){a[i] = a[i] ^ a[j];a[j] = a[j] ^ a[i];a[i] = a[i] ^ a[j];}
static int count(int n){int c=0;while(n>0){c++;n = n/10;}return c;}
static int[] prefix_sum(int a[],int n){int s[] = new int[n];s[0] = a[0];for(int i=1;i<n;i++){s[i] = a[i]+s[i-1];}return s;}
static long[] prefix_sum_int(int a[],int n){long s[] = new long[n];s[0] = (long)a[0];for(int i=1;i<n;i++){s[i] = ((long)a[i])+s[i-1];}return s;}
static long[] prefix_sum_Integer(Integer a[],int n){long s[] = new long[n];s[0] = (long)a[0];for(int i=1;i<n;i++){s[i] = ((long)a[i])+s[i-1];}return s;}
static long[] prefix_sum_long(long a[],int n){long s[] = new long[n];s[0] = a[0];for(int i=1;i<n;i++){s[i] = a[i]+s[i-1];}return s;}
static boolean isPerfectSquare(double x){double sr = Math.sqrt(x);return ((sr - Math.floor(sr)) == 0);}
static ArrayList<Integer> sieve(int n) {int k=0; boolean prime[] = new boolean[n+1];ArrayList<Integer> p_arr = new ArrayList<>();for(int i=0;i<n;i++) prime[i] = true;for(int p = 2; p*p <=n; p++){ k=p;if(prime[p] == true) { p_arr.add(p);for(int i = p*2; i <= n; i += p) prime[i] = false; } }for(int i = k+1;i<=n;i++){if(prime[i]==true)p_arr.add(i);}return p_arr;}
static boolean[] seive_check(int n) {boolean prime[] = new boolean[n+1];for(int i=0;i<n;i++) prime[i] = true;for(int p = 2; p*p <=n; p++){ if(prime[p] == true) { for(int i = p*2; i <= n; i += p) prime[i] = false; } }prime[1]=false;return prime;}
static int get_bits(int n){int p=0;while(n>0){p++;n = n>>1;}return p;}
static int get_bits(long n){int p=0;while(n>0){p++;n = n>>1;}return p;}
static int get_2_power(int n){if((n & (n-1))==0)return get_bits(n)-1;return -1;}
static int get_2_power(long n){if((n & (n-1))==0)return get_bits(n)-1;return -1;}
static void close(){out.flush();}
/*-------------------------Main Code Starts(algo.java)----------------------------------*/
public static void main(String[] args) throws IOException {
int t = ni() ;
while(t--!=0){
int n = ni() ;
int q = ni() ;
long arr[] = nal(n) ;
solve(arr, n);
}
}
static void solve(long arr[] , int n){
int flip = 0 ;
long sum = 0L ;
// boolean last = false ;
for(int i=1 ; i<n ; i++){
if(flip==0){
if(arr[i]>=arr[i-1]){
continue ;
}
else{
flip = 1 ;
sum = sum + arr[i-1] ;
}
}
else{
if(arr[i]<=arr[i-1]){
continue ;
}
else{
flip = 0 ;
sum = sum - arr[i-1] ;
}
}
}
if(flip==0){
sum = sum + arr[n-1] ;
}
System.out.println(sum);
}
}
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 5487bb8af4982bcd2bd8164734fd8eb7 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tests = sc.nextInt();
for(int t=0; t<tests; t++){
int size = sc.nextInt();
int q = sc.nextInt();
int[] arr = new int[size];
long ans = 0;
for(int i=0; i<size; i++){
arr[i]=sc.nextInt();
}
boolean look_max = true;
int prev_max = arr[0];
int prev_min=arr[0];
for(int i=1; i<size; i++){
if(look_max && arr[i]>=arr[i-1]){
prev_max = arr[i];
}
else if(look_max && arr[i]<arr[i-1]){
ans+=prev_max;
look_max=false;
i--;
}
else if(!look_max && arr[i]<=arr[i-1]){
prev_min=arr[i];
}
else if(!look_max && arr[i]>arr[i-1]){
ans-=prev_min;
look_max=true;
i--;
}
}
if(look_max){
ans+=prev_max;
}
System.out.println(ans);
}
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 2e10ba6b25ab776b13bfb917c8b0f5c9 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class Rextester{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
StringBuffer sb = new StringBuffer();
while(t-->0){
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int[] arr = new int[n];
StringTokenizer st1 = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
arr[i]=Integer.parseInt(st1.nextToken());
}
long[] a= new long[n];
long[] s = new long[n];
a[0]=arr[0];
s[0]=0;
for(int i=1;i<n;i++){
a[i]=Math.max(s[i-1]+arr[i],a[i-1]);
s[i]=Math.max(s[i-1],a[i-1]-arr[i]);
}
sb.append(Math.max(a[n-1],s[n-1])).append("\n");
}
br.close();
System.out.println(sb);
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 3ca9a001f5c6c9b77821b24fdb60da42 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {
FastScanner fs=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int t=fs.nextInt();
while(t-->0)
{
int n=fs.nextInt();
int q=fs.nextInt();
long a[]=fs.readArray(n);
ArrayList<Long> al=new ArrayList<>();
for(int i=1;i<n-1;i++)
{
if(isPeak(a,i))
al.add(a[i]);
}
long sum=0;
for(int i=0;i<al.size();i++)
{
if(i%2==0)
sum+=al.get(i);
else
sum-=al.get(i);
}
al.add(a[n-1]);
long sum1=0;
for(int i=0;i<al.size();i++)
{
if(i%2==0)
sum1+=al.get(i);
else
sum1-=al.get(i);
}
long sum2=0;
for(int i=0;i<al.size()-1;i++)
{
if(i%2!=0)
sum2+=al.get(i);
else
sum2-=al.get(i);
}
sum2+=a[0];
long sum3=0;
for(int i=0;i<al.size();i++)
{
if(i%2!=0)
sum3+=al.get(i);
else
sum3-=al.get(i);
}
sum3+=a[0];
out.println(Math.max(sum,Math.max(sum1,Math.max(sum2,sum3))));
}
out.flush();
out.close();
}
static boolean isPeak(long[] a,int i)
{
if((a[i]<a[i+1] && a[i]<a[i-1]) || (a[i]>a[i+1] && a[i]>a[i-1]))
return true;
else
return false;
}
static void ruffleSort(int[] a) {
Random random=new Random();
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
}
class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String nextLine() {
String str="";
try {
str=br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
long[] readArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 9494f313f934030ffe0827f2e58537bf | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static int mod=(int)1e9+7;
public static void main(String[] args) throws IOException {
Writer out=new Writer(System.out);
Reader in=new Reader(System.in);
int ts=in.nextInt();
outer: while(ts-->0) {
int n=in.nextInt();
int q=in.nextInt();
int a[]=in.readArray(n);
int c[]=new int[n];
c[0]=1;
for(int i=1; i<n; i++) {
if(a[i]>a[i-1]) c[i]=1;
else c[i]=-1;
}
long sum=0;
if(n==1) {
out.println(a[0]); continue;
}
for(int i=1; i<n; i++) {
if(c[i]!=c[i-1]) {
sum=sum+c[i-1]*a[i-1];
}
if(i==n-1) {
if(c[i]==1) sum+=a[i];
else continue;
}
}
out.println(sum);
}
out.close();
}
/*********************************** UTILITY CODE BELOW **************************************/
static int abs(int a) {
return a>0 ? a : -a;
}
static int max(int a, int b) {
return a>b ? a : b;
}
static long pow(long n, long m) {
if(m==0) return 1;
long temp=pow(n,m/2);
long res=((temp*temp)%mod);
if(m%2==0) return res;
return (res*n)%mod;
}
static class Pair{
int u, v;
Pair(int u, int v){this.u=u; this.v=v;}
static void sort(Pair [] coll) {
List<Pair> al=new ArrayList<>(Arrays.asList(coll));
Collections.sort(al,new Comparator<Pair>() {
public int compare(Pair p1, Pair p2) {
return p1.u-p2.u;
}
});
for(int i=0; i<al.size(); i++) {
coll[i]=al.get(i);
}
}
}
static void sort(int[] a) {
ArrayList<Integer> list=new ArrayList<>();
for (int i:a) list.add(i);
Collections.sort(list);
for (int i=0; i<a.length; i++) a[i]=list.get(i);
}
static void sort(long a[]) {
ArrayList<Long> list=new ArrayList<>();
for(long i: a) list.add(i);
Collections.sort(list);
for(int i=0; i<a.length; i++) a[i]=list.get(i);
}
static int [] array(int n, int value) {
int a[]=new int[n];
for(int i=0; i<n; i++) a[i]=value;
return a;
}
static class Reader{
BufferedReader br;
StringTokenizer to;
Reader(InputStream stream){
br=new BufferedReader(new InputStreamReader(stream));
to=new StringTokenizer("");
}
String next() {
while(!to.hasMoreTokens()) {
try {
to=new StringTokenizer(br.readLine());
}catch(IOException e) {}
}
return to.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int [] readArray(int n) {
int a[]=new int[n];
for(int i=0; i<n ;i++) a[i]=nextInt();
return a;
}
long [] readLongArray(int n) {
long a[]=new long[n];
for(int i=0; i<n ;i++) a[i]=nextLong();
return a;
}
}
static class Writer extends PrintWriter{
Writer(OutputStream stream){
super(stream);
}
void println(int [] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
void println(long [] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | fbba0a7f8a429ca929fe6a4c06141d9b | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
var sc = new Scanner(System.in);
var pw = new PrintWriter(System.out);
int T = Integer.parseInt(sc.next());
for(int t = 0; t < T; t++){
int n = Integer.parseInt(sc.next());
int q = Integer.parseInt(sc.next());
var a = new int[n];
for(int i = 0; i < n; i++){
a[i] = Integer.parseInt(sc.next());
}
if(n == 1){
pw.println(a[0]);
continue;
}
long ans = 0;
boolean high = true;
int id = -1;
if(a[0] > a[1]){
ans += a[0];
high = false;
}
for(int i = 1; i < n-1; i++){
if(high){
if(a[i-1] < a[i] && a[i] > a[i+1]){
ans += a[i];
high = false;
}
}else{
if(a[i-1] > a[i] && a[i] < a[i+1]){
ans -= a[i];
high = true;
id = i;
}
}
}
if(a[n-2] < a[n-1]){
ans += a[n-1];
high = false;
}
if(high) ans += a[id];
pw.println(ans);
}
pw.flush();
}
} | Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 17d2fb07e04b6da192c0a10b0bd1e874 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 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.
*/
//package javaapplication1;
import java.util.*;
/**
*
* @author DELL
*/
public class JavaApplication1 {
/**
* @param args the command line arguments
*/
static long length(long n){
long count=0;
while(n!=0){
n=n/2;
count++;
}
return count;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
//StringBuilder sb=new StringBuilder();
while(t-->0){
int n=sc.nextInt();
int q=sc.nextInt();
long a[]=new long[n+2];
for(int i=0;i<n+2;i++){
if(i==0 || i==n+1)a[i]=0;
else a[i]=sc.nextLong();
}
boolean b=true;
long sum=0;
for(int i=0;i<n+2;i++){
if( b &&i-1>=0 && i+1<n+2 && a[i]>a[i-1] && a[i]>a[i+1]){
sum+=a[i];
b=false;
}
else if(!b && i+1<n+2 && a[i]<a[i-1] && a[i]<a[i+1]){
sum-=a[i];
b=true;
}
}
System.out.println(sum);
}
}
}
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 8490daa5d04ffc83c6fd5d88757fdd27 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class PokemonArmy {
static long getMin(int[]array,int n){
long[][]dp=new long[n][2];
for(long[]a:dp)
Arrays.fill(a, Integer.MIN_VALUE);
dp[0][0]=0;
dp[0][1]=0;
for(int i=0;i<n-1;i++){
dp[i+1][0]=Math.max(dp[i][0], dp[i][1]+array[i]);
dp[i+1][1]=Math.max(dp[i][1], dp[i][0]-array[i]);
}
dp[n-1][1]+=Math.max(array[n-1], 0);
return Math.max(dp[n-1][0], dp[n-1][1]);
}
public static void main(String[] args) throws IOException{
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(r.readLine());
while(t-->0){
String[]data1=r.readLine().split(" ");
int n=Integer.parseInt(data1[0]);
String[]data=r.readLine().split(" ");
int[]array=new int[n];
for(int i=0;i<n;i++){
array[i]=Integer.parseInt(data[i]);
}
System.out.println(getMin(array, n));
}
}
}
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 49a4057871061e44ac2efc0e9e8a95f4 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int t=in.nextInt();
while(t-->0)
{
int n=in.nextInt();
int q=in.nextInt();
long a[]=new long[n];
long dp[][]=new long[2][n];
for(int i=0;i<n;i++)
a[i]=in.nextLong();
if(n==1)
System.out.println(a[0]);
else{
dp[0][n-1]=a[n-1];
dp[1][n-1]=0;
for(int i=n-2;i>=0;i--)
{
dp[0][i]=Math.max(dp[0][i+1],dp[1][i+1]+a[i]);
dp[1][i]=Math.max(dp[0][i+1]-a[i],dp[1][i+1]);
}
System.out.println(dp[0][0]);
}
}
}
}
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 4f568aaacfb4391138e31322326ed963 | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.util.Scanner;
public class C {
static Scanner sc = new Scanner(System.in);
static StringBuilder out = new StringBuilder();
public static void main(String[] args){
int t = sc.nextInt();
while (t-- >0){
int n = sc.nextInt();
int q = sc.nextInt();
long[] a = new long[n];
for (int i=0;i<n;i++){
a[i] = sc.nextLong();
}
long ans = 0;
boolean flag = true;
if (n==1){
ans = a[0];
}else {
for (int i=0;i<n;i++){
if (i+1<n){
if (flag){
if (a[i]>a[i+1]){
flag = false;
ans += a[i];
}
}else {
if (a[i]<a[i+1]){
flag = true;
ans -= a[i];
}
}
}else {
if (flag){
if (a[i]>a[i-1]){
ans += a[i];
}
}
}
}
}
out.append(ans+"\n");
/*
while (q -- > 0){
int l = sc.nextInt()-1;
int r = sc.nextInt();
int lstates =0;
int rstates =0;
// 1 上升 0 是谷底/峰顶 -1 下讲
if (l>0){
if (l<n-2){
if (a[l]>a[l-1]&&!(a[l]>a[l+1])){
if (a[l]>a[l-1]){
lstates = 1;
}else {
lstates = -1;
}
}else {
lstates = 0;
}
}else {
if (a[l]>a[l-1]){
lstates = 0;
}else {
lstates = -1;
}
}
}else {
if (l<n-2){
if (a[l]>a[l+1]){
lstates = 0;
}else {
lstates = 1;
}
}
}
if (lstates==1){
}else if (lstates==-1){
}else {
ans -= l;
if ()
}
if (r>0){
if (r<n-2){
if (a[r]>a[r-1]&&!(a[r]>a[r+1])){
if (a[r]>a[r-1]){
rstates = 1;
}else {
rstates = -1;
}
}else {
rstates = 0;
}
}else {
if (a[r]>a[r-1]){
rstates = 0;
}else {
rstates = -1;
}
}
}else {
if (r<n-2){
if (a[r]>a[r+1]){
rstates = 0;
}else {
rstates = 1;
}
}
}
*/
}
System.out.println(out);
}
}
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | 0cb5089293962905d20c22949383945e | train_002.jsonl | 1600958100 | This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* for competitive programming
* @author BrolyCode
* @version 1.0.0
*/
public class CP {
static Random random;
private static void mySort(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
Arrays.sort(s);
}
static class Pair<A,B>{
A x;
B y;
public Pair(A x, B y) {
this.x=x;
this.y=y;
}
}
public static void pairSort(Pair[] p, Comparator<? super Pair> c) {
Arrays.sort(p, c);
}
public static void main(String[] args) {
random = new Random(543534151132L + System.currentTimeMillis());
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
task(in,out);
out.close();
}
private static void task(InputReader in, PrintWriter out) {
int t = in.nextInt();
while(--t >= 0) {
int n = in.nextInt();
int q = in.nextInt();
assert q == 0;
int[] T = new int[n];
for(int i = 0; i < n; i++)
T[i] = in.nextInt();
long ans = 0;
for(int i = 0; i < n; i++) {
if(i == n - 1)
ans += T[n - 1];
else {
ans += Math.max(0,T[i] - T[i + 1]);
}
}
out.println(ans);
}
}
public static int find(int[] T, int x) {
if(x == T[x])
return x;
return find(T,T[x]);
}
public static void add(int[] T, int a, int b) {
T[b] = find(T, a);
}
public static int gcd(int a, int b)
{
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
public static long gcd(long a, long b)
{
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.longValue();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
}
}
| Java | ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"] | 2 seconds | ["3\n2\n9"] | NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"greedy"
] | 2d088e622863ab0d966862ec29588db1 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. | 1,300 | For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap. | standard output | |
PASSED | f5e13281692bdb6c97a799f6f1ea77a6 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int n = sc.nextInt();
int sum = sc.nextInt();
int time = sc.nextInt();
// int[][] ii = new int[n][2];
int max = 0;
int s = 0;
f1:
for (int i = 0; i < n; i++) {
int t1 = sc.nextInt();
int t2 = sc.nextInt();
while (t1 - s >= time) {
max = max+(t1-s)/time;
break;
}
s = t1 + t2;
}
if (sum-s >= time)
max = max+(sum-s)/time;
System.out.println(max);
}
}
| Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | af53ef710453edd7ae49f9785f86b355 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | /*
01001101 01000001 01000001 01001100 00100000 01000001 01000001 01010100
01001001 00100000 01001000 01000001 01001001 01001110 00100000 01011001
01000001 01000001 01000100 01000101 01001001 01001110 00100000 01000011
01001000 01001111 01000100 00100000 01001010 01000001 01000001 01010100
01001001 00100000 01001000 01000001 01001001 01001110
*/
/* 01000010 01001001 01001100 01001011 01010101 01001100 00100000 01001000 01001001
00100000 01000110 01000001 01010010 01011010 01001001 00100000 01001000 01001111
00100000 01001011 01011001 01000001 00100001 00100000 00111010 00101001
*/
/*
01001000 01001111 01010000 01000101 00100000 01010100 01001000 01001001
01010011 00100000 01001101 01000001 01000100 01000101 00100000 01011001
01001111 01010101 00100000 01010011 01001101 01001001 01001100 01000101
00100001
*/
import java.io.*;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.TreeMap;
/*
CODE WRITTEN BY RITWIK SHANKER
JUET
161B180
*/
public class A514
{
public static void main(String[] args) throws Exception
{
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int n = in.readInt();
int L = in.readInt();
int a = in.readInt();
TreeMap<Integer, Integer> map = new TreeMap<>();
int t[] = new int[n];
int l[] = new int[n];
for (int i = 0; i < n; i++)
{
t[i] = in.readInt();
l[i] = in.readInt();
map.put(t[i], l[i]);
}
int q = 0;
long sum = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet())
{
t[q] = entry.getKey();
l[q] = entry.getValue();
q += 1;
}
long ans = 0;
for (int i = 0; i < n; i++)
{
ans += (t[i] - sum) / a;
sum = t[i] + l[i];
}
ans += (L - sum) / a;
out.printLine(ans);
}
//FAST IO
private static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int readInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double readDouble()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
{
return filter.isSpaceChar(c);
}
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
private static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
{
writer.print(' ');
}
writer.print(objects[i]);
}
writer.flush();
}
public void printLine(Object... objects)
{
print(objects);
writer.println();
writer.flush();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
} | Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | 8c056910bb48a5ec9b9df3b5877d8092 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.nio.Buffer;
import java.util.*;
public class Pair {
static class FastReader {
private BufferedReader br;
private StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws Exception {
try {
FastReader sc = new FastReader();
int ti,li,count=0,start=0,add;
int n = sc.nextInt();
int l = sc.nextInt();
int a = sc.nextInt();
for(int i=0;i<n;i++){
ti = sc.nextInt();
li = sc.nextInt();
add = (ti-start)/a;
count = count+add;
start=ti+li;
}
l=l-start;
add=l/a;
count=count+add;
System.out.println(count);
}
catch (Exception e) {
}
}
} | Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | 8ac2b595793915872a611029f2037920 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Codef{
public static void main ( String [] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n, l, a, i, ti, li, ans=0, pos= 0;
boolean flg = false;
String line, spl[], line2;
line = br.readLine();
spl = line.split("\\s+");
n = Integer.parseInt(spl[0]);
l = Integer.parseInt(spl[1]);
a = Integer.parseInt(spl[2]);
for (i = 0; i < n ; i++){
line2 = br.readLine();
spl = line2.split("\\s+");
ti = Integer.parseInt(spl[0]);
li = Integer.parseInt(spl[1]);
ans += (ti - pos) / a;
pos = ti + li;
}
ans += (l - pos) / a;
System.out.println(ans);
}
}
| Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | fd7c620b9fdf3d0c2200f4c8e0a2b8e2 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class ch {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
//sc.waitForInput();
int n = sc.nextInt();
long l = sc.nextLong();
int a = sc.nextInt();
//Pair[] arr = new Pair[n];
long sum = 0 ;
//long suma = 0 ;
long s =0 ;
for(int i=0 ; i<n ; i++) {
int c = sc.nextInt();
long t = sc.nextLong();
sum+= (c-s)/a;
s = t+c ;
}
sum += (l-s)/a;
System.out.println(sum);
}
/* static class Pair {
int ci;
long ti;
Pair(int c , long t){
ci = c;
ti = t;
}
}*/
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 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | d83352928c743c85c3c22dd4a0eeb91e | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.io.*;
import java.util.*;
public class Cashier
{
public static void main(String[] f)
{
long n,L,a,i,prevxi=0,prevyi=0,xi,yi;
long sum=0;
Scanner sc=new Scanner(System.in);
n=sc.nextLong();
L=sc.nextLong();
a=sc.nextLong();
for(i=0;i<n;i++)
{
xi=sc.nextLong();
yi=sc.nextLong();
sum+=((xi-prevyi)/(a));
prevyi=(yi+xi);
}
sum+=((L-prevyi)/(a));
System.out.println(sum);
}
} | Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | 3c864bdfd7366d2384f44d52c6981458 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
public class Cashier {
public static void main(String[] args) {
// TODO Auto-generated method stub
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n=in.nextInt(),L=in.nextInt(),a=in.nextInt();
int[][] vals=new int[n][2];
for(int i=0;i<n;i++) {
vals[i][0]=in.nextInt();
vals[i][1]=in.nextInt()+vals[i][0];
}
//Arrays.sort(vals,(int[] x, int[] y)->x[0]-y[1]);
long total=0;
if(n>0) {
total+=vals[0][0]/a;
for(int i=1;i<n;i++) {
total+=(vals[i][0]-vals[i-1][1])/a;
}
total+=(L-vals[n-1][1])/a;
}
else {
total+=L/a;
}
out.println(total);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | fa597adaf798a42c96ade8902925e5f9 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int L = scn.nextInt();
int a = scn.nextInt();
int[] t = new int[n];
int[] l = new int[n];
for(int i=0;i<n;++i){
t[i] = scn.nextInt();
l[i] = scn.nextInt();
}
int sum = 0, count =0;
for(int i=0;i<n;++i){
int prev = sum;
if(t[i] - prev >= a) count = count + (t[i] - prev)/a;
sum = t[i] + l[i];
}
System.out.println(count + (L-sum)/a);
}
} | Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | e95ee63b923aa576dbfe5b3b82a4f3df | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.util.*;
import java.io.*;
public class Cashier {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
long n = sc.nextInt(); long l = sc.nextInt(); long a = sc.nextInt();
long currenttime = 0;
long breaks = 0;
for(int i = 0; i<n; i++){
int x = sc.nextInt();
if(x>currenttime){breaks = breaks + (x-currenttime)/a;}
int y = sc.nextInt();
currenttime = x + y;
}
breaks = breaks + (l-currenttime)/a;
out.println(breaks);
out.flush();
}
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 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | e2fd9e0fc932affe12bd215c2aa4496f | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.util.Scanner;
public class Cashier {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int L = s.nextInt();
int a = s.nextInt();
int[] t,l;
t = new int[n];
l = new int[n];
for(int i=0;i<n;i++) {
t[i] = s.nextInt();
l[i] = s.nextInt();
}
int sum = 0;
if(n==0)
sum = L/a;
else if(n==1){
sum += t[0]/a;
sum += (L-t[n-1]-l[n-1])/a;
}else {
sum += t[0]/a;
for(int i=0;i<n-1;i++) {
int free_i = t[i+1]-(t[i]+l[i]);
if(free_i>=a)
sum += free_i/a;
}
sum += (L - t[n-1]-l[n-1])/a;
}
System.out.println(sum);
}
}
| Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | a4091b2f06e0b35e60f684244428b7ef | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.io.*;
import java.util.*;
public class Contest {
static class Customer implements Comparable<Customer>{
int t, l;
Customer(int t, int l){
this.t = t;
this.l = l;
}
@Override
public int compareTo(Customer c) {
return this.t-c.t;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int l = Integer.parseInt(st.nextToken());
int a = Integer.parseInt(st.nextToken());
Customer[] c = new Customer[n];
for (int i=0; i<n; i++) {
st = new StringTokenizer(br.readLine());
c[i] = new Customer(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
}
Arrays.sort(c);
if (n==0) {
System.out.println(l/a);
return;
}
int b = (c[0].t)/a;
for (int i=0; i<n; i++) {
if (i!=n-1) {
int t = c[i+1].t-(c[i].t+c[i].l);
b += t/a;
}else {
b += (l-(c[i].t+c[i].l))/a;
}
}
System.out.println(b);
}
} | Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | 2e03972ae0742bf81ce9875275b9c898 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.util.Scanner;
public class sdas {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), l = sc.nextInt(), a = sc.nextInt(), x=0, counter = 0;
for (int i = 0; i < n; i++){
int t = sc.nextInt(), k = sc.nextInt();
counter+= (t-x) /a;
x = t+k;
}
counter += (l-x) / a;
System.out.println(counter);
}
} | Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | b7e385a5e9dfc67fbbad268ca5d112fb | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.util.*;
public class GFG {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
long n=sc.nextInt(),l=sc.nextInt(),a=sc.nextInt();
long t1=0,l1=0;
if(n>0)
{t1=sc.nextInt();l1=sc.nextInt();}
long sum1=0;
long sum=t1+l1;
long count=t1/a;
//long r=t1%a;
for(int i=0;i<n-1;i++){
t1=sc.nextInt();l1=sc.nextInt();
count+=(t1-sum)/a;
sum=t1+l1;
//r=(sum1-sum+r)%a;
// sum=sum1;
}
count+=(l-sum)/a;
System.out.println(count);
}
}
| Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | 0353442526ceee963e6ce1b9d388a819 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.util.Scanner;
public class NewTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int L = scanner.nextInt();
int a = scanner.nextInt();
int card = 0;
int ans = 0;
for (int i = 0; i < n; i++) {
int s = scanner.nextInt();
int e = scanner.nextInt();
if ((s - card)/a!=0){
int x = (s - card)/a;
ans += x;
}
card = s + e;
}
if ((L - card)/a!=0){
int x = (L - card)/a;
ans += x;
}
System.out.println(ans);
}
}
| Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | aea0019ec20b93c38b5d23e8c9d61759 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.util.*;
public class Cashier {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int L = sc.nextInt();
int A = sc.nextInt();
int prevC = 0;
long sum = 0L;
for (int i = 0; i < N; i++) {
int curT = sc.nextInt();
int curL = sc.nextInt();
sum += (curT-prevC)/A;
prevC = curT + curL;
}
sum += (L-prevC)/A;
System.out.println(sum);
sc.close();
}
} | Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | 2a0e1d0b86e682184138a306c91310f6 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes |
//package Codeforces_contest;
import java.io.*;
import java.util.*;
/**
*
* @author abhishek
*/
import java.io.*;
import java.util.*;
public class R514Div2A{
InputStream obj;
PrintWriter out;
String check = "";
//Solution !!
void solution() {
int n=inti(),l=inti(),a=inti();
int x[]=new int[n];
int y[] = new int[n];
for(int i=0;i<n;i++){
int ti = inti(),li = inti();
x[i] = ti;
y[i] = li + ti;
}
// pa(mark);
if(n==0){
out.println(l/a);
return;
}
long ans=0;
ans+=(x[0]/a);
for(int i=0;i<n-1;i++){
ans+=((x[i+1] - y[i])/a);
}
ans+=((l-y[y.length - 1])/a);
out.println(ans);
}
//------->ends !!
public static void main(String[] args) throws IOException {
new Thread(null, new Runnable() {
public void run() {
try {
new R514Div2A().ace();
} catch (IOException e) {
e.printStackTrace();
} catch (StackOverflowError e) {
System.out.println("RTE");
}
}
}, "1", 1 << 26).start();
}
void ace() throws IOException {
out = new PrintWriter(System.out);
obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes());
// obj=check.isEmpty() ? new FileInputStream("location of file") : new ByteArrayInputStream(check.getBytes());
// long t1=System.currentTimeMillis();
solution();
// long t2=System.currentTimeMillis();
// out.println(t2-t1);
out.flush();
out.close();
}
byte inbuffer[] = new byte[1024];
int lenbuffer = 0, ptrbuffer = 0;
int readByte() {
if (lenbuffer == -1) {
throw new InputMismatchException();
}
if (ptrbuffer >= lenbuffer) {
ptrbuffer = 0;
try {
lenbuffer = obj.read(inbuffer);
} catch (IOException e) {
throw new InputMismatchException();
}
}
if (lenbuffer <= 0) {
return -1;
}
return inbuffer[ptrbuffer++];
}
boolean isSpaceChar(int c) {
return (!(c >= 33 && c <= 126));
}
String stri() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) // when nextLine, (isSpaceChar(b) && b!=' ')
{
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
int inti() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
int[][] ar2D(int n, int m) {
int ark[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ark[i][j] = inti();
}
}
return ark;
}
long loni() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
float fl() {
return Float.parseFloat(stri());
}
double dou() {
return Double.parseDouble(stri());
}
char chi() {
return (char) skip();
}
int[] arri(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = inti();
}
return a;
}
long[] arrl(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = loni();
}
return a;
}
String[] stra(int n) {
String a[] = new String[n];
for (int i = 0; i < n; i++) {
a[i] = stri();
}
return a;
}
private static void pa(Object... o) {
System.out.println(Arrays.deepToString(o));
}
// uwi mod pow function
public static long pow(long a, long n, long mod) {
// a %= mod;
long ret = 1;
int x = 63 - Long.numberOfLeadingZeros(n);
for (; x >= 0; x--) {
ret = ret * ret % mod;
if (n << 63 - x < 0) {
ret = ret * a % mod;
}
}
return ret;
}
int gcd(int a, int b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
long lcm(int a, int b) {
return a * (b / gcd(a, b));
}
}
| Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | 398786349924bd161720667dcdb683f7 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int L = in.nextInt();
int a = in.nextInt();
int curTime = 0;
int res = 0;
for (int i = 0; i < N; i++) {
int ti = in.nextInt();
int li = in.nextInt();
res += (ti - curTime) / a;
curTime = ti + li;
}
res += (L - curTime) / a;
out.println(res);
}
}
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 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | b32b36651e30114d201292918e940cb7 | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.util.*;
import java.io.*;
public final class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int L = sc.nextInt();
int a = sc.nextInt();
int[] t = new int[n];
int[] l = new int[n];
for(int i = 0; i<n; i++) {
t[i] = sc.nextInt();
l[i] = sc.nextInt();
}
int start = 0;
int ans = 0;
for(int i = 0; i<n; i++) {
ans+=(t[i]-start)/a;
start = t[i]+l[i];
}
ans+=(L-start)/a;
System.out.println(ans);
}
} | Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | be12f75c202d8448ee33701680a75c8f | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.io.*;
import java.util.*;
public class Cashier {
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 L=sc.nextInt();
int a=sc.nextInt();
cust []c=new cust[n];
for (int i=0;i<n;i++) {
c[i]=new cust(sc.nextInt(),sc.nextInt());
}
int possible=L;
for (int i=0;i<n;i++) {
possible-=c[i].service;
}
int ans=0;
if(n==0) {
out.println(possible/a);
out.flush();
return;
}
if(c[0].arrive<a) {
possible-=c[0].arrive%a;
}
for (int i=0;i<n-1;i++) {
int g=c[i+1].arrive-(c[i].arrive+c[i].service);
possible-=g%a;
}
int g=(L-(c[n-1].arrive+c[n-1].service))%a;
possible-=g;
out.println(possible/a);
out.close();
}
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 int nextInt() throws IOException{
return Integer.parseInt(next());
}
public long nextLong() throws IOException{
return Long.parseLong(next());
}
public String nextLine() throws IOException{
return br.readLine();
}
}
static class cust{
int arrive;
int service;
cust(int a,int s){
arrive=a;
service=s;
}
}
}
| Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | 46136d69c1095d9c52563469aba5976e | train_002.jsonl | 1538750100 | Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? | 256 megabytes | import java.util.Scanner;
public class Cashier {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int L = sc.nextInt();
int a = sc.nextInt();
int[] t = new int[n];
int[] l = new int [n];
int smoke = 0;
for (int i = 0; i < n; i++) {
t[i] = sc.nextInt();
l[i] = sc.nextInt();
}
if (n == 0){
smoke = L/a;
System.out.println(smoke);
return;
}
smoke += t[0]/a + Math.abs(L-t[n-1]-l[n-1])/a;
for (int i = 1; i < n; i++) {
smoke += (t[i]-t[i-1]-l[i-1])/a;
}
System.out.println(smoke);
}
}
| Java | ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"] | 2 seconds | ["3", "2", "0"] | NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks. | Java 8 | standard input | [
"implementation"
] | 00acb3b54975820989a788b9389c7c0b | The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \le n \le 10^{5}$$$, $$$1 \le L \le 10^{9}$$$, $$$1 \le a \le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \le t_{i} \le L - 1$$$, $$$1 \le l_{i} \le L$$$). It is guaranteed that $$$t_{i} + l_{i} \le t_{i + 1}$$$ and $$$t_{n} + l_{n} \le L$$$. | 1,000 | Output one integer — the maximum number of breaks. | standard output | |
PASSED | c8e1d34b0c474d56e0eacfd29a6cb720 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | //44,45,47,50,53,54,55
import java.util.*;
import java.lang.*;
import java.io.*;
import java.awt.Point;
public class CF601A
{ //***************************************** VARIABLE DECLERATION SECTION ********************************************************************;
//Integer ArrayList Math TreeMap TreeSet
// System.out.println
static int[][] graph;
static int[][] cgraph;
static int[] dist;
static int[] cdist;
static int n,m;
static int inf=(int)1e7;
static int cnt=inf,ccnt=inf;
//***************************************** VARIABLE DECLERATION ENDS ********************************************************************;
//************************************************ MAIN FUNCTION *************************************************************************;
public static void main(String[] args)
{
FastReader scan=new FastReader();
n=scan.nextInt();m=scan.nextInt();
graph=new int[n+1][n+1];
cgraph=new int[n+1][n+1];
dist=new int[n+1];
cdist=new int[n+1];
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
cgraph[i][j]=cgraph[j][i]=1;
}
}
for(int i=0;i<m;i++)
{
int x=scan.nextInt(),y=scan.nextInt();
graph[x][y]=graph[y][x]=1;
cgraph[x][y]=cgraph[y][x]=0;
}
/* for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
System.out.println(graph[i][j]);
}*/
for(int i=1;i<=n;i++)
{
dist[i]=cdist[i]=inf;
}
Queue<Integer> q=new LinkedList<Integer>();
dist[1]=0;
q.add(1);
while(!q.isEmpty())
{ int x=q.poll();
for(int i=1;i<=n;i++)
{
if(graph[x][i]==1)
{
//System.out.println(x+" "+i);
if(1+dist[x]<dist[i])
{
dist[i]=Math.min(dist[i],1+dist[x]);
q.add(i);
}
}
}
//if(x<n)q.add(x+1);
}
cdist[1]=0;
q.add(1);
while(!q.isEmpty())
{ int x=q.poll();
for(int i=1;i<=n;i++)
{
if(cgraph[x][i]==1)
{
if(1+cdist[x]<cdist[i])
{
cdist[i]=Math.min(cdist[i],1+cdist[x]);
q.add(i);
}
}
}
//if(x<n)q.add(x+1);
}
// System.out.println(dist[n]+" "+cdist[n]);
if(dist[n]==inf||cdist[n]==inf)
System.out.println(-1);
else
System.out.println(Math.max(dist[n],cdist[n]));
}
//*********************************************** MAIN FUNCTION ENDS *********************************************************************;
//********************************************** AUXILIARY FUNCTIONS **********************************************************************;
/*static void dfs(int x,int i)
{ //System.out.println(x+" "+i);
if(x==n)
{
cnt=Math.min(cnt,i);
return;
}
if(visited[x])return;
visited[x]=true;
ArrayList<Integer> al=graph.get(x);
for(int j=0;j<al.size();j++)
{
dfs(al.get(j),i+1);
}
}
static void cdfs(int x,int i)
{ //System.out.println(x+">>>>"+i);
if(x==n)
{
ccnt=Math.min(ccnt,i);
return;
}
if(cvisited[x])return;
cvisited[x]=true;
ArrayList<Integer> al=cgraph.get(x);
for(int j=0;j<al.size();j++)
{
cdfs(al.get(j),i+1);
}
}*/
//********************************************** AUXILIARY FUNCTIONS ENDS **********************************************************************;
//********************************************** INPUT FUNCTIONS ******************************************************************************;
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;
}
}
//********************************************** INPUT FUNCTIONS ******************************************************************************;
}
class Comp implements Comparator<Point>
{
public int compare(Point p1,Point p2)
{
if(p1.getY()<p2.getY())return -1;
return 1;
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 9e1a567d3e29cd9c6b2888ae8b526f10 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) {
InputReader fi = new InputReader(System.in);
int i,j,n,m1,m2;
n=fi.nextInt();
m1=fi.nextInt();
m2=((n)*(n-1)/2) - m1;
Graph train=new Graph(n,m1);
Graph bus=new Graph(n,m2);
for (i=1;i<=m1;i++){
train.addEdge(fi.nextInt(),fi.nextInt());
}
for (i=1;i<=n;i++){
for (j=1;j<=n;j++){
if (i!=j && !train.adj[i].contains(j))
bus.addEdge(i,j);
}
}
long busTime=train.Dijisktra(1);
long trainTime=bus.Dijisktra(1);
if (busTime==-1 || trainTime==-1)
System.out.println("-1");
else
System.out.println(Math.max(busTime,trainTime));
}
}
class Graph{
int n,m;
HashSet<Integer> adj[];
Graph(int n,int m){
this.n=n;
this.m=m;
adj=new HashSet[n+1];
for (int i=0;i<=n ;i++ ) {
adj[i]=new HashSet<>();
}
}
void addEdge(int i,int j){
adj[i].add(j);
adj[j].add(i);
}
long Dijisktra(int s)
{
PriorityQueue<Node> pq=new PriorityQueue<>();
long dis[]=new long[n+1];
boolean visit [] =new boolean[n+1];
Arrays.fill(dis, Long.MAX_VALUE);
pq.add(new Node(s,0));
dis[s]=0;
long ans=0;
while(!pq.isEmpty()){
Node temp=pq.peek();
pq.remove();
int vertex=temp.vertex;
Iterator <Integer> it=adj[vertex].iterator();
if(!visit[vertex]){
while(it.hasNext()){
Integer curr=it.next();
if (dis[curr] > dis[temp.vertex] + 1 ) {
dis[curr] = dis[temp.vertex] + 1;
pq.add(new Node(curr,dis[curr]));
}
}
}
visit[vertex]=true;
}
return dis[n]==Long.MAX_VALUE ?-1:dis[n];
}
}
class Node implements Comparable<Node>{
int vertex;
long cost;
Node(int vertex, long cost){
this.vertex = vertex; this.cost = cost;
}
public int compareTo(Node x){
return Long.compare(this.cost, x.cost);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n+1];
for (int i = 1; i <= n; i++)
a[i] = nextInt();
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 4067e8547edddc7859fa16254aa0e230 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.*;
import java.util.InputMismatchException;
public class cf_prac_bfs{
static long big=1000000007;
static boolean b[][];
static boolean check(int i,int n)
{
return (i>0 &&i<=n);
}
static void bfs(int dist[],int n,boolean aa)
{
boolean pushed[]=new boolean[n+1];boolean visited[]=new boolean[n+1];
pushed[1]=true; Queue<Integer> x = new LinkedList<Integer>();x.add(1);dist[1]=0;
outer : while(!x.isEmpty())
{
int xx=x.remove();visited[xx]=true;
for(int j=1;j<=n;j++)
{if(j!=xx && b[xx][j]==aa)
{
if(!pushed[j] && !visited[j])
{dist[j]=dist[xx]+1; if(j==n) break outer; x.add(j);pushed[j]=true;}}}
}
}
static int min(int a,int b)
{if(a<b) return a; else return b;}
public static void main(String args[]) {
InputReader in = new InputReader(System.in);
int n=in.readInt(),m=in.readInt();
b=new boolean[n+1][n+1];
for(int i=1;i<=m;i++)
{
int x=in.readInt(),y=in.readInt();
b[x][y]=true;b[y][x]=true;
}
int disra[]=new int[n+1];int disro[]=new int[n+1];
for(int i=1;i<=n;i++) { disra[i]=-1; disro[i]=-1;}
bfs(disra,n,true);
bfs(disro,n,false);
int min=Math.max(disra[n],disro[n]);
int min2=Math.min(disra[n],disro[n]);
if(min2==-1)
System.out.println(min2);
else
System.out.println(min);
}
static int recur(int disra[],int disro[],int i,int incre1,int incre2,int n)
{
if(i==n)
return Math.min(disra[i]+incre1,disro[i]+incre2);
if(disra[i]==disro[i])
return Math.min(recur(disra,disro,i+1,incre1+2,incre2,n),recur(disra,disro,i+1,incre1,incre2+2,n));
return recur(disra,disro,i+1,incre1,incre2,n);
}}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | cabf71460126b5d7b23426639c46e79f | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.*;
import java.io.*;
public class gfg {
static int n;
static int m;
static boolean[][] road;
static boolean[][] train;
static boolean[] visroad;
static boolean[] vistrain;
static int[] levelroad;
static int[] leveltrain;
static void solve()throws IOException{
n = Reader.nextInt();
m = Reader.nextInt();
train = new boolean[n+1][n+1];
leveltrain = new int[n+1];
vistrain = new boolean[n+1];
road = new boolean[n+1][n+1];
levelroad = new int[n+1];
visroad = new boolean[n+1];
Arrays.fill(leveltrain,10000000);
Arrays.fill(levelroad,10000000);
levelroad[1]=0;
leveltrain[1]=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)
road[i][j]=true;
}
for(int i=0;i<m;i++){
int a = Reader.nextInt();
int b = Reader.nextInt();
train[a][b]=true;
train[b][a]=true;
road[a][b]=false;
road[b][a]=false;
}
dfs_train();
dfs_road();
if(levelroad[n]==10000000 | leveltrain[n]==10000000)
System.out.println(-1);
else
System.out.println(Math.max(levelroad[n],leveltrain[n]));
}
static void dfs_train(){
//System.out.println(x+" "+par);
vistrain[1]=true;
Queue<Integer> q = new LinkedList<Integer>();
q.add(1);
while(q.size()>0){
int x = q.poll();
for(int i=1;i<=n;i++){
if(train[x][i] && !vistrain[i]){
leveltrain[i] = leveltrain[x]+1;
vistrain[i]=true;
q.add(i);
}
}
}
}
static void dfs_road(){
//System.out.println(x+" "+par);
visroad[1]=true;
Queue<Integer> q = new LinkedList<Integer>();
q.add(1);
while(q.size()>0){
int x = q.poll();
for(int i=1;i<=n;i++){
if(road[x][i] && !visroad[i]){
levelroad[i] = levelroad[x]+1;
//System.out.println(i+" "+leveltrain[i]);
visroad[i]=true;
q.add(i);
}
}
}
}
public static void main(String[] args) throws IOException{
Reader.init(System.in);
int t = 1;//Reader.nextInt();
while(t-->0){
solve();
}
}
// ggratest common divisor
static int gcd(int a , int b){
if(b==0)
return a;
else
return gcd(b,a%b);
}
// least common multiple
static int lcm(int a, int b){
return (a*b)/gcd(a,b);
}
// a^b
static long fastpow(long a, long n){
//System.out.println("ssdf");
if(n>0){
long half = fastpow(a,n/2);
if(n%2==0){
return half*half;
}
else
return a*half*half;
}
return 1;
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
class newcomparator implements Comparator<Integer>{
//@Override
public int compare(Integer a, Integer b){
return a<=b?1:-1;
}
}
class node {
int a;
long b;// cost to rreach\
node(int s,long va){
a=s;
b=va;
}
}
class mergesort{
static void sort(int l, int h, int[] arr){
if(l<h){
int mid = (l+h)/2;
sort(l,mid,arr);
sort(mid+1,h,arr);
merge(l,mid,h,arr);
}
}
static void merge(int l, int m , int h , int [] arr){
int[] left = new int[m-l+1];
int[] right = new int[h-m];
for(int i= 0 ;i< m-l+1;i++){
left[i] = arr[l+i];
}
for(int i=0;i<h-m;i++){
right[i] = arr[m+1+i];
}
//now left and right arrays are assumed to be sorted and we have tp merge them together
// int the original aaray.
int i=l;
int lindex = 0;
int rindex = 0;
while(lindex<m-l+1 && rindex<h-m){
if(left[lindex]<=right[rindex]){
arr[i]=left[lindex];
lindex++;
i++;
}
else{
arr[i]=right[rindex];
rindex++;
i++;
}
}
while(lindex<m-l+1){
arr[i]=left[lindex];
lindex++;
i++;
}
while(rindex<h-m){
arr[i]=right[rindex];
rindex++;
i++;
}
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 6dba0c7068107a9970e75c1c8b7a66ad | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import javax.swing.plaf.synth.SynthSpinnerUI;
public class Problem2 {
static Scanner sc=new Scanner(System.in);
static final double EPS = 1e-9;
static ArrayList<Integer> bus[];
static boolean railway[][];
public static void main(String[] args) throws IOException, InterruptedException {
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
int m=sc.nextInt();
bus=new ArrayList[n];
railway=new boolean[n][n];
for (int i = 0; i < n; i++) {
bus[i]=new ArrayList<>();
}
for (int i = 0; i <n; i++) {
for (int j = 0; j < n; j++) {
if(i!=j) {
bus[i].add(j);
bus[j].add(i);
}
}
}
n1=n;
while(m-->0) {
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
railway[u][v]=true;
railway[v][u]=true;
}
tdst=bfs(0,n-1,true);
if(tdst[n-1]==10000000) {
System.out.println(-1);
return;
}
int max1=tdst[n-1];
int bdst[]=bfs(0,n-1,false);
if(bdst[n-1]==10000000) {
System.out.println(-1);
return;
}
System.out.println(Math.max(bdst[n-1],max1));
}
static int n1;
static boolean visited[];
private static int[] tdst;
static int[] bfs(int s, int t,boolean type)
{
Queue<Integer> q = new LinkedList<Integer>();
q.add(0);
int dist[]=new int[n1];
Arrays.fill(dist,10000000);
dist[0]=0;
while(!q.isEmpty())
{
int u = q.remove();
if(u==t) {
break;
}
for(int v: bus[u]) {
if(!type&&tdst[v]==dist[u]+1) {
continue;
}
if(!type&&dist[v]==10000000&&!railway[u][v])
{
dist[v]=dist[u]+1;
q.add(v);
}
else if(dist[v]==10000000&&type&&railway[u][v]) {
dist[v]=dist[u]+1;
q.add(v);
}
}
}
return dist;
}
static final int INF = (int)1e9; //don't increase, avoid overflow
static ArrayList<Edge>[] edgejList;
/** static int dijkstra(int S, int T) //O(E log E)
{
int[] dist = new int[V];
Arrays.fill(dist, INF);
PriorityQueue<Edge> pq = new PriorityQueue<Edge>();
dist[S] = 0;
pq.add(new Edge(S, 0)); //may add more in case of MSSP (Mult-Source)
while(!pq.isEmpty())
{
Edge cur = pq.remove();
if(cur.node == T) //remove if all computations are needed
return dist[T];
if(cur.w > dist[cur.node]) //lazy deletion
continue;
for(Edge nxt: edgeList[cur.node])
if(cur.w + nxt.w < dist[nxt.node])
pq.add(new Edge(nxt.node, dist[nxt.node] = cur.w+ nxt.cost ));
}
return -1;
}**/
static Edge[] edgeList;
static int V;
static int kruskal() //O(E log E)
{
int mst = 0;
Arrays.sort(edgeList);
UnionFind uf = new UnionFind(V);
for(Edge e: edgeList)
if(uf.union(e.node, e.v))
mst += e.w;
return mst;
}
static class Edge implements Comparable<Edge>
{
int node, v, w;
Edge(int a, int b, int c) { node= a; v = b; w = c; }
public int compareTo(Edge e) { return w - e.w; }
}
static class UnionFind {
int[] p, rank;
UnionFind(int N)
{
p = new int[N];
rank = new int[N];
for (int i = 0; i < N; i++)
p[i] = i;
}
int findSet(int x) { return p[x] == x ? x : (p[x] = findSet(p[x])); }
boolean union(int x, int y)
{
x = findSet(x);
y = findSet(y);
if(x == y)
return false;
if (rank[x] > rank[y])
p[y] = x;
else
{
p[x] = y;
if(rank[x] == rank[y])
++rank[y];
}
return true;
}
}
static int numPF(int N)
{
int ans = 0, idx = 0, p = primes.get(0);
while(p * p <= N)
{
while(N % p == 0) { N /= p; ++ans; }
p = primes.get(++idx);
}
if(N != 1)
++ans;
return ans;
}
static ArrayList<Integer> div=new ArrayList<>();
static boolean Limit(int b, int e)
{
return b + EPS < Math.pow(2, 64.0 / e);
}
static int numDivs(int N)
{
int ans = 0;
for(int i = 1; i * i <= N; ++i)
if(N % i == 0)
{
++ans;
if(N / i != i)
++ans;
}
return ans;
}
static boolean isPrime(int N)
{
if(N <= 1e6)
return !isComposite[N];
for(int p: primes)
if(p * p > N)
break;
else if(N % p == 0)
return false;
return true;
}
static ArrayList<Integer> primes;
static TreeSet<Integer> primes1;
static HashMap<Integer,Integer> prime;
static boolean[] isComposite;
static int primus[]=new int[664579];
static void sieve(int N) // O(N log log N)
{
isComposite = new boolean[N+1];
isComposite[0] = isComposite[1] = true; // 0 indicates a prime number
primes = new ArrayList<Integer>();
primes1=new TreeSet<>();
int nxt = 0;
for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N))
if (isComposite[i] == false) //can loop in 2 and odd integers for slightly better performance
{
primes.add(i);
primes1.add(i);
primus[nxt++] = i;
if(1l * i * i <= N)
for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve
isComposite[j] = true;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public long[] nextLongArr(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {Thread.sleep(2000);}
}
}
class Dsu {
int[] p, rank, setSize;
int numSets;
public Dsu(int N)
{
numSets = N;
p = new int[N];
rank = new int[N];
setSize = new int[N];
Arrays.fill(setSize, 1);
for (int i = 0; i < N; i++)
p[i] = i;
}
public int findSet(int v) {
if (v == p[v])
return v;
return findSet(p[v]);
}
public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }
public void unionSet(int i, int j)
{
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if(setSize[x] > setSize[y]) {
p[y] = x;
setSize[x] += setSize[y];
}
else
{ p[x] = y;
setSize[y] += setSize[x];
}
}
public int numDisjointSets() { return numSets; }
public int sizeOfSet(int i) { return setSize[findSet(i)]; }
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | e6f0fcf4a74582e3fb356a2f6a142534 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import javafx.util.Pair;
/**
*
* @author Public
*/
public class TheTwoRoutes601A {
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
int t=Integer.parseInt(st.nextToken());
int rt=Integer.parseInt(st.nextToken());
LinkedList rail[]=new LinkedList[t+1];
LinkedList road[]=new LinkedList[t+1];
for(int i=0;i<=t;i++){
rail[i]=new LinkedList();
road[i]=new LinkedList();
}
for(int i=1;i<=rt;i++){
StringTokenizer st1=new StringTokenizer(br.readLine());
int x=Integer.parseInt(st1.nextToken());
int y=Integer.parseInt(st1.nextToken());
rail[x].add(y);
rail[y].add(x);
}
for(int i=1;i<=t;i++){
for(int j=1;j<=t;j++){
if(i!=j){
if(!rail[i].contains(j))
road[i].add(j);
}
}
}
boolean visited[]=new boolean[t+1];
Queue<Pair<Integer,Integer>> q=new LinkedList<Pair<Integer,Integer>>();
if(rail[1].contains(t)){
q.add(new Pair(1,0));
visited[0]=true;
while(!q.isEmpty()){
Pair p=q.poll();
if((int)p.getKey()==t){
System.out.println(p.getValue());
return;
}
int v=(int)p.getKey();
Iterator i=road[v].listIterator();
while(i.hasNext()){
int k=(int)i.next();
if(visited[k]!=true){
visited[k]=true;
q.add(new Pair(k,(int)p.getValue()+1));
}
}
}
}
else{
q.add(new Pair(1,0));
visited[0]=true;
while(!q.isEmpty()){
Pair p=q.poll();
if((int)p.getKey()==t){
System.out.println(p.getValue());
return;
}
int v=(int)p.getKey();
Iterator i=rail[v].listIterator();
while(i.hasNext()){
int k=(int)i.next();
if(visited[k]!=true){
visited[k]=true;
q.add(new Pair(k,(int)p.getValue()+1));
}
}
}
}
System.out.println(-1);
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | cd3b4c4ba74070e8ead71652f8badca1 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | //package codeforces.Round333;
import java.util.LinkedList;
import java.util.Scanner;
public class TheTwoRoutes {
private static int n;
private static boolean[][] adj;
private static int bfs(boolean edge) {
int[] distance = new int[n];
boolean[] visited = new boolean[n];
LinkedList<Pair> queue = new LinkedList<>();
queue.add(new Pair(0, 0));
while (!queue.isEmpty()) {
Pair p = queue.pollFirst();
if (visited[p.node]) continue;
visited[p.node] = true;
distance[p.node] = p.distance;
for (int i = 0; i < n; i++) {
if (adj[p.node][i] == edge) queue.add(new Pair(i, p.distance + 1));
}
}
return distance[n - 1];
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
n = s.nextInt();
adj = new boolean[n][n];
int m = s.nextInt();
for (int i = 0; i < m; i++) {
int from = s.nextInt() - 1;
int to = s.nextInt() - 1;
adj[from][to] = true;
adj[to][from] = true;
}
int train = bfs(true);
int bus = bfs(false);
int distance = Math.max(train, bus);
if (distance == 1) System.out.println("-1");
else System.out.println(distance);
}
static class Pair {
int distance;
int node;
Pair(int node, int distance) {
this.distance = distance;
this.node = node;
}
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 50b095bb03fa6116662e084fa0cc0c80 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int graph[][];
static int target;
static boolean vis[];
static boolean flag = false;
static int point = 1;
// public static int dfs1(int node) {
// vis[node] = true;
// if (node == target) {
// flag = true;
// return 0;
// }
// int min1 = 100000;
//
// for (int i = 1; i < graph[node].length; i++) {
// if (graph[node][i] == point && !vis[i]) {
// min1 = Math.min(min1, 1 + dfs1(i));
// vis[i] = false;
// }
// }
//
// return min1;
// }
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader scanner = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n = scanner.nextInt();
int m = scanner.nextInt();
graph = new int[n + 1][n + 1];
vis = new boolean[n + 1];
target = n;
for (int i = 0; i < m; i++) {
int a = scanner.nextInt();
int b = scanner.nextInt();
graph[a][b] = graph[b][a] = 1;
}
if (graph[1][n] == 1) {
point = 0;
}
Queue<pair> q = new LinkedList<>();
q.add(new pair(1, 0));
int res = -1;
while (!q.isEmpty()) {
pair cur = q.poll();
if (cur.node == target) {
res = cur.cost;
break;
}
if (vis[cur.node]) {
continue;
}
vis[cur.node] = true;
for (int i = 1; i < graph.length; i++) {
if (graph[cur.node][i] == point) {
q.add(new pair(i, cur.cost + 1));
}
}
}
out.println(res);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
class pair {
int node;
int cost;
public pair(int node, int cost) {
this.node = node;
this.cost = cost;
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | dd9aecdcaa8e18638b4b83a4c6a144e5 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class A {
public static boolean[][] adj;
public static int n;
public static int bfs(int vertex,boolean edge) {
ArrayDeque<Integer> stack = new ArrayDeque<>();
int[] cost = new int[n];
Arrays.fill(cost, Integer.MAX_VALUE);
cost[vertex] = 0;
stack.add(vertex);
while(!stack.isEmpty()) {
int curVer = stack.poll();
for(int i=0;i<n;i++) {
if(adj[curVer][i]==edge && cost[i]>cost[curVer]+1) {
cost[i] = cost[curVer]+1;
stack.add(i);
}
}
}
return cost[n-1];
}
public static void main(String[] args) {
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
n = in.nextInt();
int m = in.nextInt();
adj = new boolean[n][n];
for(int i=0;i<m;i++) {
int u = in.nextInt(),v = in.nextInt();
u--;
v--;
adj[u][v] = true;
adj[v][u] = true;
}
int ans = Math.max(bfs(0,true),bfs(0,false));
System.out.println(ans==Integer.MAX_VALUE?-1:ans);
}
static final Random random=new Random();
// static void ruffleSort(Pair[] a) {
// int n=a.length;//shuffle, then sort
// for (int i=0; i<n; i++) {
// int oi=random.nextInt(n);
// Pair temp=a[oi];
// a[oi]=a[i]; a[i]=temp;
// }
// Arrays.sort(a);
// }
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(char[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
char temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
}
}
//class Pair implements Comparable<Pair>{
// int a;
// int b;
// public Pair(int a, int b) {
// this.a = a;
// this.b = b;
// }
// public int compareTo(Pair o) {
// if(this.a==o.a)
// return this.b - o.b;
// return this.a - o.a;
// }
//} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 52ef8c5c59798ef24f3f6113ba40ef4b | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes |
import javax.print.DocFlavor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.nio.charset.IllegalCharsetNameException;
import java.time.temporal.Temporal;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
public class Main{
public static void main(String[] args) throws IOException{
Reader.init(System.in);
// int t =Reader.nextInt();
int t = 1;
int i = 1;
while (t-->0){
// System.out.print("Case #" + i + ": ");
solve();
i++;
}
}
static int[][] graph1;
static int[][] graph2;
static int[] d1;
static int[] d2;
static int n;
static void solve() throws IOException{
n = Reader.nextInt();
int m = Reader.nextInt();
graph1 = new int[n+1][n+1];
graph2 = new int[n+1][n+1];
for (int i = 0 ; i <= n ; i++){
for (int j = 0 ; j <= n ; j++){
graph1[i][j] = 1;
}
}
for (int i = 0; i < m ; i++){
int n1 = Reader.nextInt();
int n2 = Reader.nextInt();
graph1[n1][n2] = 0;
graph1[n2][n1] = 0;
graph2[n1][n2] = 1;
graph2[n2][n1] = 1;
}
int n1 = bfs1(graph1);
int n2 = bfs1(graph2);
if (n1==-1 || n2==-1){
System.out.println(-1);
}
else{
System.out.println(Math.max(n1,n2));
}
}
static int bfs1(int[][] input){
int[][] graph = input;
d1 = new int[n+1];
boolean[] v = new boolean[n+1];
Arrays.fill(d1,-1);
Deque<Integer> q = new LinkedList<>();
d1[1] = 0;
q.addLast(1);
v[1] = true;
while (q.isEmpty()==false){
int s = q.removeFirst();
for (int i = 1; i <= n ; i++){
if (!v[i] && graph[s][i]==1){
d1[i] = d1[s] + 1;
q.addLast(i);
v[i] = true;
}
}
}
return d1[n];
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static int stringCompare(String str1, String str2)
{
int l1 = str1.length();
int l2 = str2.length();
int lmin = Math.min(l1, l2);
for (int i = 0; i < lmin; i++) {
int str1_ch = (int)str1.charAt(i);
int str2_ch = (int)str2.charAt(i);
if (str1_ch != str2_ch) {
return str1_ch - str2_ch;
}
}
if (l1 != l2) {
return l1 - l2;
}
else {
return 0;
}
}
static int next(long[] arr, long target)
{
int start = 0, end = arr.length - 1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] <= target) {
start = mid + 1;
}
else {
ans = mid;
end = mid - 1;
}
}
return ans;
}
// static int find(int x) {
// return parent[x] == x ? x : (parent[x] = find(parent[x]));
// }
// static boolean merge(int x, int y) {
// x = find(x);
// y = find(y);
// if (x==y){
// return false;
// }
// parent[x] = y;
// return true;
// }
public static void sortbyColumn(int arr[][], int col)
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
class Pair{
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
}
class Node implements Comparable<Node>{
int a;
int b;
Node (int a , int b){
this.a = a;
this.b = b;
}
public int compareTo(Node o) {
if ((this.a%2) == (o.a%2)){
return (this.b - o.b);
}
else{
return this.a - o.a;
}
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | e3165febb38ecf3b3b8431a6ec1bc0af | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.Scanner;
public class Main {
private final static int INF = 1000000005;
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
String in = input.nextLine();
String[] to = in.split(" ");
int n = Integer.parseInt(to[0]);
int r = Integer.parseInt(to[1]);
int[][] rT = new int[n][n];
int[][] cT = new int[n][n];
//init tables to 0;
for(int i = 0; i< n; i++){
for(int j = 0; j < n; j++){
cT[i][j] = 1;
rT[i][j] = INF;
}
}
for(int i = 0; i < r; i++){
in = input.nextLine();
to = in.split(" ");
int a = Integer.parseInt(to[0]) - 1;
int b = Integer.parseInt(to[1]) - 1;
rT[a][b] = 1;
rT[b][a] = 1;
cT[a][b] = INF;
cT[b][a] = INF;
}
//apsh this
apsh(rT);
apsh(cT);
//double flood fill gogogo
System.out.println(solve(rT, cT, 0, n - 1));
}
private static void apsh(int[][] rT) {
for(int k = 0; k < rT.length; k++){
for(int i = 0; i < rT.length; i++){
for(int j = 0; j < rT.length; j++){
if(rT[i][j] > rT[i][k] + rT[k][j]){
rT[i][j] = rT[i][k] + rT[k][j];
}
}
}
}
}
private static int solve(int[][] rT, int[][] cT, int curr, int dest) {
//if not reachable, return
if(rT[curr][dest] >= INF || cT[curr][dest] >= INF){
return -1;
} else {
return Math.max(rT[curr][dest], cT[curr][dest]);
}
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 6e5da6b23d1c2ea250337c05300b9a6d | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class A601 {
static char[] sarr;
public static void main(String[] args) throws IOException {
FastScanner fs=new FastScanner();
PrintWriter out = new PrintWriter(System.out);
// int T = 1;
// int T=fs.nextInt();
// for (int tt=0; tt<T; tt++) {
// }
int n = fs.nextInt();
int m = fs.nextInt();
List<HashSet<Integer>> rails = new ArrayList();
List<List<Integer>> roads = new ArrayList();
for (int i=0; i<n; i++) {
rails.add(new HashSet());
roads.add(new ArrayList());
}
boolean directRails=false;
for (int i=0; i<m; i++) {
int x = fs.nextInt()-1;
int y = fs.nextInt()-1;
rails.get(x).add(y);
rails.get(y).add(x);
if ((y==n-1 && x==0) || (x==n-1 && y==0)) {
directRails=true;
}
}
boolean existsRoad=false;
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
if (i==j) {
continue;
}
if (!rails.get(i).contains(j)) {
roads.get(i).add(j);
existsRoad=true;
}
}
}
boolean reached = false;
if (!existsRoad) {
out.println(-1);
}
else {
if (directRails) {
Queue<Integer> q=new LinkedList();
q.offer(0);
boolean[] vis = new boolean[n];
vis[0]=true;
int t=0;
outer:while (!q.isEmpty()) {
int size = q.size();
for (int i=0; i<size; i++) {
int cur = q.poll();
if (cur==n-1) {
reached=true;
break outer;
}
for (int neigh: roads.get(cur)) {
if (!vis[neigh]) {
vis[neigh]=true;
q.offer(neigh);
}
}
}
t++;
}
if (reached) {
out.println(t);
}
else
out.println(-1);
}
else {
Queue<Integer> q=new LinkedList();
q.offer(0);
boolean[] vis = new boolean[n];
vis[0]=true;
int t=0;
outer: while (!q.isEmpty()) {
int size = q.size();
for (int i=0; i<size; i++) {
int cur = q.poll();
if (cur==n-1) {
reached=true;
break outer;
}
for (int neigh: rails.get(cur)) {
if (!vis[neigh]) {
vis[neigh]=true;
q.offer(neigh);
}
}
}
t++;
}
if (reached) {
out.println(t);
}
else
out.println(-1);
}
}
out.close();
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 52249b66239ed872a00a302975de0494 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.*;
public class TheTwoRoutes {
static int n, m;
static List<Integer>[] rail;
static int[] vis;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
rail = (List<Integer>[]) (new List[n]);
vis = new int[n];
for(int i = 0; i < n; ++i) rail[i] = new ArrayList<>();
for(int i = 0; i < m; ++i) {
int a = sc.nextInt();
int b = sc.nextInt();
a--;
b--;
rail[a].add(b);
rail[b].add(a);
}
int mx1 = sol(rail);
vis = new int[n];
List<Integer>[] bus = (List<Integer>[]) (new List[n]);
for(int i = 0; i < n; ++i) bus[i] = new ArrayList<>();
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j)
if(i != j) {
if(!rail[i].contains(j) && !bus[i].contains(j)) {
bus[i].add(j);
bus[j].add(i);
}
}
}
int mx2 = sol(bus);
//System.out.println(mx1 + " " + mx2);
if(mx1 == -1 || mx2 == -1) System.out.println(-1);
else System.out.println(Math.max(mx1, mx2));
}
private static int sol(List<Integer>[] list) {
if(list[0].size() == 0) return -1;
PriorityQueue<Node> q = new PriorityQueue<>(Comparator.comparingInt(a -> a.cost));
q.add(new Node(0, 0));
vis[0] = 1;
while(!q.isEmpty()) {
Node root = q.remove();
if(root.idx == n - 1) return root.cost;
for(Integer nbr : list[root.idx]) {
if(vis[nbr] == 0) q.add(new Node(nbr, root.cost + 1));
vis[nbr] = 1;
}
}
return -1;
}
private static class Node {
int idx;
int cost;
public Node(int idx, int cost) {
this.idx = idx;
this.cost = cost;
}
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 64a59becf5b082a2017e2a7a9859054f | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.*;
public class TheTwoRoutes {
static int n, m;
static List<Integer>[] rail;
static int[] vis;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
rail = (List<Integer>[]) (new List[n]);
vis = new int[n];
for(int i = 0; i < n; ++i) rail[i] = new ArrayList<>();
for(int i = 0; i < m; ++i) {
int a = sc.nextInt();
int b = sc.nextInt();
a--;
b--;
rail[a].add(b);
rail[b].add(a);
}
int mx1 = 0;
if(rail[0].contains(n - 1)) mx1 = 1;
else mx1 = sol(rail);
vis = new int[n];
List<Integer>[] bus = (List<Integer>[]) (new List[n]);
for(int i = 0; i < n; ++i) bus[i] = new ArrayList<>();
int mx2 = 0;
if(!rail[0].contains(n - 1)) mx2 = 1;
else {
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j)
if(i != j) {
if(!rail[i].contains(j) && !bus[i].contains(j)) {
bus[i].add(j);
bus[j].add(i);
}
}
}
mx2 = sol(bus);
}
//System.out.println(mx1 + " " + mx2);
if(mx1 == -1 || mx2 == -1) System.out.println(-1);
else System.out.println(Math.max(mx1, mx2));
}
private static int sol(List<Integer>[] list) {
if(list[0].size() == 0) return -1;
Queue<Node> q = new LinkedList<>();
q.add(new Node(0, 0));
vis[0] = 1;
while(!q.isEmpty()) {
Node root = q.remove();
if(root.idx == n - 1) return root.cost;
for(Integer nbr : list[root.idx]) {
if(vis[nbr] == 0) q.add(new Node(nbr, root.cost + 1));
vis[nbr] = 1;
}
}
return -1;
}
private static class Node {
int idx;
int cost;
public Node(int idx, int cost) {
this.idx = idx;
this.cost = cost;
}
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | e9c9df1a95569cefef8a6dab3c6ebb65 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){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 long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){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 double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
}
///////////////////////////////////////////////////////////////////////////////////////////
// RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL //
// RR RRR AAAAA HHH HHH IIIIIIIIIII LLL //
// RR RRR AAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHHHHHHHHHH III LLL //
// RRRRRR AAA AAA HHHHHHHHHHH III LLL //
// RR RRR AAAAAAAAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL //
///////////////////////////////////////////////////////////////////////////////////////////
static int n;
static int m;
static int mark[];
public static void bfs(int edges[][], int u,int v)
{
int visited[]=new int[n];Arrays.fill(visited,-1);
int distance[]=new int[n];
Queue<Integer> Q = new LinkedList<>();
Q.add(u);
visited[u]=1;
while (!Q.isEmpty())
{
int x = Q.remove();
for (int i=0; i<n; i++)
{
if(edges[x][i]==0)
continue;
if (visited[i]==1)continue;
distance[i]= distance[x]+1;
Q.add(i);
visited[i]= 1;
}
}
int val=distance[v]!=0?distance[v]:-1;
System.out.println(val);
}
public static void main(String[] args)throws IOException
{
PrintStream out= new PrintStream(System.out);
Reader sc=new Reader();
n=sc.i();
m=sc.i();
int bustrain=0;
int arr[][]=new int[n][n];
int brr[][]=new int[n][n];
for(int i=0;i<m;i++)
{
int a=sc.i();int b=sc.i();
a--;b--;
arr[a][b]=1;arr[b][a]=1;
if(a==0&&b==n-1||a==n-1&&b==0)
bustrain=1;
}
for(int i=0;i<n;i++) for(int j=0;j<n;j++) if(arr[i][j]==0)brr[i][j]=1;
if(bustrain==1)bfs(brr,0,n-1);
else bfs(arr,0,n-1);
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | d9dd56416a7d6393b94107e76da10684 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.io.*;
import java.util.*;
public class A601
{
static int dp[][];
static void bfs(int adj[][],int n,int r)
{
Queue<Integer> qu=new LinkedList<>();
qu.add(1);
boolean vis[]=new boolean[n+1];
vis[1]=true;
if(r==0)
{
dp[0][1]=0;
while(qu.size()!=0)
{
int a=qu.poll();
for(int i=1;i<=n;i++)
{
if(adj[a][i]==1 && !vis[i])
{
dp[0][i]=(int)Math.min(dp[0][i],1+dp[0][a]);
//System.out.println(i+" "+a+" "+dp[0][i]);
vis[i]=true;
qu.add(i);
}
}
}
}
else
{
dp[1][1]=0;
while(qu.size()!=0)
{
int a=qu.poll();
//System.out.println(a);
for(int i=1;i<=n;i++)
{
if(adj[a][i]==1 && !vis[i])
{
// System.out.println(i+" "+a);
if(1+dp[1][a] == dp[0][i])
dp[1][i]=2+dp[1][a];
else
dp[1][i]=1+dp[1][a];
//System.out.println(i+" "+a+" "+dp[1][i]);
vis[i]=true;
qu.add(i);
}
}
}
}
}
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int adj1[][]=new int[n+1][n+1];
int adj2[][]=new int[n+1][n+1];
dp=new int[2][n+1];
for(int i=1;i<=n;i++)
{
adj1[i][i]=adj2[i][i]=1;
dp[0][i]=dp[1][i]=Integer.MAX_VALUE;
}
for(int i=1;i<=m;i++)
{
int x=sc.nextInt();
int y=sc.nextInt();
adj1[x][y]=adj1[y][x]=1;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(adj1[i][j]==0)
adj2[i][j]=1;
}
}
dp[0][1]=dp[1][1]=0;
bfs(adj1,n,0);
bfs(adj2,n,1);
for(int i=1;i<=n;i++)
{
//System.out.println(dp[0][i]+" "+dp[1][i]);
}
if(dp[0][n]==Integer.MAX_VALUE || dp[1][n]==Integer.MAX_VALUE)
{
System.out.println(-1);
}
else
System.out.println((int)Math.max(dp[0][n],dp[1][n]));
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | aee21bb80f1a887ac3b463bfe2d45dab | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class A601 {
public static void main(String[] args) throws IOException{
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
String[] s1 = inp.readLine().split(" ");
int n = Integer.parseInt(s1[0]);
int trainEdges = Integer.parseInt(s1[1]);
GraphA601 graph = new GraphA601(n);
boolean trainConnected = false;
for(int i=0;i<trainEdges;i++){
String[] s2 = inp.readLine().split(" ");
int a = Integer.parseInt(s2[0]);
int b = Integer.parseInt(s2[1]);
if((a==1 && b==n) ||( a==n && b==1)){
trainConnected = true;
}
graph.addEdge(a,b);
}
if(trainConnected){
GraphA601 graphRoad = graph.graphComplement();
graphRoad.BFS(1);
//System.out.println("sss");
}
else{
graph.BFS(1);
}
}
}
class GraphA601{
int vertices;
ArrayList<Integer> edge[];
Map<Integer,Integer> parent;
Map<Integer,Integer> minDist;
GraphA601(int vertices){
this.vertices = vertices;
edge = new ArrayList[vertices+1];
parent = new HashMap<>();
minDist = new HashMap<>();
for(int i=0;i<=vertices;i++){
edge[i] = new ArrayList<>();
parent.put(i,-1);
minDist.put(i,-1);
}
}
void addEdge(int a,int b){
edge[a].add(b);
edge[b].add(a);
}
GraphA601 graphComplement(){
for(int i=0;i<=vertices;i++){
Collections.sort(edge[i]);
}
GraphA601 graph = new GraphA601(vertices);
for(int i=1;i<=vertices;i++){
int count = 0;
for(int j=1;j<=vertices;j++){
if(i!=j) {
if (count < edge[i].size()) {
if (edge[i].get(count) == j) {
count++;
} else {
graph.addEdge(i, j);
}
} else {
graph.addEdge(i, j);
}
}
}
}
return graph;
}
int BFS(int v){
parent.put(v,0);
minDist.put(v,0);
boolean[] visited = new boolean[vertices+1];
Queue<Integer> queue = new ArrayDeque<>();
queue.add(v);
while (queue.size()>0){
int s = queue.poll();
Iterator<Integer> iterator = edge[s].listIterator();
while (iterator.hasNext()) {
int n = iterator.next();
if(!visited[n]) {
visited[n] = true;
parent.put(n,s);
minDist.put(n,minDist.get(s)+1);
queue.add(n);
}
}
}
System.out.println(minDist.get(vertices));
return minDist.get(vertices);
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 4339c54d32ea1e94ecaf7a799dcae30f | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.*;
public class A573
{
static int n;
static boolean[][] rails;
public static void main( String[] args )
{
Scanner in = new Scanner( System.in );
n = in.nextInt();
int m = in.nextInt();
rails = new boolean[n + 1][n + 1];
for ( int i = 0; i < m; i++ )
{
int u = in.nextInt(), v = in.nextInt();
rails[u][v] = true;
rails[v][u] = true;
}
if ( rails[1][n] )
System.out.println( dfs( false ) );
else
System.out.println( dfs( true ) );
in.close();
System.exit( 0 );
}
public static int dfs( boolean rail )
{
LinkedList<vertex> q = new LinkedList<vertex>();
q.add( new vertex( 1, 0 ) );
boolean[] visit = new boolean[n + 1];
while ( !q.isEmpty() )
{
vertex v = q.removeFirst();
if ( rails[v.index][n] == rail )
return v.dist + 1;
visit[v.index] = true;
for ( int i = 1; i <= n; i++ )
if ( !visit[i] && rails[v.index][i] == rail )
q.add( new vertex( i, v.dist + 1 ) );
}
return -1;
}
}
class vertex
{
int index, dist;
public vertex( int index, int dist )
{
this.index = index;
this.dist = dist;
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 91c6c087f934f4cf5dd7759d4e526a60 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.io.*;
import java.util.*;
public final class TwoRoutes {
static class Stop {
int t;
int d;
Stop(int t, int d) { this.t = t; this.d = d; }
}
static int n;
static boolean[][] rail;
static boolean[] visited;
static int bfs(boolean isRail) {
// System.out.println("Visiting " + town);
Queue<Stop> stops = new LinkedList<Stop>();
stops.add(new Stop(1, 0));
visited[1] = true;
while (!stops.isEmpty()) {
Stop s = stops.poll();
if (s.t == n) {
return s.d;
}
// System.out.println(i + ": " + rail[town][i] + ", " + visited[i]);
for (int i = 1; i <= n; i++) {
if (s.t == i) continue;
if (rail[s.t][i] == isRail && !visited[i]) {
visited[i] = true;
stops.add(new Stop(i, s.d + 1));
}
}
}
return -1;
}
public static void main (String[] args) throws java.lang.Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(reader.readLine(), " ");
n=Integer.parseInt(st.nextToken());
int m=Integer.parseInt(st.nextToken());
rail = new boolean[n+1][n+1];
while (m-- > 0) {
st = new StringTokenizer(reader.readLine(), " ");
int r=Integer.parseInt(st.nextToken()), c=Integer.parseInt(st.nextToken());
rail[r][c] = true;
rail[c][r] = true;
}
visited = new boolean[n+1];
int d;
if (rail[1][n])
d = bfs(false);
else
d = bfs(true);
System.out.println(d);
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | a7b9d749c8802e760906d7ff10217c29 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class CF601A {
static int N;
static int M;
static boolean[][] roads;
static int[] visited;
static Queue<Integer> Q;
public static void main(String[] args) {
/*
for(int i = 2; i < 401; i++) {
System.out.println((i-1) + " " + i);
}
*/
Scanner S = new Scanner(System.in);
N = S.nextInt();
M = S.nextInt();
roads = new boolean[N+1][N+1];
for(int m = 0; m < M; m++) {
int X = S.nextInt();
int Y = S.nextInt();
roads[X][Y] = true;
roads[Y][X] = true;
}
/*
for(int x = 1; x < N+1; x++) {
for(int y = 1; y < N+1; y++) {
System.out.print(roads[x][y] + " ");
}
System.out.println("");
}
*/
Q = new LinkedList<Integer>();
Q.add(1);
visited = new int[N+1];
visited[1] = 1;
int railway = bfs(true);
visited = new int[N+1];
visited[1] = 1;
Q = new LinkedList<Integer>();
Q.add(1);
int roadway = bfs(false);
if(railway == -1 || roadway == -1) {
System.out.println(-1);
}
else {
System.out.println(Math.max(railway,roadway)-1);
}
}
public static int bfs(boolean road) {
while(!Q.isEmpty()) {
int cur = Q.remove();
//System.out.println(cur + " " + visited[cur]);
if(cur == N) {
return visited[cur];
}
else {
for(int i = 1; i < N+1; i++) {
if(roads[cur][i] == road) {
if(visited[i] == 0) {
//System.out.println(i);
Q.add(i);
visited[i] = visited[cur] + 1;
}
}
}
}
}
return -1;
}
/*
public static int dfs(int town, boolean road) {
if(town == N) {
return 0;
}
else if(visited[town] == false) {
visited[town] = true;
int min = -1;
for(int i = 1; i < N+1; i++) {
if(roads[town][i] == road) {
int cur = dfs(i, road);
if(cur != -1 && (cur < min || min == -1)) {
min = cur;
}
//System.out.println(town + " " + i + " " + road + " " + cur);
}
}
if(min != -1) {
min = min + 1;
}
visited[town] = false;
return min;
}
return -1;
}
*/
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 49bd9426ebb4cb0dcf53b8aac23993ed | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.*;
public class the_two_routes
{
static int n;
static boolean[][] rails;
public static void main( String[] args )
{
Scanner in = new Scanner( System.in );
n = in.nextInt();
int m = in.nextInt();
rails = new boolean[n + 1][n + 1];
for ( int i = 0; i < m; i++ )
{
int u = in.nextInt(), v = in.nextInt();
rails[u][v] = true;
rails[v][u] = true;
}
if ( rails[1][n] )
System.out.println( dfs( false ) );
else
System.out.println( dfs( true ) );
in.close();
System.exit( 0 );
}
public static int dfs( boolean rail )
{
LinkedList<vertex> q = new LinkedList<vertex>();
q.add( new vertex( 1, 0 ) );
boolean[] visit = new boolean[n + 1];
while ( !q.isEmpty() )
{
vertex v = q.removeFirst();
if ( rails[v.index][n] == rail )
return v.dist + 1;
visit[v.index] = true;
for ( int i = 1; i <= n; i++ )
if ( !visit[i] && rails[v.index][i] == rail )
q.add( new vertex( i, v.dist + 1 ) );
}
return -1;
}
}
class vertex
{
int index, dist;
public vertex( int index, int dist )
{
this.index = index;
this.dist = dist;
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 3f76c419360c68e430802cf5f1cb320d | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.Scanner;
public class Main {
public static int floyd(int[][] tmp,int n) {
for(int k = 1;k <= n;k++) {
for(int i = 1;i <= n;i++) {
for(int j = 1;j <= n;j++) {
//中间点和起点或者终点都不可连
if(tmp[i][k] == 0 || tmp[k][j] == 0)
continue;
//如果起点和终点不可连,那么一定更新
if(tmp[i][j] == 0)
tmp[i][j] = tmp[i][k] + tmp[k][j];
tmp[i][j] = Math.min(tmp[i][j],tmp[i][k] + tmp[k][j]);
}
}
}
return tmp[1][n];
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int m = cin.nextInt();
int[][] huo = new int[n + 1][n + 1];
int[][] qi = new int[n + 1][n + 1];
for(int i = 0;i < m;i++) {
int a = cin.nextInt();
int b = cin.nextInt();
huo[a][b] = huo[b][a] = 1;
}
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
qi[i][j] = 1 - huo[i][j];
int res;
if(huo[1][n] == 1) //火车从1直达n
//汽车floyd
res = floyd(qi,n);
else //汽车1直达n
//火车floyd
res = floyd(huo,n);
if(res == 0)
System.out.println(-1);
else
System.out.println(res);
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | c73d4602d89577c979a5b53414fa1f6a | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.Scanner;
public class Main {
public static int floyd(int[][] tmp,int n) {
for(int k = 1;k <= n;k++) {
for(int i = 1;i <= n;i++) {
for(int j = 1;j <= n;j++) {
//中间点和起点或者终点都不可连
if(tmp[i][k] == 0 || tmp[k][j] == 0)
continue;
//如果起点和终点不可连,那么一定更新
if(tmp[i][j] == 0)
tmp[i][j] = tmp[i][k] + tmp[k][j];
tmp[i][j] = Math.min(tmp[i][j],tmp[i][k] + tmp[k][j]);
}
}
}
return tmp[1][n];
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int m = cin.nextInt();
int res;
int[][] huo = new int[n + 1][n + 1];
int[][] qi = new int[n + 1][n + 1];
for(int i = 0;i < m;i++) {
int a = cin.nextInt();
int b = cin.nextInt();
huo[a][b] = huo[b][a] = 1;
}
if(huo[1][n] == 1) {//火车从1直达n
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
qi[i][j] = 1 - huo[i][j];
//汽车floyd
res = floyd(qi,n);
} else //汽车1直达n
//火车floyd
res = floyd(huo,n);
if(res == 0)
System.out.println(-1);
else
System.out.println(res);
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 773e287423e4c6f2f6e4450f0807d36f | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.*;
public class TheTwoRoutes {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
Set<Integer>[] railAdj = new Set[n+1];
Set<Integer>[] roadAdj = new Set[n+1];
for(int i = 0; i <= n; i++) {
railAdj[i] = new HashSet<>();
roadAdj[i] = new HashSet<>();
}
int m = s.nextInt();
for(int i = 1; i <= m; i++) {
int u = s.nextInt();
int v = s.nextInt();
railAdj[u].add(v);
railAdj[v].add(u);
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(i != j && !railAdj[i].contains(j))
roadAdj[i].add(j);
}
}
Queue<Integer> q = new LinkedList<>();
q.offer(1);
int railDist[] = new int[n+1];
int roadDist[] = new int[n+1];
railDist[1] = 0;
roadDist[1] = 0;
Set<Integer> seen = new HashSet<>();
seen.add(1);
boolean routeFound = false;
while (!q.isEmpty()) {
int curr = q.poll();
for(int next : railAdj[curr]) {
if(next == n) {
routeFound = true;
}
if(seen.add(next)) {
railDist[next] = 1 + railDist[curr];
q.offer(next);
}
}
}
if(!routeFound) {
System.out.println(-1);
return;
}
q.offer(1);
seen.clear();
seen.add(1);
while(!q.isEmpty()) {
int curr = q.poll();
for(int next : roadAdj[curr]) {
if(next == n) {
System.out.println(Math.max(railDist[next], 1 + roadDist[curr]));
return;
}
if(railDist[next] != 1 + roadDist[curr] && seen.add(next)) {
roadDist[next] = 1 + roadDist[curr];
q.offer(next);
}
}
}
System.out.println("-1");
}
}
| Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 12d17fc139ad4cfd079134e106db86d0 | train_002.jsonl | 1448382900 | In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. | 256 megabytes | import java.util.*;
public class Main11233 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] V = new int[n+1][n+1];
for (int i = 1; i <= m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
V[a][b] = 1;
V[b][a] = 1;
}
int[] D = new int[n+1];
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(1);
while (!queue.isEmpty()) {
int vertex = queue.poll();
for (int i = 2; i <= n; i++) {
if (D[i] == 0 && V[vertex][i] != V[1][n]) {
D[i] = D[vertex] + 1;
queue.add(i);
}
}
}
if (D[n] == 0) D[n] = -1;
System.out.print(D[n]);
}
} | Java | ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. | Java 8 | standard input | [
"shortest paths",
"graphs"
] | fbfc333ad4b0a750f654a00be84aea67 | The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. | 1,600 | Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. | standard output | |
PASSED | 4be9d0a66da44eb75b5d4d1990082b07 | train_002.jsonl | 1561905900 | Vasya has an array $$$a_1, a_2, \dots, a_n$$$.You don't know this array, but he told you $$$m$$$ facts about this array. The $$$i$$$-th fact is a triple of numbers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$) and it means: if $$$t_i=1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is sorted in non-decreasing order; if $$$t_i=0$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter. For example if $$$a = [2, 1, 1, 3, 2]$$$ then he could give you three facts: $$$t_1=1, l_1=2, r_1=4$$$ (the subarray $$$[a_2, a_3, a_4] = [1, 1, 3]$$$ is sorted), $$$t_2=0, l_2=4, r_2=5$$$ (the subarray $$$[a_4, a_5] = [3, 2]$$$ is not sorted), and $$$t_3=0, l_3=3, r_3=5$$$ (the subarray $$$[a_3, a_5] = [1, 3, 2]$$$ is not sorted).You don't know the array $$$a$$$. Find any array which satisfies all the given facts. | 256 megabytes |
//When I wrote this code, only God & I understood what it did. Now only God knows !!
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static class FastReader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public FastReader() { this(System.in); }public FastReader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String next(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){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 double d() throws IOException {return Double.parseDouble(next()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
public void scanIntArr(int [] arr){ for(int li=0;li<arr.length;++li){ arr[li]=i();}}
public void scanLongArr(long [] arr){for (int i=0;i<arr.length;++i){arr[i]=l();}}
public void shuffle(int [] arr){ for(int i=arr.length;i>0;--i) { int r=(int)(Math.random()*i); int temp=arr[i-1]; arr[i-1]=arr[r]; arr[r]=temp; } }
}
public static int mod = (int) (1e9 + 7);
public static void main(String[] args) throws IOException {
FastReader fr = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
/*
inputCopy
7 4
1 1 3
1 2 5
0 5 6
1 6 7
outputCopy
YES
1 2 2 3 5 4 4
inputCopy
4 2
1 1 4
0 2 3
outputCopy
NO
*/
int n=fr.i();
int m=fr.i();
boolean [] increasing=new boolean[n];
boolean [] isSorted=new boolean[n];
Arrays.fill(isSorted,true);
int [] ans=new int[n];
for(int i=0;i<n;++i)
{
ans[i]=(i+1)*1000;
}
PriorityQueue<Node> pq=new PriorityQueue<Node>();
for(int mi=0;mi<m;++mi)
{
Node node=new Node(fr.i(),fr.i()-1,fr.i()-1);
pq.add(node);
}
boolean possible=true;
while(!pq.isEmpty())
{
Node node=pq.remove();
if(node.t==1)
{
//System.err.println("Here"+node.l+" "+node.r);
int l=node.l;
int r=node.r;
for(int i=l+1;i<=r;++i)
increasing[i]=true;
}
else
{
int l=node.l;
int r=node.r;
boolean found=false;
for(int i=l+1;i<=r;++i)
{
//System.err.println("i="+i+" l"+l+"r="+r+"t="+node.t+" "+Arrays.toString(increasing)+" "+Arrays.toString(isSorted));
if(!isSorted[i] || !increasing[i])
{
//System.err.println("Here 2");
ans[i]=ans[i-1]-1;
found=true;
isSorted[i]=false;
break;
}
}
if(!found)
{
possible=false;
break;
}
}
}
if(!possible)
pw.println("NO");
else
{
//System.err.println(Arrays.toString(increasing)+" "+Arrays.toString(isSorted));
pw.println("YES");
for(int i=0;i<n;++i)
pw.print(ans[i]+" ");
pw.println();
}
pw.flush();
pw.close();
}
static class Node implements Comparable<Node>
{
int t,l,r;
public Node(int t, int l, int r) {
this.t = t;
this.l = l;
this.r = r;
}
public int compareTo(Node other)
{
if(this.t==other.t)
return Integer.compare(this.l,other.l);
if(this.t==1)
return -1;
return 1;
}
}
}
| Java | ["7 4\n1 1 3\n1 2 5\n0 5 6\n1 6 7", "4 2\n1 1 4\n0 2 3"] | 1 second | ["YES\n1 2 2 3 5 4 4", "NO"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 1522d9845b4ea1a903d4c81644797983 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 1000, 1 \le m \le 1000$$$). Each of the next $$$m$$$ lines contains three integers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$). If $$$t_i = 1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is sorted. Otherwise (if $$$t_i = 0$$$) subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is not sorted. | 1,800 | If there is no array that satisfies these facts in only line print NO (in any letter case). If there is a solution, print YES (in any letter case). In second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$, satisfying all the given facts. If there are multiple satisfying arrays you can print any of them. | standard output | |
PASSED | 77c10c1ad80d0af5dd7ea18d74f6a2a6 | train_002.jsonl | 1561905900 | Vasya has an array $$$a_1, a_2, \dots, a_n$$$.You don't know this array, but he told you $$$m$$$ facts about this array. The $$$i$$$-th fact is a triple of numbers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$) and it means: if $$$t_i=1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is sorted in non-decreasing order; if $$$t_i=0$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter. For example if $$$a = [2, 1, 1, 3, 2]$$$ then he could give you three facts: $$$t_1=1, l_1=2, r_1=4$$$ (the subarray $$$[a_2, a_3, a_4] = [1, 1, 3]$$$ is sorted), $$$t_2=0, l_2=4, r_2=5$$$ (the subarray $$$[a_4, a_5] = [3, 2]$$$ is not sorted), and $$$t_3=0, l_3=3, r_3=5$$$ (the subarray $$$[a_3, a_5] = [1, 3, 2]$$$ is not sorted).You don't know the array $$$a$$$. Find any array which satisfies all the given facts. | 256 megabytes | import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution
{
public static void main(String[] args) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter w = new PrintWriter(System.out);
String[] s1 = in.readLine().trim().split("\\s+");
int n = Integer.parseInt(s1[0]);
int m = Integer.parseInt(s1[1]);
int[][] ref = new int[m][3];
boolean gpos = true;
ArrayList<Integer> al = new ArrayList<Integer>();
int[] available = new int[n+1];
for(int q=0;q<m;q++)
{
String[] s2 = in.readLine().trim().split("\\s+");
int t = Integer.parseInt(s2[0]);
int l = Integer.parseInt(s2[1]);
int r = Integer.parseInt(s2[2]);
ref[q][0] = t;
ref[q][1] = l-1;
ref[q][2] = r-1;
if(ref[q][0]==1)
{
available[ref[q][1]]+=1;
available[ref[q][2]]-=1;
}
}
for(int i=1;i<=n;i++)
{
available[i] += available[i-1];
// w.print(available[i-1]+" ");
}
// w.println();
for(int p=0;p<m;p++)
{
int t = ref[p][0];
int l = ref[p][1];
int r = ref[p][2];
if(t==0)
{
boolean pos = false;
for(int i=l;i<r;i++)
{
if(available[i] <= 0)
{
pos = true;
al.add(i);
break;
}
}
gpos = gpos&pos;
if(!gpos)
break;
}
}
if(gpos)
{
w.println("YES");
int[] ans = new int[n];
int cur = al.size();
Collections.sort(al);
int prev = -1;
for(int i=0;i<al.size();i++)
{
if(al.get(i)==prev)
continue;
prev = al.get(i);
ans[al.get(i)]+=cur;
cur--;
}
for(int i=0;i<n;i++)
{
w.print((ans[i]+1)+" ");
}
w.println();
}
else
w.println("NO");
w.close();
}
}
| Java | ["7 4\n1 1 3\n1 2 5\n0 5 6\n1 6 7", "4 2\n1 1 4\n0 2 3"] | 1 second | ["YES\n1 2 2 3 5 4 4", "NO"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 1522d9845b4ea1a903d4c81644797983 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 1000, 1 \le m \le 1000$$$). Each of the next $$$m$$$ lines contains three integers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$). If $$$t_i = 1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is sorted. Otherwise (if $$$t_i = 0$$$) subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is not sorted. | 1,800 | If there is no array that satisfies these facts in only line print NO (in any letter case). If there is a solution, print YES (in any letter case). In second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$, satisfying all the given facts. If there are multiple satisfying arrays you can print any of them. | standard output | |
PASSED | 087404394d10621ff4e891773e5c9f89 | train_002.jsonl | 1561905900 | Vasya has an array $$$a_1, a_2, \dots, a_n$$$.You don't know this array, but he told you $$$m$$$ facts about this array. The $$$i$$$-th fact is a triple of numbers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$) and it means: if $$$t_i=1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is sorted in non-decreasing order; if $$$t_i=0$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter. For example if $$$a = [2, 1, 1, 3, 2]$$$ then he could give you three facts: $$$t_1=1, l_1=2, r_1=4$$$ (the subarray $$$[a_2, a_3, a_4] = [1, 1, 3]$$$ is sorted), $$$t_2=0, l_2=4, r_2=5$$$ (the subarray $$$[a_4, a_5] = [3, 2]$$$ is not sorted), and $$$t_3=0, l_3=3, r_3=5$$$ (the subarray $$$[a_3, a_5] = [1, 3, 2]$$$ is not sorted).You don't know the array $$$a$$$. Find any array which satisfies all the given facts. | 256 megabytes | import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
void solve(){
int n=ni(),m=ni();
int a[]=new int[n+1];
int t[]=new int[m+1];
int l[]=new int[m+1];
int r[]=new int[m+1];
for(int i=1;i<=m;i++){
t[i]=ni(); l[i]=ni(); r[i]=ni();
if(t[i]==1){
for(int j=l[i]+1;j<=r[i];j++) a[j]=1;
}
}
out : for(int i=1;i<=m;i++){
if(t[i]==1) continue;
for(int j=l[i]+1;j<=r[i];j++){
if(a[j]==0){
a[j]=-1;
continue out;
}else if(a[j]==-1) continue out;
}
pw.println("NO");
return;
}
int b[]=new int[n+1];
Arrays.fill(b,10000000);
for(int i=2;i<=n;i++){
if(a[i]==-1){
b[i]=b[i-1]-1;
}else if(a[i]==1){
b[i]=Math.max(b[i-1],b[i]);
}
}
pw.println("YES");
for(int i=1;i<=n;i++){
pw.print(b[i]+" ");
}
pw.println("");
}
boolean check(int freq1[],int freq2[]){
for(int i=-0;i<26;i++){
if(freq1[i]<freq2[i]) return false;
}
return true;
}
long add(long a,long b){
a+=b;
if(a>=M) a-=M;
return a;
}
long mul(long a,long b){
a*=b;
if(a>=M) a%=M;
return a;
}
long sub(long a,long b){
a-=b;
if(a<0) a+=M;
return a;
}
long modpow(long x, long y, long M){
long res = 1;
x = x % M;
while (y > 0)
{
if((y & 1)==1)
res = (res * x) % M;
y = y >> 1;
x = (x * x) % M;
}
return res;
}
long modInverse(long A,long M){
return modpow(A,M-2,M);
}
long M =(long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
} | Java | ["7 4\n1 1 3\n1 2 5\n0 5 6\n1 6 7", "4 2\n1 1 4\n0 2 3"] | 1 second | ["YES\n1 2 2 3 5 4 4", "NO"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"greedy"
] | 1522d9845b4ea1a903d4c81644797983 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 1000, 1 \le m \le 1000$$$). Each of the next $$$m$$$ lines contains three integers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$). If $$$t_i = 1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is sorted. Otherwise (if $$$t_i = 0$$$) subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is not sorted. | 1,800 | If there is no array that satisfies these facts in only line print NO (in any letter case). If there is a solution, print YES (in any letter case). In second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$, satisfying all the given facts. If there are multiple satisfying arrays you can print any of them. | standard output | |
PASSED | fcb0b22e50e7ec05bf02eaad115cb6a0 | train_002.jsonl | 1291536000 | Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class CF_46_C_HAMSTERS_TIGERS {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
int h = 0;
char[] c = s.toCharArray();
for (char ch : c)
if (ch == 'H')
h++;
int res = 0;
int min = Integer.MAX_VALUE;
for(int i = 0 , j = i ;i<n;i++)
{
int freq = 0;
j=i;
int count = 0;
while(count++ !=h) {
if(c[j++] == 'T')
freq++;
j = j==n ? 0 : j;
}
min = Math.min(min, freq);
}
System.out.println(((min == Integer.MAX_VALUE?0:min)));
}
static class Scanner {
BufferedReader bf;
StringTokenizer st;
public Scanner(InputStream i) {
bf = new BufferedReader(new InputStreamReader(i));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(bf.readLine());
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
} | Java | ["3\nHTH", "9\nHTHTHTHHT"] | 2 seconds | ["0", "2"] | NoteIn the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then — the tiger in position 9 with the hamster in position 7. | Java 8 | standard input | [
"two pointers"
] | 0fce263a9606fbfc3ec912894ab1a8f8 | The first line contains number n (2 ≤ n ≤ 1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one. | 1,600 | Print the single number which is the minimal number of swaps that let the trainer to achieve his goal. | standard output | |
PASSED | f3d887c60fcaa0509666144fe39d2c0d | train_002.jsonl | 1291536000 | Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class SPCC {
public static void main (String[] args) throws java.lang.Exception {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = in.nextInt();
char[] ca = in.next().toCharArray();
int h = 0;
for (int i = 0; i < n; i++) {
if (ca[i] == 'H')
h++;
}
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (ca[i] == 'H') {
int temp = 0;
for (int j = i + 1; j < h + i; j++) {
if (ca[(j) % n] == 'T')
temp++;
}
ans = Math.min(temp, ans);
}
}
w.println(ans);
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public void skip(int x) {
while (x-- > 0)
read();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextString() {
return next();
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public boolean hasNext() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value != -1;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
} | Java | ["3\nHTH", "9\nHTHTHTHHT"] | 2 seconds | ["0", "2"] | NoteIn the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then — the tiger in position 9 with the hamster in position 7. | Java 8 | standard input | [
"two pointers"
] | 0fce263a9606fbfc3ec912894ab1a8f8 | The first line contains number n (2 ≤ n ≤ 1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one. | 1,600 | Print the single number which is the minimal number of swaps that let the trainer to achieve his goal. | standard output | |
PASSED | fccb8919f090609dd2850c503623a069 | train_002.jsonl | 1291536000 | Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
char[] original = s.toCharArray();
char[] sort = s.toCharArray();
Arrays.sort(sort);
int min = n;
for(int i = 0; i < n; i++) {
int diff = 0;
for(int j = 0; j < n; j++)
if(sort[j] != original[(i + j) % n])
diff++;
min = Math.min(min, diff / 2);
}
System.out.println(min);
}
}
| Java | ["3\nHTH", "9\nHTHTHTHHT"] | 2 seconds | ["0", "2"] | NoteIn the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then — the tiger in position 9 with the hamster in position 7. | Java 8 | standard input | [
"two pointers"
] | 0fce263a9606fbfc3ec912894ab1a8f8 | The first line contains number n (2 ≤ n ≤ 1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one. | 1,600 | Print the single number which is the minimal number of swaps that let the trainer to achieve his goal. | standard output | |
PASSED | 1077af543d21ca4ecfdd27c4f6bbf370 | train_002.jsonl | 1291536000 | Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Deque;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class HamstersandTigers {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String s=sc.next();
int H=0;
char[]c=new char[n];
for(int i=0;i<n;++i) {
c[i]=s.charAt(i);
if(s.charAt(i)=='H')
++H;
}
int min=1000000;
for(int i=0;i<n;++i) {
int cnt=0;
for(int j=i;j<i+H ;++j)
if(c[j%n]=='T')
++cnt;
min=Math.min(min, cnt);
}
System.out.println(min);
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["3\nHTH", "9\nHTHTHTHHT"] | 2 seconds | ["0", "2"] | NoteIn the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then — the tiger in position 9 with the hamster in position 7. | Java 8 | standard input | [
"two pointers"
] | 0fce263a9606fbfc3ec912894ab1a8f8 | The first line contains number n (2 ≤ n ≤ 1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one. | 1,600 | Print the single number which is the minimal number of swaps that let the trainer to achieve his goal. | standard output | |
PASSED | 4e19f669471e283b2e1343957e59a9bc | train_002.jsonl | 1291536000 | Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him. | 256 megabytes | import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class A
{ static int v;
static ArrayList<Edge> adjList[];
static int node1[], node2[], time[];
static int max = (int)1e5+10;
static int dist[][];
static int t;
static int idx;
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner (System.in);
PrintWriter wr=new PrintWriter(System.out);
int n=sc.nextInt();
String s=sc.next();
char arr[]=s.toCharArray();
int H=0;
for(int i=0;i<n;i++) {
if(arr[i]=='H')H++;
}
int ans=100000;
for(int i=0;i<n;i++) {
int T=0;
for(int j=0;j<H;j++) {
if(arr[(i+j)%n]=='T')T++;
}
ans=Math.min(ans, T);
}
System.out.println(ans);
}
}
class Edge{
int a,d;
Edge(int a,int d){
this.a=a;this.d=d;
}
}
class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
} | Java | ["3\nHTH", "9\nHTHTHTHHT"] | 2 seconds | ["0", "2"] | NoteIn the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then — the tiger in position 9 with the hamster in position 7. | Java 8 | standard input | [
"two pointers"
] | 0fce263a9606fbfc3ec912894ab1a8f8 | The first line contains number n (2 ≤ n ≤ 1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one. | 1,600 | Print the single number which is the minimal number of swaps that let the trainer to achieve his goal. | standard output | |
PASSED | 59a6384bb4a3e54f0a1d7d22a48eca08 | train_002.jsonl | 1291536000 | Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him. | 256 megabytes | import java.util.Scanner;
public class A
{
static String makeTigers(int s, int l, int n)
{
String res = "";
for (int i = 0; i < n; i++)
{
if ((s + l) >= n)
{
if (i < (s + l) % n || i >= s)
res += 'T';
else
res += 'H';
}
else
{
if (i < s + l && i >= s)
res += 'T';
else
res += 'H';
}
}
return res;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s = in.next();
int t = 0;
for (int i = 0; i < n; i++)
if (s.charAt(i) == 'T')
t++;
int res = (int)1e9;
for (int i = 0; i < n; i++)
{
int counter = 0;
char c;
for (int j = 0; j < n; j++)
{
if ((i + t) >= n)
{
if (j < (i + t) % n || j >= i)
c = 'T';
else
c = 'H';
}
else
{
if (j < i + t && j >= i)
c = 'T';
else
c = 'H';
}
if (s.charAt(j) != c)
counter++;
}
res = Math.min(res, counter / 2);
}
System.out.print(res);
}
}
| Java | ["3\nHTH", "9\nHTHTHTHHT"] | 2 seconds | ["0", "2"] | NoteIn the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then — the tiger in position 9 with the hamster in position 7. | Java 8 | standard input | [
"two pointers"
] | 0fce263a9606fbfc3ec912894ab1a8f8 | The first line contains number n (2 ≤ n ≤ 1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one. | 1,600 | Print the single number which is the minimal number of swaps that let the trainer to achieve his goal. | standard output | |
PASSED | 2c145d789b1b710ab31a29fb11125e6d | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes |
import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String s = in.next();
int count1=0, count2=0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '('){
count1++;
}
else {
if(count1!=0){
count1--;
count2+=2;
}
}
}
System.out.println(count2);
}
}
//maximum number of table nxn
/*
int n = in.nextInt();
int [] [] matrix = new int[n][n];
matrix[0][0]=1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
matrix[i][1] = matrix[1][i]= 1;
matrix[i][j] = matrix[i-1][j] +
matrix[i][j-1];
}
}
System.out.println(matrix[n-1][n-1]);*/ | Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 4448f6ada4a65d44a3a19cb454788fb7 | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.util.*;
import java.lang.*;
public class bracketSeq{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
String bra = sc.nextLine();
Stack<Character> s = new Stack<Character>();
for(int i = 0 ; i < bra.length();i++){
if(!s.empty()){
char l = s.pop();
char n = bra.charAt(i);
if((int)l+1 != (int)n){
s.push(l);
s.push(n);
}
}
else{
s.push(bra.charAt(i));
}
}
System.out.println(bra.length()-s.size());
}
}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 52b275a3df0f164600cb535af61b735d | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.Writer;
import java.io.OutputStreamWriter;
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);
BRegularBracketSequenceAnotherApproach solver = new BRegularBracketSequenceAnotherApproach();
solver.solve(1, in, out);
out.close();
}
static class BRegularBracketSequenceAnotherApproach {
public void solve(int testNumber, InputReader in, OutputWriter out) {
String s = in.nextString();
TreeSet<Integer> ts = new TreeSet<>();
ts.add(0);
int depth = 0;
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') ++depth;
else --depth;
if (s.charAt(i) == ')' && ts.contains(depth)) {
count++;
}
ts.add(depth);
}
out.println(count * 2);
}
}
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 println(long i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 1b2d3a391917dc2d72cce427389af912 | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.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);
BRegularBracketSequence solver = new BRegularBracketSequence();
solver.solve(1, in, out);
out.close();
}
static class BRegularBracketSequence {
public void solve(int testNumber, InputReader in, OutputWriter out) {
String s = in.nextString();
int depth = 0;
int min = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') depth++;
else depth--;
min = _F.min(min, depth);
}
out.println(s.length() - (-min + Math.abs(depth - min)));
}
}
static class _F {
public static <T extends Comparable<T>> T min(T... list) {
T candidate = list[0];
for (T i : list) {
if (candidate.compareTo(i) > 0) {
candidate = i;
}
}
return candidate;
}
}
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 println(long i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 636f18a7904cf24cea16d49b2d9b67c2 | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.HashSet;
import java.io.Writer;
import java.io.OutputStreamWriter;
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);
BRegularBracketSequenceAnotherApproach solver = new BRegularBracketSequenceAnotherApproach();
solver.solve(1, in, out);
out.close();
}
static class BRegularBracketSequenceAnotherApproach {
public void solve(int testNumber, InputReader in, OutputWriter out) {
String s = in.nextString();
HashSet<Integer> hs = new HashSet<>();
hs.add(0);
int depth = 0;
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') ++depth;
else --depth;
if (s.charAt(i) == ')' && hs.contains(depth)) {
count++;
}
hs.add(depth);
}
out.println(count * 2);
}
}
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 println(long i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | faa9d9f35f3a50f53f118c5f4c1820d1 | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes |
import java.util.*;
public class regularseq {
public static void main(String args[]) {
Scanner S= new Scanner(System.in);
String s=S.nextLine();
int max=0;
int curr=0;
for(int x=s.length()-1;x>=0;x--) {
int co=0;
int cc=0;
//System.out.println(x);
while(cc>=co&&x>=0) {
// System.out.println(cc+" "+co);
if(s.charAt(x)==')') {
cc++;
} else co++;
x--;
}
x++;
if(cc==co)curr=curr+cc*2;
else if(cc>co)curr=curr+co*2;
else if(cc<co)curr=curr+cc*2;
}
System.out.println(curr);
}
}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 396b3da145d8ee8e351561f4b9d61656 | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.util.*;
import java.io.*;
public class Regular_Bracket_Sequence {
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;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader t = new FastReader();
PrintWriter o = new PrintWriter(System.out);
String s = t.next();
int cur = 0;
int count = 0;
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (ch == '(')
cur++;
else {
if (cur > 0) {
cur--;
count++;
}
}
}
o.println(count << 1);
o.flush();
o.close();
}
} | Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 654967ba3bcfe5f65a624c82aa5c080a | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes |
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.*;
import java.io.InputStream;
public class WTF{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String str = input.nextLine();
int openningBraket=0,ans=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)=='('){
openningBraket++;
}else if(openningBraket>0){
ans+=2;
openningBraket--;
}
}
System.out.println(ans);
}
} | Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | c061e44b50c1a4d9ff5e51ba6ee948dc | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
//import java.util.*;
public class sex {
public static void main (String args[]) throws Exception{
// Scanner s = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String n = br.readLine();
//System.out.println(n);
int a=0;
Stack<Character> s = new Stack<>();
for(int i=0;i<n.length();i++){
if(n.charAt(i)=='(' ||s.empty()){
s.push(n.charAt(i));
}
else if(s.peek()=='('){
//if(n.charAt(i)==')'){
s.pop();
a=a+2;
}
}
System.out.println(a);
}
} | Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 8c0ef92c6fdec67ffc5c132a1d7e7a2c | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes |
/**
* @author egaeus
* @mail sebegaeusprogram@gmail.com
* @veredict Accepted
* @url <https://codeforces.com/problemset/problem/26/B>
* @category strings
* @date 23/10/2019
**/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import static java.lang.Integer.parseInt;
public class CF26B {
public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (String ln; (ln = in.readLine()) != null; ) {
char[] a = ln.toCharArray();
int sum = a[0]==')'?-1:1;
int min = sum;
for(int i=1;i<a.length;i++) {
sum += a[i]==')'?-1:1;
min = Math.min(min, sum);
}
System.out.println(a.length-Math.abs(min)-sum+min);
}
}
}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | a3ae54896cc3162fe7952c68e53dda5c | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
/**
* @author Tran Anh Tai
* @template for CP codes
* What a trick prob!
*/
public class ProbA {
public static void main(String[] args) {
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();
}
// main solver
static class Task{
static int MOD = 1000000007;
public void solve(InputReader in, PrintWriter out) {
String s = in.nextToken();
int n = s.length();
int cnt = 0;
int result = 0;
for (int i = 0; i < n; i++){
if (s.charAt(i) == '(')cnt++;
else if (cnt > 0){
result += 2;
cnt--;
}
}
out.println(result);
}
}
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
}
} | Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 26edd04ec3374ad3c94aeb83ab278805 | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.util.*;
public class sb {
public static void main(String[] args) {
Scanner no=new Scanner(System.in);
String s=no.next();
int o=0;
int c=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('){
o++;
}
else if(s.charAt(i)==')'){
if(o>0){
o--;
c+=2;
}
}
}
System.out.println(c);
}
}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | d36e9ef36de7702e92ef6e99bdfb60bb | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.util.*;
public class RegularBracketSequence {
static void solve(){
Scanner sc = new Scanner(System.in);
// len - maximum length so far, l = current length
int ocount = 0, len = Integer.MIN_VALUE, l = 0;
for(char ch: sc.next().toCharArray()){
if(ch=='('){
ocount++;
} else {
if((ocount-1)>=0){
ocount--;
l+=2;
if(l>len) len = l;
}
}
}
System.out.println((len==Integer.MIN_VALUE) ? 0 :len);
sc.close();
}
public static void main(String args[]) {
solve();
}
} | Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | c261473f2d7d302b8708f53aea2ebfd9 | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.util.*;
public class RegularBracketSequence {
// A little optimized.
static void solve(){
Scanner sc = new Scanner(System.in);
// len - maximum length so far
int ocount = 0, len = 0;
for(char ch: sc.next().toCharArray()){
if(ch=='('){
ocount++;
} else {
if((ocount-1)>=0){
ocount--;
len+=2;
}
}
}
System.out.println(len);
sc.close();
}
public static void main(String args[]) {
solve();
}
} | Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | e3e9a649715fb13bf08c09dbe6821b15 | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.util.*;
import java.util.Scanner;
public class lol {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char[] b=s.next().toCharArray();
Stack<Character> stack = new Stack<>();
int c=0;
for (int i = 0; i <b.length; i++) {
if(b[i]=='('){
stack.push(b[i]);
}
else if(b[i]==')'&&!stack.empty()){
char t= stack.peek();
if(t=='('){
c+=2;
stack.pop();
}
}
}
System.out.println(c);
}
}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 5688198718e60512e902d16dff1eb8d0 | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | //I AM THE CREED
/* package codechef; // don't place package name! */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class HelloWorld{
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
while(input.hasNext()){
String s=input.next();
Stack<Integer> st=new Stack<>();
int close=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('){
st.push(1);
continue;
}
if(st.isEmpty()){
close++;
continue;
}
st.pop();
}
System.out.println(s.length()-close-st.size());
}
}
} | Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 122e77345ebf146dc90eec88f4974730 | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.util.*;
//import java.util.Scanner;
/**
*
* @author DELL
*/
public class Main{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int track=1;
int t=1;
while(t-->0){
//int n=sc.nextInt();
String s=sc.next();
int count=0;
int a=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(')a++;
else{
if(a>0){
count++;
a--;
}
}
}
System.out.println(count*2);
}
}
} | Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 7921e58a55c6b62a2f309ab817cfbe4f | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes |
import java.util.*;
public class CodeForces3 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Stack s=new Stack();
Stack s2=new Stack();
String string=in.next();
int k=0;
for(int i=0;i<string.length();i++)
{
if(string.charAt(i)=='('&&i!=string.length()-1)
{
s.push(string.charAt(i));
}
else if(string.charAt(i)==')'&&i!=0&&!s.isEmpty())
{
s.pop();
k+=2;
}
}
System.out.println(k);
}
static class Stack{
int top=-1;
char[] a;
int size=1;
Stack()
{
a=new char[this.size];
}
public char pop()
{
return a[top--];
}
public void push(char element)
{
if(top==size-1)
{
size*=2;
a=Arrays.copyOf(a, size);
}
a[++top]=element;
}
public boolean isEmpty()
{
if(top==-1)
return true;
return false;
}
}
}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | 46d54e85156d078b8a7f65a7e47a80ca | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java .io.*;
import java.util.*;
import java.lang.*;
import java.util.Arrays;
public class RATHOD
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
String s=sc.next();
int i;
Stack<Character> stack = new Stack<>();
long index=-1;
long length=0;
for(i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(c=='(')
{
stack.push(c);
index++;
}
else if((c==')')&&(!(stack.isEmpty())))
{
stack.pop();
// System.out.println((list.size())+" "+list+" "+index);
length=length+2;
index--;
}
else
{
continue;
}
}
System.out.println(length);
}
} | Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | d3205b3b3c6bdcde951094b0ae2b1dcf | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.util.Scanner;
public class acm {
public static void main(String[] args)
{
Scanner in =new Scanner(System.in);
String x=in.next();
int l=x.length(),counter=0;
for(int i=0;i<x.length();i++)
{
if(x.charAt(i)=='(')
counter++;
else
counter--;
if(counter<0)
{
counter=0;
l--;
}
}
l-=counter;
System.out.println(l);
}}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output | |
PASSED | ba3a2cb7079b72cb9bc376d7e6d0e62d | train_002.jsonl | 1281970800 | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class A{
static FastReader scan=new FastReader();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException
{
String s=scan.next();
char[]chars=s.toCharArray();
int o=0,e=0;
for(int i=0;i<chars.length;i++){
if(chars[i]=='(')o++;
else {
if(e<o)e++;
}
}
out.println(2*e);
out.close();
}
public static long pow(long b, long e) {
long r = 1;
while (e > 0) {
if (e % 2 == 1) r = r * b ;
b = b * b;
e >>= 1;
}
return r;
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long object : arr) list.add(object);
Collections.sort(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception addd) {
addd.printStackTrace();
}
}
return root.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception addd) {
addd.printStackTrace();
}
return str;
}
public int[] nextIntArray(int arraySize) {
int array[] = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextInt();
}
return array;
}
}
static class pair{
int i;
int j;
pair(int i,int j){
this.i=i;
this.j=j;
}
}}
| Java | ["(()))(", "((()())"] | 5 seconds | ["4", "6"] | null | Java 11 | standard input | [
"greedy"
] | 2ce2d0c4ac5e630bafad2127a1b589dd | Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. | 1,400 | Output the maximum possible length of a regular bracket sequence. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.