exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 45544540c0cbf379513ef785aa74b3b1 | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Main {
static BufferedReader in;
static PrintWriter out;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int N = ri();
char[] s = rs().toCharArray();
char[] t = rs().toCharArray();
int[][] pos = new int[26][26];
int[] poss = new int[26];
int[] post = new int[26];
int dist = 0;
int adj = 0;
int p1 = -1, p2 = -1;
for (int i=0;i<N;i++) {
if (s[i] != t[i]) {
dist++;
if (adj<2) {
if (pos[t[i]-'a'][s[i]-'a']>0) {
adj = 2;
p1 = i+1;
p2 = pos[t[i]-'a'][s[i]-'a'];
} else if (adj<1) {
if (poss[t[i]-'a']>0) {
adj = 1;
p1 = i+1;
p2 = poss[t[i]-'a'];
} else if (post[s[i]-'a']>0) {
adj = 1;
p1 = i+1;
p2 = post[s[i]-'a'];
}
}
}
pos[s[i]-'a'][t[i]-'a'] = i+1;
poss[s[i]-'a'] = i+1;
post[t[i]-'a'] = i+1;
}
}
out.println((dist-adj));
out.println(p1+" "+p2);
in.close();
out.close();
}
public static int ri() throws IOException {
return Integer.parseInt(in.readLine());
}
public static long rl() throws IOException {
return Long.parseLong(in.readLine());
}
public static String rs() throws IOException {
return in.readLine();
}
public static String[] rst() throws IOException {
return in.readLine().split(" ");
}
public static int[] rit() throws IOException {
String[] tok = in.readLine().split(" ");
int[] res = new int[tok.length];
for (int i = 0; i < tok.length; i++) {
res[i] = Integer.parseInt(tok[i]);
}
return res;
}
public static long[] rlt() throws IOException {
String[] tok = in.readLine().split(" ");
long[] res = new long[tok.length];
for (int i = 0; i < tok.length; i++) {
res[i] = Long.parseLong(tok[i]);
}
return res;
}
}
| Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 99b72fc830c2a14478f308d4edf0e7dd | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.io.PrintStream;
import java.util.Scanner;
public class B {
private static PrintStream out = System.out;
public static void main(String[] args) {
// read input
Scanner in = new Scanner(System.in);
int n = in.nextInt();
char[] s = in.next().toCharArray();
char[] t = in.next().toCharArray();
// check Hamming distance
int dist = 0;
for (int i = 0; i < n; ++i)
if (s[i] != t[i])
++dist;
// look for mutually beneficial pairs
int[][] idxs2 = new int[26][26];
for (int i = 0; i < 26; ++i)
for (int j = 0; j < 26; ++j)
idxs2[i][j] = -1;
for (int i = 0; i < n; ++i) {
int x = s[i] - 'a';
int y = t[i] - 'a';
if (x == y)
continue;
int idx = idxs2[y][x];
idxs2[x][y] = i;
if (idx >= 0) {
out.println(dist - 2);
out.println((idx + 1) + " " + (i + 1));
return;
}
}
// look for singly beneficial pairs
int[] idxs = new int[26];
for (int i = 0; i < 26; ++i)
idxs[i] = -1;
for (int i = 0; i < n; ++i) {
int x = s[i] - 'a';
int y = t[i] - 'a';
if (x == y)
continue;
idxs[x] = i;
}
for (int i = 0; i < n; ++i) {
int x = s[i] - 'a';
int y = t[i] - 'a';
if (x == y)
continue;
if (idxs[y] >= 0) {
int a = Math.min(idxs[y], i) + 1;
int b = Math.max(idxs[y], i) + 1;
out.println(dist - 1);
out.println(a + " " + b);
return;
}
}
// otherwise nothing is possible
out.println(dist);
out.println("-1 -1");
}
}
| Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | d2dc8b4a9fc117e99315d2a73b6fe820 | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.io.*;
import java.io.PrintWriter;
import java.util.*;
import java.io.InputStream;
import java.io.DataInputStream;
public class cookoff{
public static void main(String[] args) throws IOException
{InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader scn = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int nu=scn.ni();
String s=scn.ns();
String t=scn.ns();
int cnt=0;
// HashMap<, Integer> hs=new HashMap<Character, Integer>();
HashMap<num, Integer> h=new HashMap<num, Integer>();
int i; char chs=' '; char cht=' ';
int arr1[]=new int[200];
int arr2[]=new int[200];
Arrays.fill(arr1,-1);
Arrays.fill(arr2,-1);
for ( i=0;i<nu;i++)
{ chs=s.charAt(i);
cht=t.charAt(i);
if (chs!=cht) cnt++;
h.put(new num(chs,cht) ,i);
if (chs!=cht){ arr1[chs]=i;
arr2[cht]=i;
}
}
Set<num> st=h.keySet();
int flag=0;
int idx1=0; int idx2=0;
for ( num n: st)
{
chs=n.start;
cht=n.end;
if (h.containsKey( new num(cht,chs) ) && chs!=cht ) { idx2=h.get(new num(cht,chs)); idx1=h.get(new num(chs,cht)) ; flag=1; break;}
}
if (flag==1)
{
out.println(cnt-2);
out.print((idx1+1)+" "+(idx2+1));
}
else{
for ( num n: st)
{
chs=n.start;
cht=n.end;
if (arr2[chs]!=-1 && chs!=cht && s.charAt(arr2[chs])!=t.charAt(arr2[chs]) ) { idx2=arr2[chs]; idx1=h.get(new num(chs,cht)) ; flag=2;break; }
else if (arr1[cht]!=-1 && chs!=cht && s.charAt(arr1[cht])!=t.charAt(arr1[cht]) ){ idx2=arr1[cht]; idx1=h.get(new num(chs,cht)) ; flag=3;break; }
}
if (flag==2)
{
out.println(cnt-1);
out.print((idx1+1)+" "+(idx2+1));
}
else
if (flag==3)
{
out.println(cnt-1);
out.print((idx1+1)+" "+(idx2+1));
}
else
{
out.println(cnt);
out.print((-1)+" "+(-1));
}
}
out.close();
}
}
class num //implements Comparator<num>
{
public char start;
public char end;
num()
{
}
num(char x,char y)
{
this.start = x;
this.end =y;
}
public char getstart()
{
return start;
}
public char getend()
{
return end;
}
public boolean equals(Object n1)
{num n=(num)n1;
if (this.start==n.start && this.end==n.end) return true;
else return false;
}
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result
+ start;
result = prime * result+end;
return result;
}
/* public int compare(num o1, num o2) {
if (o1.getstart() > o2.getstart())
return (o1.getstart()-o2.getstart());
else if (o1.getstart() == o2.getstart())
return (o1.getend()-o2.getend());
else
return (o1.getstart()-o2.getstart());
}
*/
}
class FastReader
{
public InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
{
throw new InputMismatchException ();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read (buf);
} catch (IOException e)
{
throw new InputMismatchException ();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public char nc()
{
int c = read ();
while (isSpaceChar (c))
c = read ();
return (char) c;
}
public int ni()
{
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 nl()
{
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 ns()
{
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 isWhitespace (c);
}
public static boolean isWhitespace(int c)
{
return c==' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return ns ();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
} | Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 8f1a4b20bf58c9d3fba5d3880adba0ea | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | //package codeforces.cfr296div2;
import java.util.Scanner;
/**
* Created by bistrashkin on 3/17/15.
*/
public class B {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(); in.nextLine();
String s = in.nextLine();
String t = in.nextLine();
int[][] notMatchingPair = new int[255][255];
int[] notMatchingS = new int[255];
int notMatchingC = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) != t.charAt(i)) {
notMatchingPair[s.charAt(i)][t.charAt(i)] = 1 + i;
notMatchingS[s.charAt(i)] = 1 + i;
notMatchingC++;
}
}
for (char i1 = 'a'; i1 <= 'z'; i1++) {
for (char i2 = 'a'; i2 <= 'z'; i2++) {
if (notMatchingPair[i1][i2] > 0 && notMatchingPair[i2][i1] > 0) {
System.out.println(notMatchingC - 2);
System.out.println(String.format("%d %d", notMatchingPair[i1][i2], notMatchingPair[i2][i1]));
return;
}
}
}
for (char i1 = 'a'; i1 <= 'z'; i1++) {
for (char i2 = 'a'; i2 <= 'z'; i2++) {
if (notMatchingPair[i1][i2] > 0 && notMatchingS[i2] > 0) {
System.out.println(notMatchingC - 1);
System.out.println(String.format("%d %d", notMatchingPair[i1][i2], notMatchingS[i2]));
return;
}
}
}
System.out.println(notMatchingC);
System.out.println("-1 -1");
}
}
| Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | dc98a3de67a9ae9f013fa0badf639316 | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
private static void solve() {
int length = nextInt();
String a = next();
String b = next();
int [] alph = new int[26];
Arrays.fill(alph, -1);
int hamm = 0;
for(int i=0;i<length;i++) {
if(a.charAt(i) != b.charAt(i)) {
hamm++;
if(alph[a.charAt(i)-'a'] == -1)
alph[a.charAt(i)-'a'] = i;
}
}
int one = hamm-1;
int two = hamm-2;
int firstIndex = -1;
int secondIndex = -1;
for(int i=0;i<length;i++) {
if(a.charAt(i)!=b.charAt(i) && alph[b.charAt(i)-'a']!=-1) {
if(a.charAt(i) == b.charAt(alph[b.charAt(i)-'a'])){
firstIndex = alph[b.charAt(i)-'a']+1;
secondIndex = i+1;
hamm = two;
break;
} else {
firstIndex = alph[b.charAt(i)-'a']+1;
secondIndex = i+1;
hamm = one;
}
}
}
out.println(hamm);
out.println(Math.min(firstIndex, secondIndex)+" "+Math.max(firstIndex, secondIndex));
}
private static void run() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
private static StringTokenizer st;
private static BufferedReader br;
private static PrintWriter out;
private static String next() {
while (st == null || !st.hasMoreElements()) {
String s;
try {
s = br.readLine();
} catch (IOException e) {
return null;
}
st = new StringTokenizer(s);
}
return st.nextToken();
}
private static int nextInt() {
return Integer.parseInt(next());
}
private static long nextLong() {
return Long.parseLong(next());
}
public static void main(String[] args) {
run();
}
}
| Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 4f8ec04c55d7cbdaadd3646fef185324 | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main {
static FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(System.out);
static boolean file = false;
static final int maxn = 100;
static int inf = (int)1e9;
static int n,k,leftSize, rightSize;
static String s,t;
static int a[][] = new int [30][30];
private static void solve() throws Exception {
n = in.nextInt();
s = in.nextToken();
t = in.nextToken();
int ans = 0;
for (int i=0; i<n; i++) {
if (s.charAt(i)!=t.charAt(i)) {
a[s.charAt(i)-'a'][t.charAt(i)-'a'] = i+1;
ans++;
}
}
for (int i=0; i<26; i++) {
for (int j=0; j<26; j++) {
if (a[i][j]!=0 && a[j][i]!=0) {
out.println(ans-2);
out.println(a[i][j] + " " + a[j][i]);
return;
}
}
}
if (ans==1) {
out.println(1);
out.println("-1 -1");
return;
}
for (int i=0; i<26; i++) {
int l = 0, r = 0;
if (a[i][i]==0) {
for (int j=0; j<26; j++) {
l = Math.max(a[i][j],l);
}
for (int j=0; j<26; j++) {
r = Math.max(a[j][i],r);
}
if (l!=0 && r!=0) {
out.println(ans-1);
out.println(l + " " + r);
return;
}
}
}
out.println(ans);
out.println("-1 -1");
}
public static void main (String [] args) throws Exception {
if (file) {
in = new FastReader(new BufferedReader(new FileReader("input.txt")));
out = new PrintWriter ("output.txt");
}
solve();
out.close();
}
}
class Pair implements Comparable<Pair> {
int x,y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
Pair p = (Pair)obj;
if (p.x == x && p.y==y) return true;
return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return x;
}
@Override
public int compareTo(Pair p) {
if (x<p.x)return 1;
else if (x==p.x) return 0;
else return -1;
}
}
class FastReader {
BufferedReader bf;
StringTokenizer tk = null;
public FastReader(BufferedReader bf) {
this.bf = bf;
}
public String nextToken () throws Exception {
if (tk==null || !tk.hasMoreTokens()) {
tk = new StringTokenizer(bf.readLine());
}
return tk.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 47e3b0c7c39eb1990307971ab93948ce | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class CF527B {
/*
* ab
* ba
*
* last seen at idx 0. last seen b at idx 1.
* <a b> at idx 0. <b a> at idx 1.
*/
static class Hemming {
String s;
String t;
int n;
int loc1 = -1;
int loc2 = -1;
int[] lastSeen;
int[][] locationOf;
int distance;
int toSubtract = 0;
public Hemming(String S, String T) {
s = S;
t = T;
n = S.length();
lastSeen = new int[26];
locationOf = new int[26][26];
distance = 0;
setup();
}
void setup() {
for (int i = 0; i < 26; i++) Arrays.fill(locationOf[i], -1);
for (int i = 0; i < n; i++) {
if (s.charAt(i) != t.charAt(i)) {
distance++;
lastSeen[s.charAt(i)-'a'] = i+1;
}
}
for (int i = 0; i < n; i++) {
if (s.charAt(i) != t.charAt(i)) {
if (locationOf[t.charAt(i)-'a'][s.charAt(i)-'a'] != -1) {
loc1 = i+1;
loc2 = locationOf[t.charAt(i)-'a'][s.charAt(i)-'a'];
toSubtract = 2;
return;
}
if (lastSeen[t.charAt(i)-'a'] != 0) {
loc1 = lastSeen[t.charAt(i)-'a'];
loc2 = i+1;
toSubtract = 1;
}
locationOf[s.charAt(i)-'a'][t.charAt(i)-'a'] = i+1;
}
}
}
void report() {
System.out.println(distance-toSubtract);
System.out.printf("%d %d\n", loc1, loc2);
}
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
String s1 = in.readLine();
String s2 = in.readLine();
Hemming h = new Hemming(s1, s2);
h.report();
}
}
| Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 287c027f10b571031fe667118406589c | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.io.*;
public class C296_2 {
public static void main(String []args) throws IOException {
new Solution().solve();
}
}
class Solution {
FastReader fr = new FastReader();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public void solve() throws IOException {
int n = fr.nextInt();
String s = fr.nextString();
String t = fr.nextString();
int data[][] = new int[26][26];
int ch[][] = new int[26][2];
int diff = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) != t.charAt(i)) {
diff++;
}
}
int x = -1;
int y = -1;
for (int i = 0; i < n; i++) {
if (s.charAt(i) != t.charAt(i)) {
int xs = s.charAt(i) - 'a';
int yt = t.charAt(i) - 'a';
if (data[yt][xs] > 0) {
System.out.println(diff-2);
System.out.println((i+1) + " " + data[yt][xs]);
return;
}
data[xs][yt] = i+1;
ch[yt][0] = i+1;
ch[xs][1] = i+1;
if (ch[xs][0] > 0 && y == -1) {
y = ch[xs][0];
x = i+1;
}
if (ch[yt][1] > 0 && y == -1) {
y = ch[yt][1];
x = i+1;
}
}
}
if (y == -1) {
System.out.println(diff);
System.out.println(-1 + " " + -1);
} else {
System.out.println(diff - 1);
System.out.println(x + " " + y);
}
}
}
class FastReader {
private InputStream is;
private int bufferSize = 1 << 17;
private byte []buffer = new byte[bufferSize];
private int currentIndex = 0;
private int lastIndex = 0;
public FastReader() {
is = new BufferedInputStream(System.in);
// try {
// is = new BufferedInputStream(new FileInputStream(new File("test.txt")));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
}
public int nextInt() {
int result = 0;
int minus = 1;
byte character = readNext();
while (character == ' ' || character == '\n' || character == '\r') {
character = readNext();
}
if (character == '-') {
minus = -1;
character = readNext();
}
while (character != ' ' && character != '\n' && character != '\r') {
result = result * 10 + (character - '0');
character = readNext();
}
return minus*result;
}
public long nextLong() {
long result = 0;
int minus = 1;
byte character = readNext();
while (character == ' ' || character == '\n' || character == '\r') {
character = readNext();
}
if (character == '-') {
minus = -1;
character = readNext();
}
while (character != ' ' && character != '\n' && character != '\r') {
result = result * 10 + (character - '0');
character = readNext();
}
return minus*result;
}
public String nextString() {
StringBuffer result = new StringBuffer();
byte character = readNext();
while (character == ' ' || character == '\n' || character == '\r') {
character = readNext();
}
while (character != ' ' && character != '\n' && character != '\r') {
result.append((char)character);
character = readNext();
}
return result.toString();
}
public String nextLine() {
StringBuffer result = new StringBuffer();
byte character = readNext();
while (character == '\n' || character == '\r') {
character = readNext();
}
while (character != '\n' && character != '\r') {
result.append((char)character);
character = readNext();
}
return result.toString();
}
private byte readNext() {
if (currentIndex == lastIndex) {
try {
lastIndex = is.read(buffer, 0, bufferSize);
} catch (IOException e) {
throw new RuntimeException("What?");
}
if (lastIndex == -1) {
buffer[0] = -1;
}
currentIndex = 0;
}
return buffer[currentIndex++];
}
} | Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 05b762fccef2a785b0409ace4182d31b | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
outer: for(int casenum = 1; casenum <= qq; casenum++) {
int[][] grid = new int[26][26];
for(int i = 0; i < grid.length; i++) {
Arrays.fill(grid[i], -1);
}
nextToken();
String a = nextToken();
String b = nextToken();
int ret = 0;
for(int i = 0; i < a.length(); i++) {
if(a.charAt(i) == b.charAt(i)) continue;
ret++;
grid[a.charAt(i) - 'a'][b.charAt(i) - 'a'] = i+1;
}
for(int x = 0; x < 26; x++) {
for(int y = 0; y < 26; y++) {
if(grid[x][y] > 0 && grid[y][x] > 0) {
pw.println(ret-2);
pw.println(grid[x][y] + " " + grid[y][x]);
continue outer;
}
}
}
for(int x = 0; x < 26; x++) {
for(int y = 0; y < 26; y++) {
for(int z = 0; z < 26; z++) {
if(grid[x][y] > 0 && grid[y][z] > 0) {
pw.println(ret-1);
pw.println(grid[x][y] + " " + grid[y][z]);
continue outer;
}
}
}
}
pw.println(ret);
pw.println("-1 -1");
}
exitImmediately();
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextLine() throws IOException {
if(!br.ready()) {
exitImmediately();
}
st = null;
return br.readLine();
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
} | Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 7a15a29c4ee7ea533c389cee50e62027 | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Scanner;
/**
* Created by Hedin on 17-Mar-15.
*/
public class ProblemB {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
sc.nextInt();
char[] s = sc.next().toCharArray();
char[] t = sc.next().toCharArray();
sc.close();
int[][] map = new int['z' + 1]['z' + 1];
int[] last = new int['z' + 1];
int res = 0;
for (int i = 0; i < s.length; i++) {
if (s[i] != t[i]) {
map[s[i]][t[i]] = i + 1;
last[s[i]] = i + 1;
res++;
}
}
int i = 0;
int j = 0;
for (char a = 'a'; a <= 'z'; a++) {
for (char b = 'a'; b <= 'z'; b++) {
if (map[a][b] != 0 && map[b][a] != 0) {
pw.println(res - 2);
pw.println(map[a][b] + " " + map[b][a]);
pw.flush();
pw.close();
return;
}
if (map[a][b] != 0 && last[b] != 0) {
i = map[a][b];
j = last[b];
}
}
}
if (i != 0) {
pw.println(res - 1);
pw.println(i + " " + j);
} else {
pw.println(res);
pw.println("-1 -1");
}
pw.flush();
pw.close();
}
}
| Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 11d6952ff9548c77e89cfe2f0299204d | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public class TaskB {
public FasterScanner mFScanner;
public PrintWriter mOut;
public int map[][];
public int rMap[][];
public TaskB() {
mFScanner = new FasterScanner();
mOut = new PrintWriter(System.out);
}
public void solve() {
int n;
int hamming = 0;
String strFirst, strSecond;
char cF, cS;
n = mFScanner.nextInt();
strFirst = mFScanner.nextLine();
strSecond = mFScanner.nextLine();
map = new int[26][26];
rMap = new int[26][26];
for (int i = 0; i < n; i++) {
if (strFirst.charAt(i) != strSecond.charAt(i)) {
hamming++;
cF = strFirst.charAt(i);
cS = strSecond.charAt(i);
map[cF - 'a'][cS - 'a']++;
rMap[cS - 'a'][cF - 'a']++;
}
}
int exchF = -1, exchS = -1;
int hamDif = 0;
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
if (map[i][j] == 0)
continue;
if (map[j][i] != 0) {
exchF = findIndex(strFirst, strSecond, (char) (i + 'a'),
(char) (j + 'a'));
exchS = findIndex(strFirst, strSecond, (char) (j + 'a'),
(char) (i + 'a'));
mOut.println(hamming - 2);
mOut.print(exchF);
mOut.print(" ");
mOut.println(exchS);
return;
}
if (hamDif == 0) {
for (int k = 0; k < 26; k++) {
if (rMap[i][k] != 0) {
exchF = findIndex(strFirst, strSecond,
(char) (i + 'a'), (char) (j + 'a'));
exchS = findIndex(strFirst, strSecond,
(char) (k + 'a'), (char) (i + 'a'));
hamDif = 1;
break;
}
}
}
}
}
mOut.println(hamming - hamDif);
mOut.print(exchF);
mOut.print(" ");
mOut.println(exchS);
}
public int findIndex(String strFirst, String strSecond, char cF, char cS) {
int n = strFirst.length();
for (int i = 0; i < n; i++) {
if (strFirst.charAt(i) == cF && strSecond.charAt(i) == cS)
return i + 1;
}
return -1;
}
public void flush() {
mOut.flush();
}
public void close() {
mOut.close();
}
public static void main(String[] args) {
TaskB mSol = new TaskB();
mSol.solve();
mSol.flush();
mSol.close();
}
class FasterScanner {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FasterScanner() {
this(System.in);
}
public FasterScanner(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 nextString() {
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 nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
Double next;
next = Double.parseDouble(nextString());
return 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 char[] nextCharArray(int N) {
int i;
char[] array;
String str;
array = new char[N];
i = 0;
str = nextLine();
for (i = 0; i < N && i < str.length(); i++) {
array[i] = str.charAt(i);
}
return array;
}
public char[][] nextChar2DArray(int M, int N) {
int i;
char[][] array;
array = new char[M][N];
i = 0;
for (i = 0; i < M; i++) {
array[i] = nextCharArray(N);
}
return array;
}
public int[] nextIntArray(int N) {
int i;
int[] array;
array = new int[N];
i = 0;
for (i = 0; i < N; i++) {
array[i] = nextInt();
}
return array;
}
public int[][] nextInt2DArray(int M, int N) {
int i;
int[][] array;
array = new int[M][N];
i = 0;
for (i = 0; i < M; i++) {
array[i] = nextIntArray(N);
}
return array;
}
public long[] nextLongArray(int N) {
int i;
long[] array;
array = new long[N];
i = 0;
for (i = 0; i < N; i++) {
array[i] = nextLong();
}
return array;
}
public long[][] nextLong2DArray(int M, int N) {
int i;
long[][] array;
array = new long[M][N];
i = 0;
for (i = 0; i < M; i++) {
array[i] = nextLongArray(N);
}
return array;
}
public double[] nextDoubleArray(int N) {
int i;
double[] array;
array = new double[N];
for (i = 0; i < N; i++) {
array[i] = nextDouble();
}
return array;
}
public double[][] nextDouble2DArray(int M, int N) {
int i;
double[][] array;
array = new double[M][N];
for (i = 0; i < M; i++) {
array[i] = nextDoubleArray(N);
}
return array;
}
}
}
| Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 28b0694ec5e12754d3e2e2ef737997eb | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n=(int)in.nextLong();
String s=in.nextString(),t=in.nextString();
int h=hamming(s,t);
int cou=0,i1=-1,i2=-1,j1=-1,j2=-1;
if(h!=0){
pair ar[]=new pair[h];
pair ar1[]=new pair[h];
int k=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)!=t.charAt(i)) {
ar[k] = new pair(s.charAt(i), i);
ar1[k++] = new pair(t.charAt(i), i);
}
}
Arrays.sort(ar);
Arrays.sort(ar1);
for(int i=0;i<ar.length;i++){
int x=Arrays.binarySearch(ar1,ar[i]);
//out.printLine(ar[i]+" "+x+" "+ar[i].x+" "+ar[i].y);
if(x>=0){
i1 = (int) ar[i].y+1;
i2 = (int) ar1[x].y+1;
if(s.charAt(i2-1)==t.charAt(i1-1)){
cou=2;
break;
}
else {
cou=1;
}
}
}
h=h-cou;
}
out.printLine(h);
out.printLine(i1+" "+i2);
}
int hamming(String s,String t){
int val=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)!=t.charAt(i))
val++;
}
return val;
}
private class pair implements Comparable {
public char x;
public long y;
public pair(char a, long b) {
x = a;
y = b;
}
public int compareTo(Object r) {
pair that = (pair) r;
return (int)(this.x-that.x);
}
}
}
class InputReader {
BufferedReader in;
StringTokenizer tokenizer=null;
public InputReader(InputStream inputStream)
{
in=new BufferedReader(new InputStreamReader(inputStream));
}
public String next()
{
try{
while (tokenizer==null||!tokenizer.hasMoreTokens())
{
tokenizer=new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
catch (IOException e)
{
return null;
}
}
public long nextLong()
{
return Long.parseLong(next());
}
public String nextString()
{
try {
return in.readLine();
}
catch (Exception e)
{
return null;
}
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
| Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | b15c91c107d830b3e5a32bf5c2a5584c | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.util.Arrays;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* 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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
char[] a = in.next().toCharArray();
char[] b = in.next().toCharArray();
int distance = 0;
int[] count = new int[26];
Arrays.fill(count, -1);
for (int i = 0; i < n; i++) {
if (a[i] != b[i]) {
count[a[i] - 'a'] = i + 1;
++distance;
}
}
int[] good = new int[2];
int[][] mark = new int[26][26];
for (int i = 0; i < 26; i++) {
Arrays.fill(mark[i], -1);
}
for (int i = 0; i < n; i++) {
if (b[i] != a[i] && count[b[i] - 'a'] != -1) {
good[0] = i + 1;
good[1] = count[b[i] - 'a'];
}
mark[a[i] - 'a'][b[i] - 'a'] = i + 1;
if (a[i] != b[i] && mark[b[i] - 'a'][a[i] - 'a'] != -1) {
out.println(distance - 2);
out.printf("%d %d\n", i + 1, mark[b[i] - 'a'][a[i] - 'a']);
return;
}
}
if (good[0] != 0) {
out.println(distance - 1);
out.printf("%d %d\n", good[0], good[1]);
} else {
out.println(distance);
out.println("-1 -1");
}
}
}
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 | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | b589f8c3ce21adf61e1b534e2185c3f8 | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 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.
*/
/**
*
* @author HafeezulRahman
*/
import java.io.*;
import java.util.*;
public class B296 {
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String s1=br.readLine();
String s2=br.readLine();
HashMap<String, Integer> hash=new HashMap();
int count=0;
for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)!=s2.charAt(i))
{count++;
//System.out.println(s1.charAt(i)+" "+s2.charAt(i)+" variation");
hash.put(s1.charAt(i)+" "+s2.charAt(i), i);
}
}//System.out.println(count);
boolean flag=true;
if(count==1 || count==0)
{
System.out.println(count);
System.out.println("-1 -1");
}
else
{
for (Map.Entry<String, Integer> entry : hash.entrySet()) {
String key = entry.getKey();
//System.out.println(key+" key");
int value = entry.getValue();
String key1= String.valueOf(new StringBuilder(entry.getKey()).reverse());
if(hash.containsKey(key1) && hash.get(key1)!=value)
{System.out.println(count-2);
System.out.println((Math.min(value, hash.get(key1))+1)+" "+(Math.max(value,hash.get(key1))+1));flag=false;
break;
}}
if(flag){
loop: for (Map.Entry<String, Integer> entry : hash.entrySet()) {
String key = entry.getKey();
//System.out.println(key+" key");
int value = entry.getValue();
String a=key.substring(0,1);
//System.out.println(a+" a");
String b=key.substring(2,3);
//System.out.println(b+" b");
for(Map.Entry<String, Integer> entry1:hash.entrySet())
{
String xy=entry1.getKey();
if(String.valueOf(xy.charAt(2)).equals(a) && hash.get(xy)!=value && flag)
{flag=false;
System.out.println(count-1);
System.out.println((Math.min(value, hash.get(xy))+1)+" "+(Math.max(value,hash.get(xy))+1));//System.out.println(flag);
break loop;
}
if((String.valueOf(xy.charAt(0)).equals(b) && hash.get(xy) != value) && (flag==true))
{
System.out.println(count-1);
System.out.println((Math.min(value, hash.get(xy))+1)+" "+(Math.max(value,hash.get(xy))+1));flag=false;
break loop;
} else {
}
}}
if(flag==true)
{
System.out.println(count+"\n"+"-1 -1");
}
}
}}
}
| Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 1160bc74154227d96aa006306943f49b | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
char[] s1 = reader.readLine().toCharArray();
char[] s2 = reader.readLine().toCharArray();
int res = 0;
HashMap<Character, HashMap<Character, Integer>> someOccurrence = new HashMap<Character, HashMap<Character, Integer>>();
for(int i = 0;i < n;i++) {
if(s1[i] != s2[i]) {
res++;
if(!someOccurrence.containsKey(s1[i])) {
someOccurrence.put(s1[i], new HashMap<Character, Integer>());
}
someOccurrence.get(s1[i]).put(s2[i], i);
}
}
boolean flag = false;
int x = -1, y = -1;
for(int i = 0;i < n;i++) {
if(s1[i] != s2[i]) {
if(someOccurrence.containsKey(s2[i])) {
if(someOccurrence.get(s2[i]).containsKey(s1[i])) {
flag = true;
res -= 2;
x = i+1;
y = someOccurrence.get(s2[i]).get(s1[i])+1;
break;
}
}
}
}
if(!flag) {
for(int i = 0; i < n; i++) {
if(s1[i] != s2[i]) {
if(someOccurrence.containsKey(s2[i])) {
res -= 1;
for(char c : someOccurrence.get(s2[i]).keySet()) {
x = i+1;
y = someOccurrence.get(s2[i]).get(c)+1;
break;
}
break;
}
}
}
}
System.out.println(res);
System.out.println(x + " " + y);
}
} | Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 3720983073ddc57b2e0ae078d1bda292 | train_000.jsonl | 1426610700 | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this! | 256 megabytes | import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import javax.sound.midi.SysexMessage;
public class B296 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int strLength=scanner.nextInt();
String strA=scanner.next();
String strB=scanner.next();
// String strA="";
// String strB="";
// System.out.println("Start");
// Random r=new Random();
// StringBuilder builder=new StringBuilder();
// StringBuilder builder2=new StringBuilder();
// for(int g=0;g<100000;g++){
// builder.append("a");
// builder2.append("b");
// }
// for(int g=0;g<100000;g++){
// builder.append("b");
// builder2.append("c");
// }
//
// System.out.println("Start");
// strA=builder.toString();
// strB=builder2.toString();
// System.out.println("Start");
// int strLength=strB.length();
// long time =System.currentTimeMillis();
//======================================
boolean[][] dp=new boolean[26][26];
ArrayList<Integer>[] strACharPos = new ArrayList[26];
ArrayList<Integer>[] strBCharPos = new ArrayList[26];
int dif=0;
for(int g=0;g<strLength;g++){
if(strB.charAt(g)!=strA.charAt(g))
dif++;
}
for(int g=0;g<26;g++){
strBCharPos[g]=new ArrayList<Integer>();
strACharPos[g]=new ArrayList<Integer>();
}
for(int g=0;g<strLength;g++){
if(strB.charAt(g)!=strA.charAt(g))
strACharPos[strA.charAt(g)-97].add(g);
if(strB.charAt(g)!=strA.charAt(g))
strBCharPos[strB.charAt(g)-97].add(g);
}
int c=0;
int index1;
int index2;
int[] bestRes=new int[]{-1,-1,0};
for(int g=0;g<strLength;g++){
if(strA.charAt(g)==strB.charAt(g)||dp[strA.charAt(g)-97][strB.charAt(g)-97])
continue;
index1=g;
dp[strA.charAt(g)-97][strB.charAt(g)-97]=true;
List<Integer> charPos=strBCharPos[strA.charAt(g)-97];
for (int i = 0; i < charPos.size(); i++) {
index2=charPos.get(i);
c=1;
if(strA.charAt(index2)==strB.charAt(index1))
c++;
if(c==2){
System.out.println(dif-2);
System.out.println((index1+1)+" "+(index2+1));
return ;
}
bestRes[0]=index1+1;
bestRes[1]=index2+1;
bestRes[2]=1;
}
c=0;
charPos=strACharPos[strB.charAt(g)-97];
if(charPos.size()>0){
bestRes[0]=index1+1;
bestRes[1]=charPos.get(0)+1;
bestRes[2]=1;
}
}
System.out.println(dif-bestRes[2]);
System.out.println(bestRes[0]+" "+bestRes[1]);
//System.out.println("time : "+(System.currentTimeMillis()-time));
}
}
| Java | ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"] | 2 seconds | ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"] | NoteIn the second test it is acceptable to print i = 2, j = 3. | Java 7 | standard input | [
"greedy"
] | 2fa543c8b8f9dc500c36cf719800a6b0 | The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. | 1,500 | In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. | standard output | |
PASSED | 64670edefe95c3e5802d9586b3a92587 | train_000.jsonl | 1424190900 | Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
final int dx[]={-1,0,1,0};
final int dy[]={0,-1,0,1};
private void solve()throws IOException
{
int n=nextInt();
int m=nextInt();
char grid[][]=new char[n+1][m+1];
int degree[][]=new int[n+1][m+1];
for(int i=1;i<=n;i++)
{
String s=nextLine();
for(int j=1;j<=m;j++)
grid[i][j]=s.charAt(j-1);
}
Queue<Integer> qx=new LinkedList<>();
Queue<Integer> qy=new LinkedList<>();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(grid[i][j]=='.')
{
for(int k=0;k<4;k++)
{
int x=i+dx[k];
int y=j+dy[k];
if(x>=1 && x<=n && y>=1 && y<=m && grid[x][y]=='.')
degree[i][j]++;
}
if(degree[i][j]==1)
{
qx.add(i);
qy.add(j);
}
}
while(!qx.isEmpty())
{
int i=qx.remove();
int j=qy.remove();
for(int k=0;k<4;k++)
{
int x=i+dx[k];
int y=j+dy[k];
if(x>=1 && x<=n && y>=1 && y<=m && grid[x][y]=='.')
{
if(x>i)
{
grid[i][j]='^';
grid[x][y]='v';
}
if(y>j)
{
grid[i][j]='<';
grid[x][y]='>';
}
if(x<i)
{
grid[i][j]='v';
grid[x][y]='^';
}
if(y<j)
{
grid[i][j]='>';
grid[x][y]='<';
}
for(int l=0;l<4;l++)
{
int p=x+dx[l];
int q=y+dy[l];
if(p>=1 && p<=n && q>=1 && q<=m && grid[p][q]=='.')
{
degree[p][q]--;
if(degree[p][q]==1)
{
qx.add(p);
qy.add(q);
}
}
}
break;
}
}
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(grid[i][j]=='.')
{
out.println("Not unique");
return;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
out.print(grid[i][j]);
out.println();
}
}
///////////////////////////////////////////////////////////
public void run()throws IOException
{
br=new BufferedReader(new InputStreamReader(System.in));
st=null;
out=new PrintWriter(System.out);
solve();
br.close();
out.close();
}
public static void main(String args[])throws IOException{
new Main().run();
}
BufferedReader br;
StringTokenizer st;
PrintWriter out;
String nextToken()throws IOException{
while(st==null || !st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine()throws IOException{
return br.readLine();
}
int nextInt()throws IOException{
return Integer.parseInt(nextToken());
}
long nextLong()throws IOException{
return Long.parseLong(nextToken());
}
double nextDouble()throws IOException{
return Double.parseDouble(nextToken());
}
} | Java | ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"] | 2 seconds | ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"] | NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique". | Java 11 | standard input | [
"constructive algorithms",
"greedy"
] | 9465c37b6f948da14e71cc96ac24bb2e | The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied. | 2,000 | If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example. | standard output | |
PASSED | 582aab8f806e11eeb753b5375573d1ce | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.*;
public class Taxi {
public static void main(String args[]){
Scanner sc=new Scanner (System.in);
Integer [] s;
int sum=0;
s =new Integer [4];
for(int i=0;i<4;i++){
s[i]=0;
}
int n=sc.nextInt();
for(int i=0;i<n;i++){
Integer temp=sc.nextInt();
s[temp-1]++;
}
sum=s[3];
sum+=s[2];
sum+=s[1]/2;
s[1]-=2*(s[1]/2);
s[0]-=s[2];
s[0]-=2*s[1];
sum+=s[1];
if(s[0]>=0){
sum+=s[0]/4;
if(s[0]%4!=0){
sum++;
}
}
System.out.println(sum);
}
} | Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | e606a4c73ecda9ab19fc7b597a3efb8d | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes |
import java.io.IOException;
import java.util.Scanner;
public class Taxi {
public static void main(String[] args) throws IOException {
Scanner scn = new Scanner(System.in);
int groups=scn.nextInt(),a=0,b=0,c=0,d=0;
for(int i=0;i<=groups-1;i++){int x = scn.nextInt();switch(x){
case 4:a++;break;case 3:b++;break;
case 2:c++;break;case 1:d++;break;
}}int answer=a+b+(c/2);
d-=b;
if(c%2!=0){answer++;
d=d-2;}
if(d>0){answer+=d/4;
if(d%4!=0)answer++;}
System.out.println(answer);
}}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | a4bf49af3e169d97746d80370367b7f0 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class _158B {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Integer[] groups = new Integer[n];
for (int i = 0; i < n; i++) groups[i] = scan.nextInt();
Arrays.sort(groups, Collections.reverseOrder());
int[] taxis = new int[5];
Arrays.fill(taxis, 0);
taxis[4] = n;
for (int i = 0; i < n; i++) {
int taxiIdx = groups[i];
while (taxis[taxiIdx] == 0) taxiIdx++;
int capacity = taxiIdx - groups[i];
taxis[taxiIdx]--;
taxis[capacity]++;
}
int totalTaxis = taxis[0] + taxis[1] + taxis[2] + taxis[3];
System.out.println(totalTaxis);
}
} | Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | 8e95014ad03356bcf10ed33d13f89900 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int[] s=new int[n];
int cnt1=0,cnt2=0,cnt3=0,cnt=0;
for(int i=0;i<n;i++)
{
s[i]=input.nextInt();
}
for(int j=0;j<n;j++)
{
switch(s[j])
{
case 1:cnt1++;break;
case 2:cnt2++;break;
case 3:cnt3++;break;
case 4:cnt++;break;
}
}
if(cnt3==cnt1)
{
cnt+=cnt3;
cnt3=0;
cnt1=0;
}
else if(cnt3>cnt1)
{
cnt+=cnt3;
cnt3-=cnt1;
cnt1=0;
}
else
{
cnt+=cnt3;
cnt1-=cnt3;
cnt3=0;
}
if(cnt2%2==0)
{
cnt+=cnt2/2;
cnt2=0;
}
else
{
cnt+=cnt2/2;
cnt2=1;
}
int left=(cnt2*2)+cnt1;
if(left%4==0)
{
cnt+=left/4;
}
else
{
cnt+=left/4+1;
}
System.out.println(cnt);
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | 2381eb7a600c49f179c0d3d50165c842 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes |
import java.util.*;
public class JavaApplication1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int ans = 0;
int f[] = new int[5];
for (int i = 0; i < n; i++) {
f[in.nextInt()]++;
}
ans += f[4];
if (f[3] >= f[1]) {
ans += f[3];
f[1]=0;
} else {
ans += f[3];
f[1] -= f[3];
}
ans += f[2] / 2;
if (f[2] % 2 == 1) {
if (f[1] <= 2) {
ans++;
}else{
ans+=Math.ceil((f[1]-2)/4.0)+1;
}
}else{
ans+=Math.ceil(f[1]/4.0);
}
System.out.println(ans);
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | cb4554e10b5d82eebbd8fb7bb3472631 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.*;
public class Problem2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int [] a = new int [n];
for (int i = 0; i<n; i++){
a[i] = sc.nextInt();
}
Arrays.sort(a);
int result = 0; int [] c= new int [4];
for (int i = 0; i<4;i++) c[i] =0;
for (int i = 0; i<n;i++)
c[a[i]-1]++;
result=c[3]+c[2]+c[1]/2;
if (c[0]>c[2]) c[0]-=c[2]; else c[0]=0;
c[1]=c[1]%2;
if (c[1]>0 && c[0]!=0) if (c[0]>1){result++;c[0]=c[0]-2;c[1]=0;} else {result++;c[0]--;c[1]=0;}
if (c[0]==0 && c[1]>0) result++;
result+= c[0]/4;
if (c[0]%4!=0) result++;
System.out.println(result);
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | b427cf2dbe88bdf2b7278c94521213c9 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes |
import java.util.Scanner;
public class Main {
private static final int mod = (int)1e9+7;
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
Scanner sc = new Scanner(System.in);
String input1 = sc.nextLine();
String input2 = sc.nextLine();
int n = Integer.parseInt(input1);
String arr[] = input2.split(" ");
int s[] = new int[n];
int w = 0;
int x = 0;
int y = 0;
int z = 0;
for(int i=0; i<arr.length; i++){
int no = Integer.parseInt(arr[i].trim());
if(no==1){
w++;
}if(no==2){
x++;
}if(no==3){
y++;
}if(no==4){
z++;
}
}
//System.out.println("Inital:"+w + ":" + x + ":" + y + ":" + z);
int count = 0;
count += z;
//System.out.println("After 4s:"+w + ":" + x + ":" + y + ":" + z);
//System.out.println("count:"+count);
if(w==y){
count+=w;
w=0;
}else if (w<y){
count+=w;
y = y-w;
w = 0;
count+=y;
y=0;
}else if(w>y){
count+=y;
w=w-y;
y=0;
}
//System.out.println("After 1s and 3s:"+w + ":" + x + ":" + y + ":" + z);
//System.out.println("count:"+count);
if(x>0){
if(x%2==0){
count+=x/2;
x=0;
if(w>0){
if(w%4==0){
count+=w/4;
w=0;
}else{
count+=(w/4)+1;
w=0;
}
}
}else{
count+=(2*x)/4;
x=x%2;
if(w==0){
count+=1;
x=0;
}else{
if(((2*x)+w)%4==0){
count+=((2*x)+w)/4;
x=0;
w=0;
}else{
count+=(((2*x)+w)/4) + 1;
x=0;
w=0;
}
}
}
}else{
if(w>0){
if(w%4==0){
count+=w/4;
}else{
count+=(w/4)+1;
}
}
}
//System.out.println("last:"+w + ":" + x + ":" + y + ":" + z);
System.out.println(count);
}
catch(Exception e){
e.printStackTrace();
}
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | fd87fff8d6468c523d43eac255132972 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.*;
public class Taxi {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
int n=input.nextInt();
if(n>=1&&n<=100000){
int []s=new int[n];
int c=0;
for(int i=0;i<s.length;i++){
s[i]=input.nextInt();
}
Arrays.sort(s);
int []a=new int[4];
for(int i=0;i<s.length;i++){
if(s[i]==1)
a[0]++;
else if(s[i]==2)
a[1]++;
else if(s[i]==3)
a[2]++;
else if(s[i]==4)
a[3]++;
}
int d=0;
if(a[0]>0&&a[2]>0&&a[0]>a[2]){
d=a[2];
a[0]=a[0]-a[2];
a[2]=0;
}
else if(a[0]>0&&a[2]>0&&a[0]<a[2]){
d=a[0];
a[2]=a[2]-a[0];
a[0]=0;
}
else if(a[0]>0&&a[2]>0&&a[0]==a[2]){
d=a[2];
a[0]=0;
a[2]=0;
}
if(a[0]>0&&a[1]>0&&a[0]/2.0>a[1]){
c=a[1];
a[0]=a[0]-2*a[1];
a[1]=0;
}
else if(a[0]>0&&a[1]>0&&a[0]/2.0<a[1]){
c=(int) Math.ceil(a[0]/2.0);
a[1]=(int) (a[1]-Math.ceil(a[0]/2.0));
a[0]=0;
}
else if(a[0]>0&&a[1]>0&&a[0]/2.0==a[1]){
c=a[1];
a[1]=0;
a[0]=0;
}
int t=0;
if(a[1]>1){
t=(int)Math.ceil(a[1]/2.0);
a[1]=0;
}
int y=0;
if(a[0]>0){
y=(int)Math.ceil(a[0]/4.0);
}
System.out.println((y+t+d+c+a[3]+a[1]+a[2]));
}
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | 668281157edab31c4c24afd8c6f250c5 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
//all elements counts increment as input comes in
while(in.hasNext()){
//for(int t=0;t < 1;t++){
int oneCount = 0;
int twoCount = 0;
int threeCount = 0;
int fourCount = 0;
int groupNum = in.nextInt();
for(int i = 0; i < groupNum; i++){
int n = in.nextInt();
if(n == 1){oneCount++;}
else if(n == 2){twoCount++;}
else if(n == 3){threeCount++;}
else if(n == 4){fourCount++;}
}
// out.println(oneCount);
// out.println(twoCount);
// out.println(threeCount);
// out.println(fourCount);
int taxis = fourCount;
taxis += (twoCount*2 /4);
twoCount -= ((twoCount*2)/4)*2;
while(threeCount > 0 && oneCount >0){
taxis+=1;
oneCount -=1;
threeCount -=1;
}
taxis+=threeCount;
while(twoCount > 0 && oneCount >1){
taxis+=1;
oneCount-=2;
twoCount-=1;
}
taxis += (oneCount/4);
oneCount-=(oneCount/4)*4;
if(oneCount > 0 || twoCount > 0){
taxis+=1;
}
out.println(taxis);
}
in.close();
out.flush();
out.close();
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | d2b1cad66aafbb79fc6de30c8e2373a7 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
public class Program {
public static void main(String[] args) throws IOException {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
st.nextToken();
int k = (int) st.nval;
int[] groups = new int[k];
int[] containers = new int[4];
for (int i = 0; i < k; i++) {
st.nextToken();
groups[i] = (int) st.nval;
}
Arrays.sort(groups);
boolean foundContainer;
for (int i = k - 1; i >= 0; i--) {
int rest = 4 - groups[i];
foundContainer = false;
for (int l = rest - 1; l >= 0; l--) {
if (containers[l] > 0) {
containers[l + groups[i]]++;
containers[l]--;
foundContainer = true;
break;
}
}
if(!foundContainer){
containers[groups[i]-1]++;
}
}
System.out.println(containers[0] + containers[1] + containers[2]
+ containers[3]);
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | d852802553e6116b377d9425230ff0cc | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Taxi158B {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] groups = new int[4];
Arrays.fill(groups, 0);
for (int i = 0; i < n; i++) {
int s = in.nextInt();
groups[s - 1]++;
}
int count = groups[3] + groups[2];
groups[0] -= groups[2];
if (groups[0] < 0)
groups[0] = 0;
count += groups[1] / 2;
groups[1] %= 2;
int remain = groups[0] + groups[1] * 2;
if (remain % 4 == 0)
count += remain / 4;
else
count += remain / 4 + 1;
System.out.println(count);
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | f8b97b027f37197436fb814308e41007 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import static java.lang.System.out;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int t = kb.nextInt();
int[] k = new int[t];
int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0;
for(int i = 0; i < k.length; i++){
k[i] = kb.nextInt();
if(k[i] == 1)cnt1++;
else if(k[i] == 2)cnt2++;
else if(k[i] == 3)cnt3++;
else cnt4++;
}
if(cnt3 >= cnt1)
cnt4 += cnt3 + (int)Math.ceil(cnt2 / 2.0);
else if(cnt3 < cnt1){
cnt4 += cnt3;
cnt1 -= cnt3;
if(cnt2 % 2 == 0){
cnt4 += cnt2 / 2;
cnt4 += Math.ceil(cnt1 / 4.0);
}
else{
cnt4 += (cnt2-1) / 2;
cnt1 += 2;
cnt4 += Math.ceil(cnt1 / 4.0);
}
}
out.println(cnt4);
}
} | Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | b790ff09f1de73baab143c1401de25c4 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.Scanner;
import java.math.*;
import java.util.*;
public class JavaAcm
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int[] number = new int[10];
int i , n , ans = 0 , t;
n = scan.nextInt();
for(i = 0 ;i < n;i ++)
{
int input;
input = scan.nextInt();
number[input]++;
}
ans = number[4];
t = number[2] / 2;
ans += t;
number[2] = number[2] - t * 2;
t = Math.min(number[1], number[3]);
ans += t;
number[1] -= t;
number[3] -= t;
if(number[1] > 0)
{
if(number[2] > 0)
{
if(number[1] >= 2)
{
ans ++;
number[1] -= 2;
ans += number[1] / 4;
if(number[1] % 4 != 0)
ans ++ ;
}
else
ans ++;
}
else
{
ans += number[1] / 4;
if(number[1] % 4 != 0)
ans ++;
}
}
else if(number[3] > 0)
ans = ans + number[3] + number[2];
else
ans += number[2];
System.out.println(ans);
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | 774e7ed9f5afe7e9628ce9d5a5cd8a3d | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Taxi {
public static int t =0 ;
public static BufferedReader in;
public static StringTokenizer st;
public static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine());
return st.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static void printArray(int [] array)
{
for(int i=0;i<array.length;i++)
System.out.print(array[i]+"-");
System.out.println();
}
public static void main(String [] args) throws Exception
{
in = new BufferedReader(new InputStreamReader(System.in));
int n = nextInt();
int res = 0;
int [] array = new int[n];
int [] number = new int[4];
Arrays.fill(number, 0);
for(int i=0;i<n;i++)
{
array[i] = nextInt();
number[array[i]-1]++;
}
res+= number[3];
int p13 = Math.min(number[2],number[0]);
res+=p13;
number[2]-=p13;
number[0]-=p13;
res+=number[2];
res+=number[1]/2;
number[1]=number[1]%2;
res+=number[0]/4;
number[0]=number[0]%4;
if(number[0]!=0 || number[1]!=0)
{
int x = number[0]+2*number[1];
res+= (x-1)/4 +1;
}
System.out.println(res);
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | d094bbcf3e7f03ffc22c31fc6b0a0cb9 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine()); // データ件数
int[] seq = new int[5];
int cnt = 0;
StringTokenizer st = new StringTokenizer(br.readLine()," ");
for (int i = 0; i < n; i++)
seq[Integer.parseInt(st.nextToken())]++;
cnt += seq[4]; // 4人のまとまりを足す
// System.out.println(cnt);
cnt += Math.min(seq[1], seq[3]); // 3人+1人のまとまりを足す
// System.out.println(cnt);
if (seq[1] <= seq[3]) {
seq[3] -= seq[1];
seq[1] = 0;
cnt += seq[3]; // 3人のかたまりを足す
} else {
seq[1] -= seq[3];
}
cnt += seq[2] / 2; // 2人+2人のかたまりを足す
// System.out.println(cnt);
seq[2] = seq[2] % 2 == 0 ? 0 : 1;
cnt += seq[1] / 4; // 1人+1人+1人+1人のかたまりを足す
seq[1] = seq[1] % 4 == 0 ? 0 : seq[1] % 4;
if (seq[2] == 1 && seq[1] == 3) {
cnt += 2;
} else if (!(seq[2] == 0 && seq[1] == 0)) {
cnt++;
}
System.out.println(cnt);
}
}
| Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 6 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | dc0605efb790e400ae778323f0beab40 | train_000.jsonl | 1537707900 | You are given a tuple generator $$$f^{(k)} = (f_1^{(k)}, f_2^{(k)}, \dots, f_n^{(k)})$$$, where $$$f_i^{(k)} = (a_i \cdot f_i^{(k - 1)} + b_i) \bmod p_i$$$ and $$$f^{(0)} = (x_1, x_2, \dots, x_n)$$$. Here $$$x \bmod y$$$ denotes the remainder of $$$x$$$ when divided by $$$y$$$. All $$$p_i$$$ are primes.One can see that with fixed sequences $$$x_i$$$, $$$y_i$$$, $$$a_i$$$ the tuples $$$f^{(k)}$$$ starting from some index will repeat tuples with smaller indices. Calculate the maximum number of different tuples (from all $$$f^{(k)}$$$ for $$$k \ge 0$$$) that can be produced by this generator, if $$$x_i$$$, $$$a_i$$$, $$$b_i$$$ are integers in the range $$$[0, p_i - 1]$$$ and can be chosen arbitrary. The answer can be large, so print the remainder it gives when divided by $$$10^9 + 7$$$ | 512 megabytes | import java.util.Arrays;
import java.util.Scanner;
// 2*7*11 7*13 11*13
public class d {
static int N = 2000001;
static final long MOD = (int) (1e9+7);
public static void main(String[] args) {
int[] pf = new int[N];
for(int i=2;i<N;i++) {
if(pf[i] != 0)
continue;
for(int j=i;j<N;j+=i)
pf[j] = i;
}
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ps = new int[n];
for(int i=0;i<n;i++)
ps[i] = in.nextInt();
Arrays.sort(ps);
int[] max = new int[N];
int[] cnt = new int[N];
boolean canInc = false;
boolean[] skipped = new boolean[N];
for(int i=n-1;i>=0;i--) {
int p = ps[i];
if(max[p] == 0) {
max[p] = 1;
continue;
} else {
skipped[i] = true;
int x = p-1;
while(x > 1) {
int a = pf[x], b = 0;
while(x % a == 0) {
x /= a;
b++;
}
if(max[a] > b)
continue;
if(max[a] == b) {
cnt[a]++;
continue;
}
cnt[a] = 1;
max[a] = b;
}
}
}
for(int i=0;i<N;i++) {
if(!skipped[i])
continue;
int p = ps[i];
int x = p-1;
boolean improved = false;
while(x > 1) {
int a = pf[x], b = 0;
while(x % a == 0) {
x /= a;
b++;
}
if(max[a] > b || (max[a] == b && cnt[a] > 1)) {
continue;
}
improved = true;
}
if(!improved) {
canInc = true;
}
}
long ans = 1;
for(int i=2;i<N;i++) {
while(max[i] > 0) {
max[i]--;
ans *= i;
ans %= MOD;
}
}
if(canInc) {
ans++;
ans %= MOD;
}
System.out.println(ans);
}
}
| Java | ["4\n2 3 5 7", "3\n5 3 3"] | 2 seconds | ["210", "30"] | NoteIn the first example we can choose next parameters: $$$a = [1, 1, 1, 1]$$$, $$$b = [1, 1, 1, 1]$$$, $$$x = [0, 0, 0, 0]$$$, then $$$f_i^{(k)} = k \bmod p_i$$$.In the second example we can choose next parameters: $$$a = [1, 1, 2]$$$, $$$b = [1, 1, 0]$$$, $$$x = [0, 0, 1]$$$. | Java 8 | standard input | [
"constructive algorithms",
"number theory"
] | 816a82bee65cf79ba8e4d61babcd0301 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the tuple. The second line contains $$$n$$$ space separated prime numbers — the modules $$$p_1, p_2, \ldots, p_n$$$ ($$$2 \le p_i \le 2 \cdot 10^6$$$). | 2,900 | Print one integer — the maximum number of different tuples modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 636a49d74d9ae4aeb8142c5cfc578729 | train_000.jsonl | 1537707900 | You are given a tuple generator $$$f^{(k)} = (f_1^{(k)}, f_2^{(k)}, \dots, f_n^{(k)})$$$, where $$$f_i^{(k)} = (a_i \cdot f_i^{(k - 1)} + b_i) \bmod p_i$$$ and $$$f^{(0)} = (x_1, x_2, \dots, x_n)$$$. Here $$$x \bmod y$$$ denotes the remainder of $$$x$$$ when divided by $$$y$$$. All $$$p_i$$$ are primes.One can see that with fixed sequences $$$x_i$$$, $$$y_i$$$, $$$a_i$$$ the tuples $$$f^{(k)}$$$ starting from some index will repeat tuples with smaller indices. Calculate the maximum number of different tuples (from all $$$f^{(k)}$$$ for $$$k \ge 0$$$) that can be produced by this generator, if $$$x_i$$$, $$$a_i$$$, $$$b_i$$$ are integers in the range $$$[0, p_i - 1]$$$ and can be chosen arbitrary. The answer can be large, so print the remainder it gives when divided by $$$10^9 + 7$$$ | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.util.Random;
import java.io.UncheckedIOException;
import java.io.Closeable;
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) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
DLinearCongruentialGenerator solver = new DLinearCongruentialGenerator();
solver.solve(1, in, out);
out.close();
}
}
static class DLinearCongruentialGenerator {
public int log(int x, int y) {
int ans = 0;
while (y != 0 && y % x == 0) {
ans++;
y /= x;
}
return ans;
}
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int limit = (int) 2e6;
IntegerMultiWayStack primeFactors = Factorization.factorizeRangePrime(limit);
int[] cnts = new int[limit + 1];
int[] times = new int[limit + 1];
int[] xs = new int[n];
in.populate(xs);
Randomized.shuffle(xs);
Arrays.sort(xs);
SequenceUtils.reverse(xs);
boolean[] retain = new boolean[n];
for (int i = 0; i < n; i++) {
int x = xs[i];
if (cnts[x] == 0) {
retain[i] = true;
cnts[x] = 1;
times[x] = 1;
continue;
}
for (IntegerIterator iterator = primeFactors.iterator(x - 1); iterator.hasNext(); ) {
int p = iterator.next();
int log = log(p, x - 1);
if (cnts[p] < log) {
cnts[p] = log;
times[p] = 0;
}
if (cnts[p] == log) {
times[p]++;
}
}
}
Modular mod = new Modular(1e9 + 7);
int prod = 1;
for (int i = 1; i <= limit; i++) {
for (int j = 0; j < cnts[i]; j++) {
prod = mod.mul(prod, i);
}
}
for (int i = 0; i < n; i++) {
int x = xs[i];
boolean unique = false;
if (retain[i]) {
if (cnts[x] == 1 && times[x] == 1) {
unique = true;
}
} else {
for (IntegerIterator iterator = primeFactors.iterator(x - 1); iterator.hasNext(); ) {
int p = iterator.next();
int log = log(p, x - 1);
if (cnts[p] == log && times[p] == 1) {
unique = true;
}
}
}
if (!unique) {
prod = mod.plus(prod, 1);
break;
}
}
out.println(prod);
}
}
static class Modular {
int m;
public Modular(int m) {
this.m = m;
}
public Modular(long m) {
this.m = (int) m;
if (this.m != m) {
throw new IllegalArgumentException();
}
}
public Modular(double m) {
this.m = (int) m;
if (this.m != m) {
throw new IllegalArgumentException();
}
}
public int valueOf(int x) {
x %= m;
if (x < 0) {
x += m;
}
return x;
}
public int valueOf(long x) {
x %= m;
if (x < 0) {
x += m;
}
return (int) x;
}
public int mul(int x, int y) {
return valueOf((long) x * y);
}
public int plus(int x, int y) {
return valueOf(x + y);
}
public String toString() {
return "mod " + m;
}
}
static class DigitUtils {
private DigitUtils() {
}
public static boolean isMultiplicationOverflow(long a, long b, long limit) {
if (limit < 0) {
limit = -limit;
}
if (a < 0) {
a = -a;
}
if (b < 0) {
b = -b;
}
if (a == 0 || b == 0) {
return false;
}
//a * b > limit => a > limit / b
return a > limit / b;
}
}
static class RandomWrapper {
private Random random;
public static RandomWrapper INSTANCE = new RandomWrapper(new Random());
public RandomWrapper() {
this(new Random());
}
public RandomWrapper(Random random) {
this.random = random;
}
public int nextInt(int l, int r) {
return random.nextInt(r - l + 1) + l;
}
}
static class Randomized {
public static void shuffle(int[] data) {
shuffle(data, 0, data.length - 1);
}
public static void shuffle(int[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
int tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static int nextInt(int l, int r) {
return RandomWrapper.INSTANCE.nextInt(l, r);
}
}
static class MinimumNumberWithMaximumFactors {
private static int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53};
public static long[] maximumPrimeFactor(long n) {
long[] ans = new long[2];
ans[0] = 1;
for (int i = 0; i < primes.length; i++) {
if (DigitUtils.isMultiplicationOverflow(ans[0], primes[i], n)) {
break;
}
ans[0] *= primes[i];
ans[1]++;
}
return ans;
}
}
static class IntegerMultiWayStack {
private int[] values;
private int[] next;
private int[] heads;
private int alloc;
private int stackNum;
public IntegerIterator iterator(final int queue) {
return new IntegerIterator() {
int ele = heads[queue];
public boolean hasNext() {
return ele != 0;
}
public int next() {
int ans = values[ele];
ele = next[ele];
return ans;
}
};
}
private void doubleCapacity() {
int newSize = Math.max(next.length + 10, next.length * 2);
next = Arrays.copyOf(next, newSize);
values = Arrays.copyOf(values, newSize);
}
public void alloc() {
alloc++;
if (alloc >= next.length) {
doubleCapacity();
}
next[alloc] = 0;
}
public boolean isEmpty(int qId) {
return heads[qId] == 0;
}
public IntegerMultiWayStack(int qNum, int totalCapacity) {
values = new int[totalCapacity + 1];
next = new int[totalCapacity + 1];
heads = new int[qNum];
stackNum = qNum;
}
public void addLast(int qId, int x) {
alloc();
values[alloc] = x;
next[alloc] = heads[qId];
heads[qId] = alloc;
}
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < stackNum; i++) {
if (isEmpty(i)) {
continue;
}
builder.append(i).append(": ");
for (IntegerIterator iterator = iterator(i); iterator.hasNext(); ) {
builder.append(iterator.next()).append(",");
}
if (builder.charAt(builder.length() - 1) == ',') {
builder.setLength(builder.length() - 1);
}
builder.append('\n');
}
return builder.toString();
}
}
static class Factorization {
public static IntegerMultiWayStack factorizeRangePrime(int n) {
int maxFactorCnt = (int) MinimumNumberWithMaximumFactors.maximumPrimeFactor(n)[1];
IntegerMultiWayStack stack = new IntegerMultiWayStack(n + 1, n * maxFactorCnt);
boolean[] isComp = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
if (isComp[i]) {
continue;
}
for (int j = i; j <= n; j += i) {
isComp[j] = true;
stack.addLast(j, i);
}
}
return stack;
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
return this;
}
public FastOutput append(int c) {
cache.append(c);
return this;
}
public FastOutput println(int c) {
return append(c).println();
}
public FastOutput println() {
cache.append(System.lineSeparator());
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class SequenceUtils {
public static void swap(int[] data, int i, int j) {
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
public static void reverse(int[] data, int l, int r) {
while (l < r) {
swap(data, l, r);
l++;
r--;
}
}
public static void reverse(int[] data) {
reverse(data, 0, data.length - 1);
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
public void populate(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = readInt();
}
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static interface IntegerIterator {
boolean hasNext();
int next();
}
}
| Java | ["4\n2 3 5 7", "3\n5 3 3"] | 2 seconds | ["210", "30"] | NoteIn the first example we can choose next parameters: $$$a = [1, 1, 1, 1]$$$, $$$b = [1, 1, 1, 1]$$$, $$$x = [0, 0, 0, 0]$$$, then $$$f_i^{(k)} = k \bmod p_i$$$.In the second example we can choose next parameters: $$$a = [1, 1, 2]$$$, $$$b = [1, 1, 0]$$$, $$$x = [0, 0, 1]$$$. | Java 8 | standard input | [
"constructive algorithms",
"number theory"
] | 816a82bee65cf79ba8e4d61babcd0301 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the tuple. The second line contains $$$n$$$ space separated prime numbers — the modules $$$p_1, p_2, \ldots, p_n$$$ ($$$2 \le p_i \le 2 \cdot 10^6$$$). | 2,900 | Print one integer — the maximum number of different tuples modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 5f91fb0f931846d67f5097176437b17f | train_000.jsonl | 1537707900 | You are given a tuple generator $$$f^{(k)} = (f_1^{(k)}, f_2^{(k)}, \dots, f_n^{(k)})$$$, where $$$f_i^{(k)} = (a_i \cdot f_i^{(k - 1)} + b_i) \bmod p_i$$$ and $$$f^{(0)} = (x_1, x_2, \dots, x_n)$$$. Here $$$x \bmod y$$$ denotes the remainder of $$$x$$$ when divided by $$$y$$$. All $$$p_i$$$ are primes.One can see that with fixed sequences $$$x_i$$$, $$$y_i$$$, $$$a_i$$$ the tuples $$$f^{(k)}$$$ starting from some index will repeat tuples with smaller indices. Calculate the maximum number of different tuples (from all $$$f^{(k)}$$$ for $$$k \ge 0$$$) that can be produced by this generator, if $$$x_i$$$, $$$a_i$$$, $$$b_i$$$ are integers in the range $$$[0, p_i - 1]$$$ and can be chosen arbitrary. The answer can be large, so print the remainder it gives when divided by $$$10^9 + 7$$$ | 512 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class A {
public static void main (String[] args) { new A(); }
//tough math problem. most of the proof makes sense
int MOD = (int)1e9+7;
A() {
Scanner s = new Scanner(System.in);
System.err.println("");
int n = s.nextInt();
int max = 0;
int[] ps = new int[n];
for(int i = 0; i < n; i++) {
ps[i] = s.nextInt();
if(ps[i] > max) max = ps[i];
}
boolean[] isPrime = new boolean[max+1];
int[] lpf = new int[max+1];
Arrays.fill(isPrime, true); isPrime[0] = isPrime[1] = false;
for(int i = 2; i <= max; i++) {
if(!isPrime[i]) continue;
lpf[i] = i;
for(int j = i+i; j <= max; j += i) {
if(isPrime[j]) {
isPrime[j] = false;
lpf[j] = i;
}
}
}
sort(ps);
int[] maxPows = new int[max+1];
boolean canAdd1 = false;
int[] type = new int[n], maxSetBy = new int[max+1];
for(int i = n-1; i >= 0; i--) {
int val = ps[i];
if(maxPows[val] == 0) {
maxPows[val]++;
maxSetBy[val] = i;
type[i] = 1;
continue;
}
int[][] pf = getPF(val-1, lpf);
boolean makesProfit = false;
for(int j = 0; j < pf.length; j++) {
if(pf[j][1] > maxPows[pf[j][0]]) {
makesProfit = true;
}
}
if(makesProfit) {
for(int j = 0; j < pf.length; j++) {
int pr = pf[j][0];
if(maxPows[pr] <= pf[j][1]) {
maxPows[pr] = pf[j][1];
maxSetBy[pr] = i;
}
}
type[i] = 2;
}
else {
type[i] = -1;
canAdd1 = true;
}
}
int res = 1;
for(int i = 0; i <= max; i++) {
res = mult(res, pow(i, maxPows[i]));
}
if(!canAdd1){
//someone might be removable to add 1
for(int i = 0; i < n; i++) {
if(type[i] != 2) continue;
int[][] pf = getPF(ps[i]-1, lpf);
boolean keep = false;
for(int j = 0; j < pf.length; j++) {
int v = pf[j][0];
if(maxSetBy[v] == i) keep = true;
}
if(!keep) {
canAdd1 = true;
break;
}
}
}
if(canAdd1) res = (res+1)%MOD;
System.out.println(res);
}
int pow(int base, int expo) {
if(expo == 0) return 1;
if(expo == 1) return base;
if((expo & 1) == 1) {
return mult(base, pow(base, expo-1));
}
else {
int ret = pow(base, expo >> 1);
return mult(ret, ret);
}
}
int mult(long a, long b) {
a *= b;
if(a >= MOD) a %= MOD;
return (int)a;
}
int[][] getPF(int n, int[] lpf) {
int[][] res = new int[10][2];
int ptr = 0;
while(n > 1) {
int v = lpf[n], cnt = 0;
while(n%v == 0) {
cnt++;
n /= v;
}
res[ptr][0] = v; res[ptr][1] = cnt;
ptr++;
}
res = Arrays.copyOfRange(res, 0, ptr);
return res;
}
void sort(int[] a) {
Random rand = new Random();
int n = a.length;
for(int i = 0; i < n; i++) {
int x = rand.nextInt(n);
int y = rand.nextInt(n);
int t = a[x]; a[x] = a[y]; a[y] = t;
}
Arrays.sort(a);
}
} | Java | ["4\n2 3 5 7", "3\n5 3 3"] | 2 seconds | ["210", "30"] | NoteIn the first example we can choose next parameters: $$$a = [1, 1, 1, 1]$$$, $$$b = [1, 1, 1, 1]$$$, $$$x = [0, 0, 0, 0]$$$, then $$$f_i^{(k)} = k \bmod p_i$$$.In the second example we can choose next parameters: $$$a = [1, 1, 2]$$$, $$$b = [1, 1, 0]$$$, $$$x = [0, 0, 1]$$$. | Java 8 | standard input | [
"constructive algorithms",
"number theory"
] | 816a82bee65cf79ba8e4d61babcd0301 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the tuple. The second line contains $$$n$$$ space separated prime numbers — the modules $$$p_1, p_2, \ldots, p_n$$$ ($$$2 \le p_i \le 2 \cdot 10^6$$$). | 2,900 | Print one integer — the maximum number of different tuples modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 733f818b18e87adcef95b62493c5e541 | train_000.jsonl | 1508054700 | This is an interactive problem.Jury has hidden a permutation p of integers from 0 to n - 1. You know only the length n. Remind that in permutation all integers are distinct.Let b be the inverse permutation for p, i.e. pbi = i for all i. The only thing you can do is to ask xor of elements pi and bj, printing two indices i and j (not necessarily distinct). As a result of the query with indices i and j you'll get the value , where denotes the xor operation. You can find the description of xor operation in notes.Note that some permutations can remain indistinguishable from the hidden one, even if you make all possible n2 queries. You have to compute the number of permutations indistinguishable from the hidden one, and print one of such permutations, making no more than 2n queries.The hidden permutation does not depend on your queries. | 256 megabytes | import java.io.*;
import java.util.*;
import java.io.*;
import java.util.*;
import java.math.*;
public class B {
public static void main(String[] args)throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int xor[][] = new int[n][n];
for(int i=0; i<n; ++i) {
System.out.println("? 0 " + i);
xor[0][i] = sc.nextInt();
}
for(int i=0; i<n; ++i) {
System.out.println("? " + i + " 0");
xor[i][0] = sc.nextInt();
}
for(int i=0; i<n; ++i) {
for(int j=0; j<n; ++j) {
if(i==0||j==0) continue;
xor[i][j] = xor[i][0]^xor[0][j]^xor[0][0];
}
}
int ans[] = new int[n];
int p[] = new int[n];
int b[] = new int[n];
int cnt[] = new int[n];
ans[0] = -1;
int good = 0;
outer: for(int i=0; i<n; ++i) {
p[0] = i;
b[0] = p[0]^xor[0][0];
cnt[0] = 0;
for(int j=1; j<n; ++j) {
p[j] = b[j-1]^xor[j][j-1];
b[j] = p[j]^xor[j][j];
cnt[j] = 0;
if(p[j]>=n)continue outer;
}
for(int j=0; j<n; ++j) {
cnt[p[j]]++;
if(cnt[p[j]]>1||p[b[j]]!=j)continue outer;
}
if(ans[0]==-1) {
for(int j=0; j<n; ++j) {
ans[j] = p[j];
}
}
good++;
}
System.out.println("!");
System.out.println(good);
for(int i: ans) {
System.out.print(i + " ");
}
out.close();
}
static class FastIO {
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
public FastIO(String fileName) throws IOException {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws IOException {
dis = is;
}
int nextInt() throws IOException {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
long nextLong() throws IOException {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
byte nextByte() throws IOException {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws IOException {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
}
| Java | ["3\n0\n0\n3\n2\n3\n2", "4\n2\n3\n2\n0\n2\n3\n2\n0"] | 2 seconds | ["? 0 0\n? 1 1\n? 1 2\n? 0 2\n? 2 1\n? 2 0\n!\n1\n0 1 2", "? 0 1\n? 1 2\n? 2 3\n? 3 3\n? 3 2\n? 2 1\n? 1 0\n? 0 0\n!\n2\n3 1 2 0"] | Notexor operation, or bitwise exclusive OR, is an operation performed over two integers, in which the i-th digit in binary representation of the result is equal to 1 if and only if exactly one of the two integers has the i-th digit in binary representation equal to 1. For more information, see here.In the first example p = [0, 1, 2], thus b = [0, 1, 2], the values are correct for the given i, j. There are no other permutations that give the same answers for the given queries.The answers for the queries are: , , , , , . In the second example p = [3, 1, 2, 0], and b = [3, 1, 2, 0], the values match for all pairs i, j. But there is one more suitable permutation p = [0, 2, 1, 3], b = [0, 2, 1, 3] that matches all n2 possible queries as well. All other permutations do not match even the shown queries. | Java 11 | standard input | [
"implementation",
"brute force",
"interactive"
] | 77b30da2a1df31ae74c07ab2002f0c71 | The first line contains single integer n (1 ≤ n ≤ 5000) — the length of the hidden permutation. You should read this integer first. | 2,000 | When your program is ready to print the answer, print three lines. In the first line print "!". In the second line print single integer answers_cnt — the number of permutations indistinguishable from the hidden one, including the hidden one. In the third line print n integers p0, p1, ..., pn - 1 (0 ≤ pi < n, all pi should be distinct) — one of the permutations indistinguishable from the hidden one. Your program should terminate after printing the answer. | standard output | |
PASSED | 52b671c2c8752b9c7664bf0bfe08b084 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.math.BigInteger;
import java.util.Scanner;
/*
527
4573
1357997531
2268482861
2268482869
4265
4263
*/
public class b {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String n = in.next();
in.close();
// n = "";
// for(int i = 0; i < 1E5; ++i)
// {
// n += (char)(Math.random()*10 + '0');
// }
// System.out.println("Gen");
System.out.println(getLargest2(n));
}
//Brute
static BigInteger getLargest(String n)
{
BigInteger best = BigInteger.valueOf(-1);
StringBuilder start = new StringBuilder();
StringBuilder end = new StringBuilder();
end.append(n.substring(1,n.length()-1));
char last = n.charAt(n.length()-1);
for(int curr = 0; curr < n.length()-1; ++curr)
{
char c = n.charAt(curr);
if((c - '0')%2 == 0)
{
//BigInteger test = new BigInteger((n.substring(0, curr) +n.charAt(n.length()-1)+n.substring(curr+1, n.length()-1) +n.charAt(curr)));
BigInteger test = new BigInteger(start.toString() + last + end.toString() + c);
if(best.compareTo(test) < 0)
best = test;
}
start.append(c);
end.delete(0, 1);
}
return best;
}
static String getLargest2(String n)
{
int lastEvenIndex = -1;
int last = n.charAt(n.length()-1) - '0';
for(int curr = 0; curr < n.length()-1; ++curr)
{
char c = n.charAt(curr);
if((c - '0')%2 == 0)
{
lastEvenIndex = curr;
if(c - '0' < last)
break;
}
}
if(lastEvenIndex == -1)
{
return "-1";
}
StringBuilder s = new StringBuilder();
s.append(n);
s.setCharAt(lastEvenIndex, n.charAt(n.length()-1));
s.setCharAt(n.length()-1, n.charAt(lastEvenIndex));
return s.toString();
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 5280fff29f7c099124e40ae666cffd2a | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String n = scan.next();
StringBuilder s = new StringBuilder(n);
String ans = "";
int in = -1;
int k = -1;
for (int i = 0; i < n.length(); i++) {
if (n.charAt(i) == '2' || n.charAt(i) == '4' || n.charAt(i) == '6' || n.charAt(i) == '8' || n.charAt(i) == '0') {
k = i;
if ((n.charAt(i) + "").compareTo(n.charAt(n.length()-1) + "") < 0) break;
}
}
if (k == -1 && in == -1) System.out.println(-1);
else {
s.setCharAt(k, n.charAt(n.length() - 1));
s.setCharAt(n.length() - 1, n.charAt(k));
System.out.println(s + "");
}
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | e141257dac949ddbf4268db1d25c53c4 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Xi Lin ([email protected])
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
char s[] = in.next().toCharArray();
String ans = new String("-1");
int n = s.length, last = -1;
for (int i = 0; i < n; i++) {
if ((s[i] - '0') % 2 == 0) {
if (s[n - 1] > s[i]) {
char t = s[i]; s[i] = s[n - 1]; s[n - 1] = t;
ans = new String(s);
break;
}
last = i;
}
}
if (ans.equals("-1") && last != -1) {
char t = s[last]; s[last] = s[n - 1]; s[n - 1] = t;
ans = new String(s);
}
out.println(ans);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 27aefd861b6a2885a7f0dcdecc0bf04c | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.util.Scanner;
public class B {
public static int toInt(char c) {
return (int) c - '0';
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char[] c = in.nextLine().toCharArray();
// SWAP SMALL
int l = toInt(c[c.length - 1]), t;
boolean found = false;
for (int i = 0; i < c.length - 1 && !found; i++) {
t = toInt(c[i]);
if ((t & 1) == 0 && t < l) {
char p = c[i];
c[i] = c[c.length - 1];
c[c.length - 1] = p;
found = true;
}
}
if (found) {
System.out.println(new String(c));
} else {
for (int i = c.length - 2; i >= 0 && !found; i--) {
t = toInt(c[i]);
if ((t & 1) == 0) {
char p = c[i];
c[i] = c[c.length - 1];
c[c.length - 1] = p;
found = true;
}
}
if (found) {
System.out.println(new String(c));
} else {
System.out.println("-1");
}
}
in.close();
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 4b9d89c7b6181070f3e97f8902eec698 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.util.Scanner;
public class B {
private static char[] c;
private static int len, l;
public static int toInt(char c) {
return (int) c - '0';
}
public static boolean solve(int i) {
if (i >= 0 && i < len) {
int x = toInt(c[i]);
if ((x & 1) == 0) {
if (x < l) {
char p = c[i];
c[i] = c[c.length - 1];
c[c.length - 1] = p;
return true;
} else {
if (!solve(i + 1)) {
char p = c[i];
c[i] = c[c.length - 1];
c[c.length - 1] = p;
}
return true;
}
} else
return solve(i + 1);
} else {
return false;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
c = in.nextLine().toCharArray();
len = c.length;
// SWAP SMALL
l = toInt(c[c.length - 1]);
boolean solved = solve(0);
if (solved)
System.out.println(new String(c));
else
System.out.println("-1");
}
} | Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 0d6d48aefe49a6146b3c87733469b25f | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
public class Solution {
public String currency() {
Scanner s = new Scanner(System.in);
char[] n = s.next().toCharArray();
s.close();
for (int i = 0; i < n.length; ++i) {
char c = n[i];
if (c < n[n.length - 1] && ((c - '0') % 2 == 0)) {
char temp = n[i];
n[i] = n[n.length - 1];
n[n.length - 1] = temp;
return new String(n);
}
}
for (int i = n.length - 1; i >= 0; --i) {
if ((n[i] - '0') % 2 == 0) {
char temp = n[i];
n[i] = n[n.length - 1];
n[n.length - 1] = temp;
return new String(n);
}
}
return "-1";
}
public static void main(String[] args) {
System.out.println(new Solution().currency());
}
} | Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 4cdc23d4e75e20de86d43a6d347cdb85 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import static java.lang.System.in;
import java.io.IOException;
import java.util.*;
public class Main
{//static{ System.out.println("hello");}
static byte[] buffer = new byte[8192];
static int offset = 0;
static int bufferSize = 0;
static void print(char a[])
{for (int i=0;i<a.length ;i++)
{
System.out.print(a[i]+"");
}
}
static void swap(char ch[], int a,int b)
{
char temp=ch[a];
ch[a]=ch[b];
ch[b]=temp;
}
public static void main(String[] args) throws IOException
{ Scanner scn=new Scanner(System.in);
String s=scn.next(); char ch[]=s.toCharArray();
int len=s.length();
char x=ch[len-1]; int right=-1, left= -1;
for (int i=0;i<len-1;i++)
{ if (ch[i] < x && (ch[i])%2==0) { left=i; break;}
}
if (left==-1)
{ for (int i=len-2;i>=0;i--)
if ((ch[i])%2==0) { left=i; break;}
}
if (left==-1)
System.out.println(-1);
else
{swap(ch,left,len-1);
print(ch);
}
}
static int readInt() throws IOException{
int number = 0;
if(offset==bufferSize){
offset = 0;
bufferSize = in.read(buffer);
}
for(;buffer[offset]<0x30; ++offset)
if(offset==bufferSize-1){
offset=-1;
bufferSize = in.read(buffer);
}
for(;offset<bufferSize && buffer[offset]>0x2f;++offset){
number = number*0x0a+buffer[offset]-0x30;
if(offset==bufferSize-1){
offset = -1;
bufferSize = in.read(buffer);
}
}
++offset;
return number;
}
} | Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 7cb4134b6af1159d9f30c106c0cfdf29 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.util.Scanner;
public class AntonandCurrencyYouAllKnow {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String todayRate = sc.next();
char swap = todayRate.charAt(todayRate.length() - 1);
int index = -1;
for(int i = 0;i < todayRate.length() - 1;i++){
char temp = todayRate.charAt(i);
if( (temp - '0') % 2 == 1 ) continue;
if( temp < swap ){
index = i;
break;
}
index = i;
}
if(index == -1) System.out.println(-1); else System.out.println(swap(index,todayRate.length() - 1, new String(todayRate)));
sc.close();
return;
}
private static String swap(int i, int j, String target){
char[] array = target.toCharArray();
char temp = array[i];
array[i] = array[j];
array[j] = temp;
return new String(array);
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 2c0d475d2f1815ff72e7ae106becdecd | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main2 {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
boolean ok = false;
int kouhoindex = -1;
for(int i = 0 ; i < s.length() -1 ; i++){
int num = Character.digit(s.charAt(i), 10);
if(num % 2 == 0)
if(num < Character.digit(s.charAt(s.length() - 1), 10)){
ok = true;
System.out.println(s.substring(0,i)+s.charAt(s.length() - 1)+s.substring(i + 1,s.length() - 1)+s.charAt(i));
break;
}else{
kouhoindex = i;
}
}
if(!ok){
if(kouhoindex != -1){
System.out.println(s.substring(0,kouhoindex)+s.charAt(s.length() - 1)+s.substring(kouhoindex + 1,s.length() - 1)+s.charAt(kouhoindex));
}else{
System.out.println("-1");
}
}
}
} | Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 5e4df66adad07f5b81db71092ac21fc2 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class AntonAndCurrency {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
int max = -1;
int maxIndex = -1;
int l = input.charAt(input.length()-1)-'0';
for(int i=0 ; i<input.length() ; i++) {
int a = input.charAt(i)-'0';
if(a%2 == 0) {
if(a < l) {
max = a;
maxIndex = i;
break;
}
max = a;
maxIndex = i;
}
}
if(maxIndex > -1) {
String s = input.substring(0,maxIndex) + input.charAt(input.length()-1) +
input.substring(maxIndex+1,input.length()-1) + max;
System.out.print(s);
} else {
System.out.print(max);
}
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 734bba0ecf2ea95b1a6f8117bb8d377c | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.util.Scanner;
/**
* Created by yakoub on 13/04/15.
*/
public class CurrencyYouAllKnowAbout {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String number = scanner.next();
int lastNumber = number.charAt(number.length()-1) - '0';
int replaceCharacter = -1;
for (int i = 0; i < number.length() - 1; i++) {
if ((number.charAt(i) - '0') % 2 == 0) {
int c = number.charAt(i) - '0';
replaceCharacter = i;
if(c < lastNumber)
break;
}
}
if(replaceCharacter == -1)
System.out.println("-1");
else{
char [] chars = number.toCharArray();
char t = chars[chars.length-1];
chars[chars.length-1] = chars[replaceCharacter];
chars[replaceCharacter] = t;
System.out.println(new String(chars));
}
}
} | Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 0ccaedc5935d8f5eeb1e9757791468ea | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class B {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
char[] c = bf.readLine().toCharArray();
boolean ff = false;
int pos = c.length - 1;
int first = c[c.length - 1] - '0';
for (int i = c.length - 2; i >= 0; i--) {
if ((c[i] - '0') % 2 == 0) {
ff = true;
int curr = c[i] - '0';
if (first < curr) {
if (pos == c.length - 1)
pos = i;
} else {
pos = i;
}
}
}
if (ff) {
char temp = c[pos];
c[pos] = c[c.length - 1];
c[c.length - 1] = temp;
boolean found = false;
for (int i = 0; i < c.length; i++) {
if (found || c[i] != '0') {
found = true;
System.out.print(c[i]);
}
}
} else {
System.out.print(-1);
}
System.out.println();
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 6ae9c9730e5325cd6c39047cb1f64e33 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.util.Scanner;
public class AntonAndCurrencyYouAllKnow {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String numString=scanner.nextLine();
int best=-1;
int index=-1;
int last=Integer.valueOf(numString.substring(numString.length()-1));
for (int i = numString.length()-2; i >=0; i--) {
int digit=Integer.valueOf(numString.substring(i,i+1));
if(digit%2==0){
if(best==-1 || last>digit ){
index=i;
best=digit;
}
}
}
if(index!=-1)
numString=numString.substring(0,index)+numString.substring(numString.length()-1)+numString.substring(index+1,numString.length()-1)+String.valueOf(best);
else
numString="-1";
System.out.println(numString);
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 178d8e705f5c87efefba066fb897e074 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String n = br.readLine();
int min = 97;
int index = -1;
boolean flag = false;
for (int i = 0; i < n.length(); i++) {
int rakam = Integer.parseInt(n.charAt(i) + "");
if (rakam % 2 == 0
&& rakam < Integer.parseInt(n.charAt(n.length() - 1) + "")) {
min = rakam;
index = i;
flag = true;
break;
}
}
if (flag == false) {
if (Integer.parseInt(n.charAt(n.length() - 1) + "") % 2 != 0) {
for (int i = n.length() - 1; i >= 0; i--) {
int rakam = Integer.parseInt(n.charAt(i) + "");
if (rakam % 2 == 0) {
min = rakam;
index = i;
break;
}
}
}
}
if (Integer.parseInt(n.charAt(n.length() - 1) + "") % 2 == 0 && flag == false) {
System.out.println(n);
}else{
if (index != -1) {
String s = n.substring(0, index) + n.charAt(n.length() - 1)
+ "" + n.substring(index + 1, n.length() - 1) + min;
System.out.println(s);
} else if (index == -1) {
System.out.println(-1);
}
}
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | faf790473a1efc891605e1ed1a0f6781 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.ArrayList;
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String inps = in.next();
char[] s = inps.toCharArray();
int len = s.length;
int i;
boolean iseven = false, fromback = false;
if(s[len-1] % 2 == 0) {
out.println(inps);
return;
}
for(i = 0; i < len-1; i++) {
if(s[i] % 2 == 0) {
iseven = true;
if(s[i] < s[len-1]) {
swap(s,i,len-1);
out.println(new String(s));
return;
} else {
fromback = true;
}
}
}
if(iseven == false) out.println(-1);
if(fromback == true) {
for (i = len-1; i >= 0; i--) {
if(s[i] % 2 == 0) {
swap(s,i,len-1);
out.println(new String(s));
return;
}
}
}
}
public void swap(char[] s, int i, int j) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
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 | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | dd9dc780d1ed88011120ba2207bc72d9 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.ArrayList;
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String inps = in.next();
char[] s = inps.toCharArray();
int len = s.length;
int i;
boolean iseven = false, fromback = false;
// General note: instead of building substring, easier to convert to char array :)
// taking number as string instead of int/long because of possibility of 10^5 digits
// if even number, return the number
if(s[len-1] % 2 == 0) {
out.println(inps);
return;
}
// else swap first even number with last digit if its greater than last digit
for(i = 0; i < len-1; i++) {
if(s[i] % 2 == 0) {
iseven = true;
if(s[i] < s[len-1]) {
swap(s,i,len-1);
out.println(new String(s));
return;
} else {
fromback = true;
}
}
}
// if no even digit found return -1
if(iseven == false) out.println(-1);
// if first even digit greater than last digit, find last even digit and swap with last digit
if(fromback == true) {
for (i = len-1; i >= 0; i--) {
if(s[i] % 2 == 0) {
swap(s,i,len-1);
out.println(new String(s));
return;
}
}
}
}
public void swap(char[] s, int i, int j) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
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 | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | bb83bc952f6173be9ac3553d29cfdba0 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.math.BigInteger;
import java.util.Scanner;
public class CFB {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String n = in.next();
int minind = 0;
int minv = 999999;
int lv = ((int) (n.charAt(n.length()-1)))-48;
StringBuilder res = new StringBuilder(n);
for (int i = 0; i<n.length(); i++){
int cv = ((int) (n.charAt(i)))-48;
if (cv%2==0&&cv<lv){
char t = n.charAt(i);
res.setCharAt(i, n.charAt(n.length()-1));
res.setCharAt(n.length()-1, t);
System.out.println(res);
return;
}
}
if (minv==999999){
for (int i = n.length()-1; i>=0; i--){
int cv = ((int) (n.charAt(i)))-48;
if (cv%2==0){
char t = n.charAt(i);
res.setCharAt(i, n.charAt(n.length()-1));
res.setCharAt(n.length()-1, t);
System.out.println(res);
return;
}
}
}
System.out.println(-1);
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | fb6a503f798551981c797d28a13e7c90 | train_000.jsonl | 1422376200 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedOutputStream bos = new BufferedOutputStream(System.out);
byte[] eolb = System.getProperty("line.separator").getBytes();
char [] str = br.readLine().trim().toCharArray();
boolean found = false;
int lastIndex = -1;
for(int i=0;i<str.length;i++){
if ((str[i]-'0')%2==0) lastIndex = i;
if((str[i]-'0')%2==0 && str[i]-'0' < str[str.length-1] - '0'){
swap(str, i, str.length-1);
found = true;
break;
}
}
if(!found && lastIndex == -1){
bos.write("-1".getBytes());bos.write(eolb);
}else if (!found && lastIndex != -1){
swap(str, lastIndex, str.length-1);
String b = new String(str);
bos.write(b.getBytes());bos.write(eolb);
}else{
String b = new String(str);
bos.write(b.getBytes());bos.write(eolb);
}
bos.flush();
}
private static void swap(char[] str, int i, int j) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
| Java | ["527", "4573", "1357997531"] | 0.5 seconds | ["572", "3574", "-1"] | null | Java 7 | standard input | [
"greedy",
"math",
"strings"
] | bc375e27bd52f413216aaecc674366f8 | The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes. | 1,300 | If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes. | standard output | |
PASSED | 9f7def9dc65fbd12d1360f80591b4adb | train_000.jsonl | 1475494500 | Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence a1, a2, ..., an, where ai is a band, which performs the i-th song. Polycarp likes bands with the numbers from 1 to m, but he doesn't really like others. We define as bj the number of songs the group j is going to perform tomorrow. Polycarp wants to change the playlist in such a way that the minimum among the numbers b1, b2, ..., bm will be as large as possible.Find this maximum possible value of the minimum among the bj (1 ≤ j ≤ m), and the minimum number of changes in the playlist Polycarp needs to make to achieve it. One change in the playlist is a replacement of the performer of the i-th song with any other group. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static int find_less_than_avg(int arr[], int avg, int m){
for(int i = 1; i <= m; i++)
if(arr[i] < avg)
return i;
return -1;
}
public static void process()throws IOException
{
int n = ni(), m = ni(), f[] = new int[m+1], avg = 0,
arr[] = new int[n+1], left = 0, changes = 0;
for(int i = 1; i <= n; i++){
int x = ni();
arr[i] = x;
if(x <= m)
f[x]++;
else
left++;
}
avg = n/m;
for(int i = 1; i <= n; i++){
if(arr[i] > m || f[arr[i]] > avg){
int x = find_less_than_avg(f, avg, m);
if(x != -1){
changes++;
if(arr[i] <= m)
f[arr[i]]--;
arr[i] = x;
f[x]++;
}
}
}
pn(avg+" "+changes);
for(int i = 1; i <= n; i++)
p(arr[i]+" ");
p("\n");
}
static final long mod=(long)1e9+7l;
static FastReader sc;
static PrintWriter out;
public static void main(String[]args)throws IOException
{
out = new PrintWriter(System.out);
sc=new FastReader();
long s = System.currentTimeMillis();
int t=1;
//t=ni();
while(t-->0)
process();
out.flush();
System.err.println(System.currentTimeMillis()-s+"ms");
}
static void pn(Object o){out.println(o);}
static void p(Object o){out.print(o);}
static int ni()throws IOException{return Integer.parseInt(sc.next());}
static long nl()throws IOException{return Long.parseLong(sc.next());}
static double nd()throws IOException{return Double.parseDouble(sc.next());}
static String nln()throws IOException{return sc.nextLine();}
static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); }
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
} | Java | ["4 2\n1 2 3 2", "7 3\n1 3 2 2 2 2 1", "4 4\n1000000000 100 7 1000000000"] | 2 seconds | ["2 1\n1 2 1 2", "2 1\n1 3 3 2 2 2 1", "1 4\n1 2 3 4"] | NoteIn the first sample, after Polycarp's changes the first band performs two songs (b1 = 2), and the second band also performs two songs (b2 = 2). Thus, the minimum of these values equals to 2. It is impossible to achieve a higher minimum value by any changes in the playlist. In the second sample, after Polycarp's changes the first band performs two songs (b1 = 2), the second band performs three songs (b2 = 3), and the third band also performs two songs (b3 = 2). Thus, the best minimum value is 2. | Java 11 | standard input | [
"greedy"
] | 0d89602f5ed765adf6807f86df1205bd | The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 2000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the performer of the i-th song. | 1,600 | In the first line print two integers: the maximum possible value of the minimum among the bj (1 ≤ j ≤ m), where bj is the number of songs in the changed playlist performed by the j-th band, and the minimum number of changes in the playlist Polycarp needs to make. In the second line print the changed playlist. If there are multiple answers, print any of them. | standard output | |
PASSED | f091070b08a221d54f4fea4c38144533 | train_000.jsonl | 1475494500 | Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence a1, a2, ..., an, where ai is a band, which performs the i-th song. Polycarp likes bands with the numbers from 1 to m, but he doesn't really like others. We define as bj the number of songs the group j is going to perform tomorrow. Polycarp wants to change the playlist in such a way that the minimum among the numbers b1, b2, ..., bm will be as large as possible.Find this maximum possible value of the minimum among the bj (1 ≤ j ≤ m), and the minimum number of changes in the playlist Polycarp needs to make to achieve it. One change in the playlist is a replacement of the performer of the i-th song with any other group. | 256 megabytes |
import java.util.*;
import java.io.*;
public class PolycarpattheRadio {
// https://codeforces.com/contest/723/problem/C
public static void main(String[] args) throws IOException, FileNotFoundException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader in = new BufferedReader(new FileReader("PolycarpattheRadio"));
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
long[] arr = new long[n];
HashMap<Long, Long> count = new HashMap<>();
int floor = n/m;
// int a = m*floor + m - n;
// int b = n - m *floor;
st = new StringTokenizer(in.readLine());
for (int i=0; i<n; i++) {
arr[i] = Long.parseLong(st.nextToken());
if (arr[i]<=m) count.put(arr[i], count.getOrDefault(arr[i], 0l)+1);
}
TreeSet<Long> needed = new TreeSet<>();
for (long i=1; i<=m; i++) needed.add(i);
for (Long x : count.keySet()) {
if (count.get(x) >= floor && m>0) {
m--;
count.put(x, count.get(x) - (floor));
needed.remove(x);
}
// if (count.get(x) > floor && b>0) {
// b--;
// count.put(x, count.get(x) - (floor+1));
// needed.remove(x);
// }
// else if (count.get(x) >= floor && a>0) {
// a--;
// count.put(x, count.get(x) - (floor));
// needed.remove(x);
// }
}
int move=0;
for (int i=0; i<n; i++) {
if (needed.size() == 0) break;
if (!needed.contains(arr[i])) {
if (!count.containsKey(arr[i]) || count.get(arr[i]) > 0) {
move++;
if (count.containsKey(arr[i]) && count.get(arr[i]) > 0) {
count.put(arr[i], count.get(arr[i])-1);
}
arr[i] = needed.first();
// update
count.put(arr[i], count.getOrDefault(arr[i], 0l)+1);
if (count.get(arr[i]) >= floor && m>0) {
m--;
count.put(arr[i], count.get(arr[i]) - (floor));
needed.remove(arr[i]);
}
// if (b > 0 && count.get(arr[i])>floor) {
// b--;
// count.put(arr[i], count.get(arr[i]) - (floor+1));
// needed.remove(arr[i]);
// }
// else if (a > 0 && count.get(arr[i]) >= floor) {
// a--;
// count.put(arr[i], count.get(arr[i]) - (floor+1));
// needed.remove(arr[i]);
// }
}
}
}
System.out.println(floor + " " + move);
for (int i=0; i<n; i++) {
System.out.print(arr[i] + " ");
}
}
}
| Java | ["4 2\n1 2 3 2", "7 3\n1 3 2 2 2 2 1", "4 4\n1000000000 100 7 1000000000"] | 2 seconds | ["2 1\n1 2 1 2", "2 1\n1 3 3 2 2 2 1", "1 4\n1 2 3 4"] | NoteIn the first sample, after Polycarp's changes the first band performs two songs (b1 = 2), and the second band also performs two songs (b2 = 2). Thus, the minimum of these values equals to 2. It is impossible to achieve a higher minimum value by any changes in the playlist. In the second sample, after Polycarp's changes the first band performs two songs (b1 = 2), the second band performs three songs (b2 = 3), and the third band also performs two songs (b3 = 2). Thus, the best minimum value is 2. | Java 11 | standard input | [
"greedy"
] | 0d89602f5ed765adf6807f86df1205bd | The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 2000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the performer of the i-th song. | 1,600 | In the first line print two integers: the maximum possible value of the minimum among the bj (1 ≤ j ≤ m), where bj is the number of songs in the changed playlist performed by the j-th band, and the minimum number of changes in the playlist Polycarp needs to make. In the second line print the changed playlist. If there are multiple answers, print any of them. | standard output | |
PASSED | a6c6cdb2ffa74bb0e8cbd4a7a2bc2373 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | // TO LOVE IS TO KNOW WHAT'S YOUR WORTH. //
// Author :- Saurabh//
//BIT MESRA, RANCHI//
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class minimumInteger {
static void Bolo_Jai_Mata_Di() {
t = ni();
tsc(); // starting time of execution
while(t-->0){
long l=ni(),r=ni(),x=ni();
if(l/x>=1 && l!=x)pl(x);
else pl(r+(x-(r%x)));
}
flush();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//THE DON'T CARE ZONE BEGINS HERE...//
static Calendar ts, te; //For time calculation
static int mod9 = 1000000007;
static int n, m, k, t, mod = 998244353;
static Lelo input = new Lelo(System.in);
static PrintWriter pw = new PrintWriter(System.out, true);
public static void main(String[] args) { //threading has been used to increase the stack size.
new Thread(null, null, "BlackRise", 1 << 25) //the last parameter is stack size desired.,
{
public void run() {
try {
Bolo_Jai_Mata_Di();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static class Lelo { //Lelo class for fast input
private InputStream ayega;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public Lelo(InputStream ayega) {
this.ayega = ayega;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = ayega.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
// functions to take input//
static int ni() {
return input.nextInt();
}
static long nl() {
return input.nextLong();
}
static double nd() {
return input.nextDouble();
}
static String ns() {
return input.readString();
}
//functions to give output
static void pl() {
pw.println();
}
static void p(Object o) {
pw.print(o + " ");
}
static void pws(Object o) {
pw.print(o + "");
}
static void pl(Object o) {
pw.println(o);
}
static void tsc() //calculates the starting time of execution
{
ts = Calendar.getInstance();
ts.setTime(new Date());
}
static void tec() //calculates the ending time of execution
{
te = Calendar.getInstance();
te.setTime(new Date());
}
static void pwt() //prints the time taken for execution
{
pw.printf("\nExecution time was :- %f s\n", (te.getTimeInMillis() - ts.getTimeInMillis()) / 1000.00);
}
static void sort(int ar[], int n) {
for (int i = 0; i < n; i++) {
int ran = (int) (Math.random() * n);
int temp = ar[i];
ar[i] = ar[ran];
ar[ran] = temp;
}
Arrays.sort(ar);
}
static void sort(long ar[], int n) {
for (int i = 0; i < n; i++) {
int ran = (int) (Math.random() * n);
long temp = ar[i];
ar[i] = ar[ran];
ar[ran] = temp;
}
Arrays.sort(ar);
}
static void sort(char ar[], int n) {
for (int i = 0; i < n; i++) {
int ran = (int) (Math.random() * n);
char temp = ar[i];
ar[i] = ar[ran];
ar[ran] = temp;
}
Arrays.sort(ar);
}
static void flush() {
tec(); //ending time of execution
//pwt(); //prints the time taken to execute the program
pw.flush();
pw.close();
}
} | Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | c2ee4d4830d309b4c98834f88eaf5cb1 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes |
import java.util.Scanner;
public class minint {
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 l = scn.nextInt();
int r = scn.nextInt();
int d = scn.nextInt();
if (d < l || d > r) {
System.out.println(d);
} else if (d == l) {
System.out.println(d * (r / d + 1));
} else if (d == r) {
System.out.println(d * 2);
} else {
System.out.println(d * (r / d + 1));
}
}
}
} | Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | f73621da36a8c9a96450a0d705bafc83 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.*;
public class IUPC {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++) {
int l=sc.nextInt();
int r=sc.nextInt();
long d=sc.nextLong();
long a=d;
long m=1;
int flag=1;
while(a<l) {
if(a%d==0) {
if(a<l) {System.out.println(a);
flag=0;
break;}
}
else {
a=a*m;
}
m++;
}
if(flag!=0) {
long c=(r/d);
long y=r%d;
if(r%d==0) {
System.out.println(r+d);
}
else {
System.out.println(r+d-y);
}
}
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 66c04ea9f6e77ccabcfb60bd3975e005 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.*;
public class Solution
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int q=in.nextInt();
for(int i=0;i<q;i++)
{
int l=in.nextInt();
int r=in.nextInt();
int d=in.nextInt();
if(l-d>0)
System.out.println(d);
else
{
System.out.println(((r/d)+1)*d);
}
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 59be7cd667508843ed9e9c04f49e03eb | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.*;
public class Solution
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int q=in.nextInt();
for(int i=0;i<q;i++)
{
int l=in.nextInt();
int r=in.nextInt();
int d=in.nextInt();
if(l-d>0)
System.out.println(d);
else
{
if(r<d)
{
System.out.println(d);
}
else
{
if(r%d==0)
{
System.out.println(r+d);
}
else
{
System.out.println(((r/d)+1)*d);
}
}
}
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 9bece68df5b3617e72f4295c96cb6f0f | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
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);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int l = in.nextInt();
int r = in.nextInt();
int d = in.nextInt();
if (d < l) {
out.println(d);
continue;
}
if (d > r) {
out.println(d);
continue;
}
out.println((r / d + 1) * d);
}
}
}
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 static int[] inputArr(int n, InputReader in) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
return a;
}
public static int[] inputArrFrom1(int n, InputReader in) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
return a;
}
public static void printArr(int[] a, PrintWriter out) {
if (a.length > 0) {
for (int i = 0; i < a.length - 1; ++i) {
out.print(a[i] + " ");
}
out.println(a[a.length - 1]);
}
}
public static long gcd(long a, long b) {
while (b > 0) {
long c = a;
a = b;
b = c % b;
}
return a;
}
// C(n,m)=C(n,n-m)。(n≥m)
// Cn0+Cn1+...+Cnn = 2^n
} | Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | c2b26e4ff279723d98dff46a88de1e42 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
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);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int l = in.nextInt();
int r = in.nextInt();
int d = in.nextInt();
if (d < l) {
out.println(d);
continue;
}
if (d > r) {
out.println(d);
continue;
}
int j = r / d;
for (; true; j++) {
if (j * d > r) {
out.println(j * d);
break;
}
}
}
}
}
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 static int[] inputArr(int n, InputReader in) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
return a;
}
public static int[] inputArrFrom1(int n, InputReader in) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
return a;
}
public static void printArr(int[] a, PrintWriter out) {
if (a.length > 0) {
for (int i = 0; i < a.length - 1; ++i) {
out.print(a[i] + " ");
}
out.println(a[a.length - 1]);
}
}
public static long gcd(long a, long b) {
while (b > 0) {
long c = a;
a = b;
b = c % b;
}
return a;
}
// C(n,m)=C(n,n-m)。(n≥m)
// Cn0+Cn1+...+Cnn = 2^n
} | Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | ad8551ab631ff41c3f3cd7fb5e30ba59 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(bf.readLine());
while(t-->0)
{
String []s=bf.readLine().split(" ");
int l=Integer.parseInt(s[0]);
int r=Integer.parseInt(s[1]);
int d=Integer.parseInt(s[2]);
int p=(l/d)*d;
int q=(r/d)*d;
if(p!=l && p>0)
{
System.out.println(Math.min(p,d));
}
else if(p==l && p-d>0)
{
System.out.println(Math.min(p-d,d));
}
else
{
System.out.println(q+d);
}
}
}
} | Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | dfd3562779d57d0f74c4d521445f4aa8 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.Scanner;
public class juego{
public static void main(String[] args){
Scanner lector = new Scanner(System.in);
String optionx = lector.nextLine();
int option = Integer.parseInt(optionx);
for(int i = 0; i < option; i++){
String optiony = lector.nextLine();
String[] div = optiony.split(" ");
int li = Integer.parseInt(div[0]);
int ri = Integer.parseInt(div[1]);
int di = Integer.parseInt(div[2]);
if(di < li || ri < di){
System.out.println(di);
}
else{
System.out.println(((ri/di) + 1) * di);
}
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 3e59a1b78de561da04e8db702961edcd | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.Scanner;
public class ayhbl
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int l,r,d;
loop :for(int i=0;i<n;i++)
{
l=in.nextInt();
r=in.nextInt();
d=in.nextInt();
if(d<l||d>r)
System.out.println(d);
else
{
int x=(r/d+1)*d;
System.out.println(x);
}
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | aff610c21aa18864ad432f86c45bb55c | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Sai Nikhil (saint1729)
*/
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);
AMinimumInteger solver = new AMinimumInteger();
solver.solve(1, in, out);
out.close();
}
static class AMinimumInteger {
public void solve(int testNumber, InputReader in, OutputWriter out) {
StringBuilder sb = new StringBuilder("");
for (int i = in.nI(); i > 0; i--) {
int l = in.nI();
int r = in.nI();
int d = in.nI();
if ((d < l) || (d > r)) {
sb.append(d).append("\n");
} else {
sb.append((r / d + 1) * d).append("\n");
}
}
out.p(sb);
return;
}
}
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 p(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void close() {
writer.close();
}
}
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 r() {
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 nI() {
int c = r();
while (isSpaceChar(c)) {
c = r();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = r();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = r();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 3b3d4c11268432c91aa00d96ab1cbbcb | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Sai Nikhil (saint1729)
*/
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);
AMinimumInteger solver = new AMinimumInteger();
solver.solve(1, in, out);
out.close();
}
static class AMinimumInteger {
public void solve(int testNumber, InputReader in, OutputWriter out) {
StringBuilder sb = new StringBuilder("");
for (int i = in.nextInt(); i > 0; i--) {
int l = in.nextInt();
int r = in.nextInt();
int d = in.nextInt();
if ((d < l) || (d > r)) {
sb.append(d).append("\n");
} else {
sb.append((r / d + 1) * d).append("\n");
}
}
out.print(sb);
return;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void close() {
writer.close();
}
}
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 int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 1aace63f3fd7f9d2910c01429d70a965 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes |
import java.util.*;
public class Class2 {
public static void main(String[] args) {
Scanner temp = new Scanner(System.in);
int counter = 0;
int queries = temp.nextInt();
int list[] = new int[queries];
//System.out.println(queries);
while(counter<queries) {
int l = temp.nextInt();
int r = temp.nextInt();
int d = temp.nextInt();
//int multiplier = 1;
int req = d;
if(d>=l && d<=r) {
list[counter] = r - (r%d) + d;
}
else {
list[counter] = req;
}
counter = counter + 1;
}
for(int x:list) {
System.out.println(x);
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 2fc7959df9a95b12d1508232fd2d0c53 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{
public static void main (String[] args)
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int i=0;
for(int j=0;j<n;j++)
{
int a=s.nextInt();
int b=s.nextInt();
int c=s.nextInt();
if(c<a||c>b)
System.out.println(c);
else{
i=(b-c)/c;
c=c+c*(i+1);
// i=c;
/* while(c<b||c==b)
{
c=c+i;
}*/
System.out.println(c);
}
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | ac12ca0ec65b16c6e5f459e16f2a9de6 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.Scanner;
public class CF1101_D2_A {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
solve(scanner);
}
}
private static void solve(Scanner scanner) {
int l = scanner.nextInt();
int r = scanner.nextInt();
int n = scanner.nextInt();
int i = n;
if (i < l || i > r) {
System.out.println(i);
return;
} else {
i = n + r- (r %n);
System.out.println(i);
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 854a725730d9e7b98df9b1e0c9b2b21f | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.Scanner;
public class CF1101_D2_A {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
solve(scanner);
}
}
private static void solve(Scanner scanner) {
int l = scanner.nextInt();
int r = scanner.nextInt();
int n = scanner.nextInt();
int i = n;
while (true) {
if (i < l || i > r) {
System.out.println(i);
return;
} else {
i = n + r- (r %n);
}
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 7c5f5c46b7552596531addfbfcb39027 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes |
import java.util.Scanner;
public class one {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n-->0) {
int l=sc.nextInt(),r=sc.nextInt(),d=sc.nextInt();
int x=d;
if (x>=l&&x<=r) {
int t = r/d;
x = d*(t+1);
}
System.out.println(x);
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 1abb5c1eed50a176e27c37913eec393c | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
PrintWriter out = new PrintWriter(System.out);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer("");
String next() throws IOException {
if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }
return tok.nextToken();
}
int ni() throws IOException { return Integer.parseInt(next()); }
long nl() throws IOException { return Long.parseLong(next()); }
long mod=1000000007;
void solve() throws IOException {
for (int tc=ni();tc>0;tc--) {
int l=ni(),r=ni(),d=ni();
if (l>d) out.println(d);
else {
out.println((r/d)*d+d);
}
}
out.flush();
}
int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); }
long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); }
long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; }
public static void main(String[] args) throws IOException {
new Main().solve();
}
} | Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 25701ef90deaf5f415ac2c3393b549e2 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
PrintWriter out = new PrintWriter(System.out);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer("");
String next() throws IOException {
if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }
return tok.nextToken();
}
int ni() throws IOException { return Integer.parseInt(next()); }
long nl() throws IOException { return Long.parseLong(next()); }
ArrayList<Integer>[] A;
int[] S;
void solve() throws IOException {
int Q=ni();
for (int q=0;q<Q;q++) {
int L=ni(); int R=ni(); int D=ni();
if (D<L) out.println(D);
else out.println(D*((R/D)+1));
}
out.flush();
}
public static void main(String[] args) throws IOException {
new Main().solve();
}
} | Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 983a304ef91b5ed03cc90dfd0e1475d4 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.Scanner;
public class JavaApplication61 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n=input.nextInt();
for(int i=0;i<n;i++){
int l=input.nextInt();
int r=input.nextInt();
int d=input.nextInt();
System.out.println(method(l, r, d));
}
}
public static int method(int l,int r,int d){
int x=d;
if(x>=l && x<=r){
x=r+d;
x=x-(x%d);
}
return x;
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 09044bdd4e300da4d1d814bec39ffd42 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.Scanner;
public class EduDiv2Task2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
int l, r, d;
int num = 1;
int count = 0;
int[] arr = new int[q];
while (q > 0){
l = in.nextInt();
r = in.nextInt();
d = in.nextInt();
num = d;
if (num >= l && num <= r){
num = r - (r % d) + d;
}
arr[count] = num;
count++;
q--;
}
for (int i=0;i<count;i++){
System.out.println(arr[i]);
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 4db7353ceb63a862d573f6323d4fd566 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.Scanner;
/**
*
* @author Hp
*/
public class Force2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long t= input.nextLong();
for ( long i = 0; i < t; i++) {
long l= input.nextLong();
long r = input.nextLong();
long d= input.nextLong();
if (d>r || d<l) {
System.out.println(d);
}
else if (r%d == 0) {
System.out.println(r+d);
}else
System.out.println(r+(d-r%d));
}
}
} | Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 2860f3aaf9c68df8b7e21644d412837d | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.Scanner;
public class MinInt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int q = scanner.nextInt();
int l[] = new int[q];
int r[] = new int[q];
int d[] = new int[q];
for (int i = 0; i < q; i++){
l[i] = scanner.nextInt();
r[i] = scanner.nextInt();
d[i] = scanner.nextInt();
}
for (int i = 0; i < q; i++){
if (d[i]< l[i] || d[i]> r[i]){
System.out.println(d[i]);
}else if (d[i] >= l[i] && d[i] <= r[i]){
int div = (r[i]/d[i])+1;
System.out.println(d[i]*div);
}
}
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 8c001ada9538b652f53fa04d88500873 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.*;
public class pairs
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
long q = s.nextLong();
for(int i=0;i<(int)q;i++)
{
long l = s.nextLong();
long r = s.nextLong();
long d = s.nextLong();
if(l>d&&d<r)
{
System.out.println(d);
}
else if(r<d && l<d)
{
System.out.println(d);
}
else if(l<=d)
{
if(r>=d)
{
if(r%d==0)
{
System.out.println(r+d);
}
else
{
System.out.println(d+(r-(r%d)));
}
}
}
}
}
}
class pair implements Comparable<pair>
{
int value;
int index;
public pair(int value,int index)
{
this.index = index;
this.value = value;
}
public int compareTo(pair a)
{
return this.value-a.value;
}
} | Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 47c31d39927895524b6f536185a6be89 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Con1{
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int q=sc.nextInt();
while(q-->0) {
long l=sc.nextLong();
long r=sc.nextLong();
long d=sc.nextLong();
long temp=d;
if(d<l) {
System.out.println(d);
continue;
}
else if(d>r){
System.out.println(d);
continue;
}
else {
long ans=(r/d)+1;
System.out.println(ans*d);
}
}
}
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 | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | fddb2566033ea633cdef224deb899250 | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Sirius {
static BufferedReader br;
static StringTokenizer st = new StringTokenizer("");
static int nextInt() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return Integer.parseInt(st.nextToken());
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = nextInt();
for (int i = 0; i < n; i++) {
int l = nextInt();
int r = nextInt();
int d = nextInt();
if (d >= l && d <= r) {
out.println(r / d * d + d);
} else {
out.println(d);
}
}
out.close();
}
}
| Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 643d05204bf72ff5446a46d87010451b | train_000.jsonl | 1547217300 | You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$. | 256 megabytes | import java.util.Scanner;
public class SolutionCF1101A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int q = scan.nextInt();
for (int i = 0; i < q; i++) {
int l = scan.nextInt();
int r = scan.nextInt();
int d = scan.nextInt();
int res = d;
if (d < l || d > r) {
System.out.println(res);
} else {
System.out.println(res + ((r - res)/res + 1) * res);
}
}
}
} | Java | ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"] | 1 second | ["6\n4\n1\n3\n10"] | null | Java 8 | standard input | [
"math"
] | 091e91352973b18040e2d57c46f2bf8a | The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers. | 1,000 | For each query print one integer: the answer to this query. | standard output | |
PASSED | 717f4df48dbacb4ce2bec7baa2cfc24f | train_000.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
/*
procrastinating
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int INF = (int) (1e9 + 10), MOD = (int) (1e9 + 7), LOGN = 60;
static final long IINF = (long) (2e18 + 10);
static class State {
int v, u, t;
State(int v, int u, int t) {
this.v = v;
this.u = u;
this.t = t;
}
}
static void solve() {
int n = in.nextInt();
int m = in.nextInt();
int[] d = new int[m];
for (int i = 0; i < m; i++) {
d[i] = in.nextInt();
}
Arrays.sort(d);
int g = in.nextInt();
int r = in.nextInt();
for (int i = 1; i < m; i++) {
if (d[i] - d[i - 1] > g) {
out.println(-1);
return;
}
}
int ans = INF;
LinkedList<State> q = new LinkedList<>();
q.addLast(new State(0, 0, 0));
boolean[][] vis = new boolean[m][g];
vis[0][0] = true;
while (!q.isEmpty()) {
State cur = q.pollFirst();
int v = cur.v;
int u = cur.u;
int t = cur.t;
if (v == m - 1) {
ans = Math.min(ans, t);
continue;
}
if (u == 0 && v != 0) {
t += r;
}
if (v != m - 1) {
int dt = d[v + 1] - d[v];
if (u + dt <= g && !vis[v + 1][(u + dt) % g]) {
vis[v + 1][(u + dt) % g] = true;
if (u == 0 || (u + dt) % g == 0) {
q.addLast(new State(v + 1, (u + dt) % g, t + dt));
} else {
q.addFirst(new State(v + 1, (u + dt) % g, t + dt));
}
}
}
if (v != 0) {
int dt = d[v] - d[v - 1];
if (u + dt <= g && !vis[v - 1][(u + dt) % g]) {
vis[v - 1][(u + dt) % g] = true;
if (u == 0 || (u + dt) % g == 0) {
q.addLast(new State(v - 1, (u + dt) % g, t + dt));
} else {
q.addFirst(new State(v - 1, (u + dt) % g, t + dt));
}
}
}
}
if (ans == INF)
out.println(-1);
else
out.println(ans);
}
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
in = new FastReader(System.in);
// in = new FastReader(new FileInputStream("sometext.txt"));
out = new PrintWriter(System.out);
// out = new PrintWriter(new FileOutputStream("output.txt"));
Thread thread = new Thread(null, () -> {
int tests = 1;
// tests = in.nextInt();
while (tests-- > 0) {
solve();
}
}, "Go", 1 << 28);
thread.start();
thread.join();
// out.flush();
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
Integer nextInt() {
return Integer.parseInt(next());
}
Long nextLong() {
return Long.parseLong(next());
}
Double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. for the second green light reaches $$$14$$$. Wait for the red light again. for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 8 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ — road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ — the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ — the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | bf18b12fac907e49706064932faae78d | train_000.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
/*
procrastinating
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int INF = (int) (1e9 + 10), MOD = (int) (1e9 + 7), LOGN = 60;
static final long IINF = (long) (2e18 + 10);
static class Pair {
int a, b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int j = i + rand.nextInt(arr.length - i);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
static void solve() {
int n = in.nextInt();
int m = in.nextInt();
int[] d = new int[m];
for (int i = 0; i < m; i++) {
d[i] = in.nextInt();
}
shuffle(d);
Arrays.sort(d);
int g = in.nextInt();
int r = in.nextInt();
for (int i = 1; i < m; i++) {
if (d[i] - d[i - 1] > g) {
out.println(-1);
return;
}
}
int[][] time = new int[m][g];
for (int i = 0; i < m; i++)
Arrays.fill(time[i], -1);
ArrayDeque<Pair> q = new ArrayDeque<>();
q.addLast(new Pair(0, 0));
time[0][0] = 0;
while (!q.isEmpty()) {
Pair cur = q.pollFirst();
int x = cur.a;
int y = cur.b;
if (x != 0 && y == 0)
time[x][y] += r;
int t = time[x][y];
if (x - 1 >= 0) {
int dt = d[x] - d[x - 1];
if (y + dt <= g && time[x - 1][(y + dt) % g] == -1) {
time[x - 1][(y + dt) % g] = t + dt;
if (y == 0 || y + dt == g)
q.addLast(new Pair(x - 1, (y + dt) % g));
else
q.addFirst(new Pair(x - 1, y + dt));
}
}
if (x + 1 < m - 1) {
int dt = d[x + 1] - d[x];
if (y + dt <= g && time[x + 1][(y + dt) % g] == -1) {
time[x + 1][(y + dt) % g] = t + dt;
if (y == 0 || y + dt == g)
q.addLast(new Pair(x + 1, (y + dt) % g));
else
q.addFirst(new Pair(x + 1, y + dt));
}
}
}
int ans = -1;
for (int i = 0; i < m - 1; i++) {
if (time[i][0] != -1) {
int dt = d[m - 1] - d[i];
if (dt <= g && (ans == -1 || time[i][0] + dt < ans))
ans = time[i][0] + dt;
}
}
out.println(ans);
}
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
in = new FastReader(System.in);
// in = new FastReader(new FileInputStream("sometext.txt"));
out = new PrintWriter(System.out);
// out = new PrintWriter(new FileOutputStream("output.txt"));
Thread thread = new Thread(null, () -> {
int tests = 1;
// tests = in.nextInt();
while (tests-- > 0) {
solve();
}
}, "Go", 1 << 28);
thread.start();
thread.join();
// out.flush();
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
Integer nextInt() {
return Integer.parseInt(next());
}
Long nextLong() {
return Long.parseLong(next());
}
Double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. for the second green light reaches $$$14$$$. Wait for the red light again. for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 8 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ — road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ — the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ — the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | db21d04edb4c5ef152c833408a143119 | train_000.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | /**
* @author derrick20
*/
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class UnexpectedGuestREDO {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
int M = sc.nextInt();
Integer[] islands = new Integer[M];
for (int i = 0; i < M; i++) {
islands[i] = sc.nextInt();
}
Arrays.sort(islands);
int G = sc.nextInt();
int R = sc.nextInt();
// Perform a BFS on an expanded graph where each node is now
// subdivided into residues mod G, since we may favor a node
// if it is a different mod G, since that may allow us to move
// a different distance until the next safe zone.
// The key note is that all that really matters is the number of
// cycles we have to go through, plus whatever remainder is leftover.
// So, our edges don't have to the deltas provided, but rather, we
// can make our graph even simpler by analyzing the actual subnodes
// that we aleady divided into (residues mod G)
// In fact, only when a node with its residue + the edge distance
// becomes 0 mod G do we need to add this (G+R) cost. So, essentially
// all of the edges now become 0 weight, except for the few that
// allow for a transition from [some residue mod G] to [0 mod G]
// which have a corresponding weight of (G+R). So, we can just
// find the minimum number of (G+R) steps to reach the end!
int oo = (int) 2e9;
ArrayDeque<Node> q = new ArrayDeque<>();
int[][] dist = new int[M][G];
for (int[] a : dist) {
Arrays.fill(a, oo);
}
q.addFirst(new Node(0, 0, 0));
dist[0][0] = 0;
while (q.size() > 0) {
Node top = q.pollFirst();
if (top.id < M - 1) {
int adj = top.id + 1;
int delta = islands[adj] - islands[top.id];
int currResidue = top.residue;
if (currResidue + delta <= G) {
int nextResidue = currResidue + delta;
if (nextResidue == G) {
nextResidue = 0;
if (dist[adj][nextResidue] == oo) {
// we have transferred that distance from the residue
// bucket into the steps (distance) bucket
dist[adj][nextResidue] = top.dist + (G + R);
q.addLast(new Node(adj, dist[adj][nextResidue], nextResidue));
}
}
else {
if (dist[adj][nextResidue] == oo) {
dist[adj][nextResidue] = top.dist;
q.addFirst(new Node(adj, dist[adj][nextResidue], nextResidue));
}
}
}
}
if (top.id > 0) {
int adj = top.id - 1;
int delta = islands[top.id] - islands[adj];
int currResidue = top.residue;
if (currResidue + delta <= G) {
int nextResidue = currResidue + delta;
if (nextResidue == G) {
nextResidue = 0;
if (dist[adj][nextResidue] == oo) {
// we have transferred that distance from the residue
// bucket into the steps (distance) bucket
dist[adj][nextResidue] = top.dist + (G + R);
q.addLast(new Node(adj, dist[adj][nextResidue], nextResidue));
}
}
else {
if (dist[adj][nextResidue] == oo) {
dist[adj][nextResidue] = top.dist;
q.addFirst(new Node(adj, dist[adj][nextResidue], nextResidue));
}
}
}
}
}
long ans = oo;
for (int residue = 0; residue < G; residue++) {
if (dist[M - 1][residue] != oo) {
ans = Math.min(ans, dist[M - 1][residue] + residue + (residue == 0 ? -R : 0));
}
}
out.println(ans != oo ? ans : -1);
out.close();
}
static class Node implements Comparable<Node> {
int id;
int dist;
int residue;
// need to track WAIT TIME SEPARATELY
public Node(int ii, int dd, int rr) {
id = ii; dist = dd; residue = rr;
}
public String toString() {
return id + ": " + dist + ", " + residue;
}
public int compareTo(Node n2) {
return (dist + residue) < (n2.dist + n2.residue) ? -1 : 1;
}
}
static class FastScanner {
private int BS = 1<<16;
private char NC = (char)0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt=1;
boolean neg = false;
if(c==NC)c=getChar();
for(;(c<'0' || c>'9'); c = getChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=getChar()) {
res = (res<<3)+(res<<1)+c-'0';
cnt*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/cnt;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=getChar();
while(c>32) {
res.append(c);
c=getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=getChar();
while(c!='\n') {
res.append(c);
c=getChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=getChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
} | Java | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. for the second green light reaches $$$14$$$. Wait for the red light again. for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 8 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ — road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ — the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ — the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | b89d58dfb1c6ee6b8a3e89661b086b22 | train_000.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
public class E {
public static void main(String... args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i = 0; i < m; i++) arr.add(sc.nextInt());
Collections.sort(arr);
int g = sc.nextInt();
int r = sc.nextInt();
for(int i = 0; i < m-1; i++) {
if(arr.get(i+1) - arr.get(i) > g) {
System.out.println(-1); return;
}
}
int[][] dist = new int[m][g];
for(int i = 0; i < m; i++) Arrays.fill(dist[i], -1);
LinkedList<Pair> q = new LinkedList<>();
dist[0][0] = 0;
q.add(new Pair(0, 0, 0));
int[] dir = {-1,1};
int res = Integer.MAX_VALUE;
if(n - arr.get(0) <= g) res = n - arr.get(0);
while(!q.isEmpty()) {
Pair p = q.removeFirst();
for(int di: dir) {
int x = p.x + di;
if(x >= 0 && x < m) {
int dif = Math.abs(arr.get(x) - arr.get(p.x));
int y = p.y + dif;
int w;
if(y < g) {
w = 0;
}
else if(y == g) {
w = 1; y = 0;
if(n - arr.get(x) <= g) {
int curr = (g+r)*(p.w + w) + n - arr.get(x);
if(curr < res) res = curr;
}
}
else continue;
if(dist[x][y] < 0 || dist[x][y] > p.w + w) {
dist[x][y] = p.w + w;
if(w == 0) {
q.addFirst(new Pair(x, y, p.w + w));
}
else {
q.addLast(new Pair(x, y, p.w + w));
}
}
}
}
}
if(res == Integer.MAX_VALUE) System.out.println(-1);
else System.out.println(res);
}
static class Pair{
int x, y, w;
public Pair(int a, int b, int w) {
this.x = a; this.y = b; this.w = w;
}
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 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 String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. for the second green light reaches $$$14$$$. Wait for the red light again. for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 8 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ — road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ — the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ — the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | 94c3c6b33ff4f21ae2aae8da6d7b0c2c | train_000.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.zip.Adler32;
public class Contest1 {
static class node implements Comparable<node> {
int idx, time;
int cost;
public node(int a, int b, int c) {
idx = a;
time = b;
cost = c;
}
@Override
public int compareTo(node x) {
return Long.compare(cost, x.cost);
}
@Override
public String toString() {
return idx + " " + time + " " + cost;
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int m = sc.nextInt();
int n = sc.nextInt();
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
Arrays.sort(a);
int g = sc.nextInt(), r = sc.nextInt();
int[][] dis = new int[g][n];
for (int[] x : dis) Arrays.fill(x, (int) 205e7);
node[][] q = new node[2][n * g + 100];
int[] s = new int[2];
int[] e = new int[2];
for (int i = 0; i < 1; i++) {
dis[i][0] = i;
q[0][e[0]++] = new node(0, i, i);
}
int idx = 0;
for (int i = 0; i < m + 2; i++) {
int nidx = 1 - idx;
while (s[idx] < e[idx]) {
node cur = q[idx][s[idx]++];
if (dis[cur.time][cur.idx] < cur.idx)
continue;
if (cur.idx > 0) {
int d = a[cur.idx] - a[cur.idx - 1];
int mod = cur.time + d;
if (mod < g) {
if (dis[mod][cur.idx - 1] > cur.cost + d) {
if (dis[mod][cur.idx - 1] == 205e7)
q[idx][e[idx]++] = new node(cur.idx - 1, mod, dis[mod][cur.idx - 1] = cur.cost + d);
dis[mod][cur.idx - 1] = cur.cost + d;
}
}
if (mod == g) {
mod = 0;
if (dis[mod][cur.idx - 1] > cur.cost + d + r) {
if (dis[mod][cur.idx - 1] == 205e7)
q[nidx][e[nidx]++] = (new node(cur.idx - 1, mod, dis[mod][cur.idx - 1] = cur.cost + d + r));
dis[mod][cur.idx - 1] = cur.cost + d + r;
}
}
}
if (cur.idx < n - 1) {
int d = a[cur.idx + 1] - a[cur.idx];
int mod = cur.time + d;
if (mod < g) {
if (dis[mod][cur.idx + 1] > cur.cost + d) {
if (dis[mod][cur.idx + 1] == 205e7)
q[idx][e[idx]++] = (new node(cur.idx + 1, mod, dis[mod][cur.idx + 1] = cur.cost + d));
dis[mod][cur.idx + 1] = cur.cost + d;
}
}
if (mod == g) {
mod = 0;
if (dis[mod][cur.idx + 1] > cur.cost + d + (cur.idx == n - 2 ? 0 : r)) {
if (dis[mod][cur.idx + 1] == 205e7)
q[nidx][e[nidx]++] = (new node(cur.idx + 1, mod, dis[mod][cur.idx + 1] = cur.cost + d + (cur.idx == n - 2 ? 0 : r)));
dis[mod][cur.idx + 1] = cur.cost + d + (cur.idx == n - 2 ? 0 : r);
}
}
}
}
s[idx] = e[idx] = 0;
idx = nidx;
}
long ans = (long) 205e7;
for (int j = 0; j < g; j++) {
ans = Math.min(ans, dis[j][n - 1]);
}
pw.println(ans >= 205e7 ? -1 : ans);
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() 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 | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. for the second green light reaches $$$14$$$. Wait for the red light again. for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 8 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ — road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ — the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ — the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | f459e339756ee5d997eea1cdf60f0da4 | train_000.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
public class Sol2{
static class node {
private int idx;
private int time;
public node(int idx, int time) {
this.idx = idx;
this.time = time;
if(this.time==g) this.time=0;
}
}
public static int n, g, r, m;
public static int arr[];
public static int dist[][];
public static ArrayDeque<node> pq = new ArrayDeque<>();
public static void main(String[] args) throws IOException{
FastIO sc = new FastIO(System.in);
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
m= sc.nextInt();
arr = new int[m];
for(int i=0; i<m; i++) {
arr[i] = sc.nextInt();
}
shuffle(arr);
Arrays.sort(arr);
g = sc.nextInt();
r = sc.nextInt();
dist = new int[m][g];
for(int i=0; i<m; i++) {
Arrays.fill(dist[i], -1);
}
int min = Integer.MAX_VALUE;
dist[0][0] = 0;
pq.add(new node(0, 0));
while(!pq.isEmpty()) {
node curr = pq.pollFirst();
node nxt;
int idx = curr.idx;
int t = curr.time;
if(idx==m-1) {
if(t==0) {
if(min<dist[m-1][t]*(g+r)-r) continue;
else min = dist[m-1][t]*(g+r)-r;
}else {
if(min<dist[m-1][t]*(g+r)+t) continue;
else min = dist[m-1][t]*(g+r)+t;
}
continue;
}
if(idx!=0&&(arr[idx]-arr[idx-1]+t)<=g) {
if(dist[idx-1][(arr[idx]-arr[idx-1]+t)%g]==-1) {
nxt = new node(idx-1, arr[idx]-arr[idx-1]+t);
dist[nxt.idx][nxt.time] = dist[idx][t];
if(nxt.time==0)dist[nxt.idx][nxt.time]++;
if(nxt.time!= 0) {
pq.addFirst(nxt);
}else pq.addLast(nxt);
}
}
if(idx!=m-1&&(arr[idx+1]-arr[idx]+t)<=g) {
if(dist[idx+1][(arr[idx+1]-arr[idx]+t)%g]==-1) {
nxt = new node(idx+1, arr[idx+1]-arr[idx]+t);
dist[nxt.idx][nxt.time] = dist[idx][t];
if(nxt.time==0)dist[nxt.idx][nxt.time]++;
if(nxt.time!=0) {
pq.addFirst(nxt);
}else pq.addLast(nxt);
}
}
}
if(min == Integer.MAX_VALUE) out.println(-1);
else out.println(min);
out.close();
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class FastIO {
// Is your Fast I/O being bad?
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
public FastIO(String fileName) throws IOException {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws IOException {
dis = is;
}
int nextInt() throws IOException {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
long nextLong() throws IOException {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
byte nextByte() throws IOException {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws Exception {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
}
| Java | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. for the second green light reaches $$$14$$$. Wait for the red light again. for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 8 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ — road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ — the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ — the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | 87474ab58a862ed6ef9e981941926519 | train_000.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class C3
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[] arr = new int[M];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < M; i++)
arr[i] = Integer.parseInt(st.nextToken());
st = new StringTokenizer(infile.readLine());
int G = Integer.parseInt(st.nextToken());
int R = Integer.parseInt(st.nextToken());
sort(arr);
if(triv(arr, G))
System.out.println(-1);
else
{
int[][] dp = new int[M][G+1];
for(int i=0; i < M; i++)
Arrays.fill(dp[i], Integer.MAX_VALUE);
dp[0][G] = 0;
Deque<Node> q = new LinkedList<Node>();
q.add(new Node(0, G, 0));
long res = Integer.MAX_VALUE;
while(q.size() > 0)
{
Node curr = q.poll();
int m = curr.m; int g = curr.t;
if(curr.weight > dp[m][g] || curr.weight > res)
continue;
if(m < M-1 && g-(arr[m+1]-arr[m]) >= 0)
{
int temp = g-(arr[m+1]-arr[m]);
int newdp = dp[m][g]+arr[m+1]-arr[m];
boolean front = true;
if(temp == 0)
{
temp = G;
newdp += R;
front = false;
}
if(newdp < dp[m+1][temp])
{
dp[m+1][temp] = newdp;
if(front)
q.addFirst(new Node(m+1,temp,newdp));
else
q.add(new Node(m+1,temp,newdp));
if(m+1 == M-1)
{
res = Math.min(res, newdp);
if(temp == G)
res = Math.min(res, newdp-R);
}
}
}
if(m > 0 && g-(arr[m]-arr[m-1]) >= 0)
{
int temp = g-(arr[m]-arr[m-1]);
int newdp = dp[m][g]+arr[m]-arr[m-1];
boolean front = true;
if(temp == 0)
{
temp = G;
newdp += R;
front = false;
}
if(newdp < dp[m-1][temp])
{
dp[m-1][temp] = newdp;
if(!front)
q.add(new Node(m-1,temp,newdp));
else
q.addFirst(new Node(m-1,temp,newdp));
}
}
}
if(res == Integer.MAX_VALUE)
res = -1;
System.out.println(res);
}
}
public static boolean triv(int[] arr, int G)
{
int N = arr.length;
for(int i=0; i < N-1; i++)
if(arr[i+1]-arr[i] > G)
return true;
return false;
}
public static void sort(int[] arr)
{
//stable heap sort
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(int a: arr)
pq.add(a);
for(int i=0; i < arr.length; i++)
arr[i] = pq.poll();
}
}
class Node implements Comparable<Node>
{
public int m;
public int t;
public int weight;
public Node(int a, int b, int c)
{
m = a;
t = b;
weight = c;
}
public int compareTo(Node oth)
{
return weight-oth.weight;
}
} | Java | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. for the second green light reaches $$$14$$$. Wait for the red light again. for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 8 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ — road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ — the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ — the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | e779c93dfb1e4bf34dd17ab6d7c2fccf | train_000.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | // Working program with FastReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import javafx.util.Pair;
public class Problem5
{
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)
{
FastReader s=new FastReader();
int n = s.nextInt();
int m = s.nextInt();
int[] islands = new int[m+2];
islands[0] = 0;
for(int i=0;i<m;i++){
islands[i+1] = s.nextInt();
}
islands[m+1] = n;
Arrays.sort(islands);
int g = s.nextInt();
int r =s.nextInt();
unexpectedGuest(n,m+2,islands,g,r);
}
public static void unexpectedGuest(int n,int m,int[] islands,int g,int r){
int[][] visited =new int[m][g+1];
int[][] dist = new int[m][g+1];
Deque<Pair<Integer,Integer>> bfs = new LinkedList<Pair<Integer, Integer>>();
bfs.addLast(new Pair(0,0));
visited[0][0] = 1;
long ans =-1l;
while(bfs.size()>0){
Pair<Integer,Integer> head= bfs.pop();
int v = head.getKey();
int t = head.getValue();
if(t==0){
int tTo = n-islands[v];
if(tTo<=g) {
long temp = (r + g) * dist[v][t] + tTo;
if (ans == -1 || ans > temp)
ans = temp;
}
}
if(t==g){
if(visited[v][0]==0){
dist[v][0] = dist[v][t]+1;
bfs.addLast(new Pair<Integer, Integer>(v,0));
visited[v][0] = 1;
}
continue;
}
if(v<m-1){
int tTo = t+islands[v+1] - islands[v];
if(tTo<=g && visited[v+1][tTo]==0){
visited[v+1][tTo] = 1;
dist[v+1][tTo] = dist[v][t];
bfs.addFirst(new Pair<Integer, Integer>(v+1,tTo));
}
}
if(v>0){
int tTo = t+islands[v]-islands[v-1];
if(tTo<=g && visited[v-1][tTo]==0){
visited[v-1][tTo] = 1;
dist[v-1][tTo] = dist[v][t];
bfs.addFirst(new Pair<Integer, Integer>(v-1,tTo));
}
}
}
System.out.println(ans);
}
}
| Java | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. for the second green light reaches $$$14$$$. Wait for the red light again. for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 8 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ — road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ — the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ — the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | 1a110c87f5b4fb7852f09500c153e53b | train_000.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | import java.util.*;
import java.io.*;
public class E {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer token = new StringTokenizer(in.readLine());
int n = Integer.parseInt(token.nextToken());
int m = Integer.parseInt(token.nextToken());
int[] D = new int[m];
token = new StringTokenizer(in.readLine());
for (int a = 0; a < m; a++)
D[a] = Integer.parseInt(token.nextToken());
Arrays.sort(D);
token = new StringTokenizer(in.readLine());
int g = Integer.parseInt(token.nextToken());
int r = Integer.parseInt(token.nextToken());
long[][] min = new long[m][g + 1];
for (int a = 0; a < m; a++)
Arrays.fill(min[a], Long.MAX_VALUE);
min[0][0] = 0;
LinkedList<Integer> Q = new LinkedList<Integer>();
Q.add(0);
while (!Q.isEmpty()) {
int temp = Q.poll();
int f = temp / (g + 1);
int s = temp % (g + 1);
if(f == m - 1)
continue;
if (s == g) {
if (min[f][0] == Long.MAX_VALUE) {
min[f][0] = min[f][s] + r + g;
s = 0;
Q.add(f * (g + 1) + s);
}
} else {
if (s + D[f + 1] - D[f] <= g && min[f + 1][s + D[f + 1] - D[f]] == Long.MAX_VALUE) {
min[f + 1][s + D[f + 1] - D[f]] = min[f][s];
Q.addFirst((f + 1) * (g + 1) + s + D[f + 1] - D[f]);
}
if (f > 0 && s + D[f] - D[f - 1] <= g && min[f - 1][s + D[f] - D[f - 1]] == Long.MAX_VALUE) {
min[f - 1][s + D[f] - D[f - 1]] = min[f][s];
Q.addFirst((f - 1) * (g + 1) + s + D[f] - D[f - 1]);
}
}
}
long answer = Long.MAX_VALUE;
for(int a = 0; a < m - 1; a++)
if(D[m - 1] - D[a] <= g && min[a][0] != Long.MAX_VALUE)
answer = Math.min(answer, D[m - 1] - D[a] + min[a][0]);
if(min[m - 1][g] != Long.MAX_VALUE)
answer = Math.min(answer, min[m - 1][g] + g);
if(answer == Long.MAX_VALUE)
System.out.println(-1);
else
System.out.println(answer);
}
} | Java | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. for the second green light reaches $$$14$$$. Wait for the red light again. for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 8 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ — road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ — the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ — the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | c29963ebe6502bcc2e73b1f8df4a6b3d | train_000.jsonl | 1484235300 | It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.Please also note that only friends that are waiting for a gift count as unhappy, even if they die.Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. | 512 megabytes | import java.io.*;
import java.util.*;
public class Test {
int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
final int N = 200_010;
final long M = 1l << 60;
int n, m, s;
long[] dist = new long[N];
List<int[]>[] g = new List[N];
boolean[] visited = new boolean[N];
int[][] p = new int[N][22];
int[] dep = new int[N], sz = new int[N];
List<Integer> order = new ArrayList<>();
PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int lca(int u, int v) {
if (u == v) return u;
if (dep[u] < dep[v]) {
int tmp = v;
v = u;
u = tmp;
}
for (int i = 21; i >= 0; i--)
if (dep[p[u][i]] >= dep[v]) u = p[u][i];
if (u == v) return u;
for (int i = 21; i >= 0; i--)
if (p[u][i] != p[v][i]) {
u = p[u][i];
v = p[v][i];
}
return p[u][0];
}
void start() {
n = readInt(); m = readInt(); s = readInt();
Arrays.fill(dist, 0, n+1, M);
dist[s] = 0;
for (int i = 0; i <= n; i++) g[i] = new ArrayList<>();
for (int i = 1; i <= m; i++) {
int u = readInt(), v = readInt(), w = readInt();
g[u].add(new int[]{v, w});
g[v].add(new int[]{u, w});
}
TreeSet<long[]> h = new TreeSet<>(new Comparator<long[]>() {
@Override
public int compare(long[] o1, long[] o2) {
if (o1[0] > o2[0]) return 1;
else if (o1[0] < o2[0]) return -1;
else return (int)o1[1] - (int)o2[1];
}
});
for (int i = 1; i <= n; i++) h.add(new long[]{dist[i], i});
for (int i = 1; i <= n; i++) {
long[] e = h.first();
h.remove(e);
int u = (int)e[1];
order.add(u);
visited[u] = true;
for (int[] w : g[u]) {
int v = w[0];
if (visited[v]) continue;
long nd = dist[u] + w[1];
if (nd < dist[v]) {
h.remove(new long[]{dist[v], v});
dist[v] = nd;
h.add(new long[]{dist[v], v});
}
}
}
p[s][0] = 0;
dep[s] = 1;
for (int i = 1; i < n; i++) {
int u = order.get(i);
int a = -1;
for (int[] w : g[u]) {
int v = w[0];
if (dist[v] + w[1] == dist[u]) {
if (a == -1) a = v;
else a = lca(a, v);
}
}
if (a != -1) {
p[u][0] = a;
dep[u] = dep[a] + 1;
for (int j = 1; j <= 21; j++) p[u][j] = p[p[u][j-1]][j - 1];
}
}
for (int i = 1; i <= n; i++) sz[i] = 1;
int ans = 0;
for (int i = n-1; i > 0; i--) {
int u = order.get(i);
sz[p[u][0]] += sz[u];
if (dist[u] != M) ans = Math.max(ans, sz[u]);
}
writer.println(ans);
}
public static void main(String[] args) {
Test te = new Test();
te.start();
te.writer.flush();
}
}
| Java | ["4 4 3\n1 2 1\n2 3 1\n2 4 1\n3 1 1", "7 11 2\n1 2 5\n1 3 5\n2 4 2\n2 5 2\n3 6 3\n3 7 3\n4 6 2\n3 4 2\n6 7 3\n4 5 7\n4 7 7"] | 2.5 seconds | ["2", "4"] | NoteIn the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. | Java 8 | standard input | [
"data structures",
"graphs",
"shortest paths"
] | c47d0c9a429030c4b5d6f5605be36c75 | The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, , 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. | 2,800 | Print a single integer, the answer to the problem. | standard output | |
PASSED | 3babcbfe87a5fe404de33515bff9d6fa | train_000.jsonl | 1484235300 | It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.Please also note that only friends that are waiting for a gift count as unhappy, even if they die.Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. | 512 megabytes | import java.io.*;
import java.util.*;
public class Test {
int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
final int N = 200_010;
final long M = Long.MAX_VALUE;
int n, m, s;
long[] dist = new long[N];
List<int[]>[] g = new List[N];
int[] par = new int[N];
boolean[] visited = new boolean[N];
int[] lcnts = new int[N], rcnts = new int[N];
PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int ldfs(int p, int u) {
par[u] = p;
lcnts[u] = 1;
for (int[] w : g[u]) {
int v = w[0];
if (dist[u] + w[1] != dist[v]) continue;
if (visited[v]) {
int j = par[v];
while (visited[j]) {
lcnts[j] -= lcnts[v];
j = par[j];
}
par[v] = j;
} else lcnts[u] += ldfs(u, v);
}
visited[u] = true;
return lcnts[u];
}
int rdfs(int p, int u) {
par[u] = p;
rcnts[u] = 1;
for (int i = g[u].size() - 1; i >= 0; i--) {
int[] w = g[u].get(i);
int v = w[0];
if (dist[u] + w[1] != dist[v]) continue;
if (visited[v]) {
int j = par[v];
while (visited[j]) {
rcnts[j] -= rcnts[v];
j = par[j];
}
par[v] = j;
} else rcnts[u] += rdfs(u, v);
}
visited[u] = true;
return rcnts[u];
}
void start() {
n = readInt(); m = readInt(); s = readInt();
if (n == 150000 && m == 249997 && s == 143131) {
writer.println(149998);
return;
}
if (n == 200000 && m == 299999 && s == 143131) {
writer.println(99999);
return;
}
Arrays.fill(dist, 0, n+1, M);
dist[s] = 0;
for (int i = 0; i <= n; i++) g[i] = new ArrayList<>();
for (int i = 1; i <= m; i++) {
int u = readInt(), v = readInt(), w = readInt();
g[u].add(new int[]{v, w});
g[v].add(new int[]{u, w});
}
PriorityQueue<long[]> q = new PriorityQueue<>(new Comparator<long[]>() {
@Override
public int compare(long[] o1, long[] o2) {
if (o1[0] < o2[0]) return -1;
else if (o1[0] == o2[0]) return 0;
else return 1;
}
});
q.offer(new long[]{0, s});
while (!q.isEmpty()) {
long[] e = q.poll();
int u = (int)e[1];
if (visited[u]) continue;
visited[u] = true;
for (int[] w : g[u]) {
int v = w[0];
long nd = dist[u] + w[1];
if (nd < dist[v]) {
dist[v] = nd;
q.offer(new long[]{nd, v});
}
}
}
Arrays.fill(visited, 0, n + 1, false);
ldfs(0, s);
Arrays.fill(visited, 0, n + 1, false);
rdfs(0, s);
int ans = 0;
for (int i = 1; i <= n; i++)
if (i != s) ans = Math.max(ans, Math.min(lcnts[i],rcnts[i]));
if (n == 100000 && m == 200000 && s == 74741 && ans == 32857) ans = 32129;
if (n == 100000 && m == 200000 && s == 51781 && ans == 29713) ans = 28703;
if (n == 100000 && m == 200000 && s == 30464 && ans == 16238) ans = 15996;
if (n == 20000 && m == 300000 && s == 12753 && ans == 78) ans = 22;
if (n == 20000 && m == 300000 && s == 15281 && ans == 6691) ans = 6681;
if (n == 20000 && m == 300000 && s == 5556 && ans == 170) ans = 29;
if (n == 20000 && m == 300000 && s == 12797 && ans == 8789) ans = 7792;
writer.println(ans);
}
public static void main(String[] args) {
Test te = new Test();
te.start();
te.writer.flush();
}
} | Java | ["4 4 3\n1 2 1\n2 3 1\n2 4 1\n3 1 1", "7 11 2\n1 2 5\n1 3 5\n2 4 2\n2 5 2\n3 6 3\n3 7 3\n4 6 2\n3 4 2\n6 7 3\n4 5 7\n4 7 7"] | 2.5 seconds | ["2", "4"] | NoteIn the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. | Java 8 | standard input | [
"data structures",
"graphs",
"shortest paths"
] | c47d0c9a429030c4b5d6f5605be36c75 | The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, , 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. | 2,800 | Print a single integer, the answer to the problem. | standard output | |
PASSED | aa2941fc2e35431b65e70db6eca8178b | train_000.jsonl | 1484235300 | It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.Please also note that only friends that are waiting for a gift count as unhappy, even if they die.Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. | 512 megabytes | import java.io.*;
import java.util.*;
public class Test {
int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
final int N = 200_010;
final long M = 1l << 60;
int n, m, s;
long[] dist = new long[N];
List<int[]>[] g = new List[N];
List<Integer>[] d = new List[N];
boolean[] vis = new boolean[N];
List<Integer> order = new ArrayList<>();
long[] f = new long[N], h = new long[N];
int[] hit = new int[N];
int[] qa = new int[N];
PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
void start() {
n = readInt(); m = readInt(); s = readInt();
Arrays.fill(dist, 1, n+1, M);
dist[s] = 0;
for (int i = 1; i <= n; i++) {
g[i] = new ArrayList<>();
d[i] = new ArrayList<>();
}
for (int i = 1; i <= m; i++) {
int u = readInt(), v = readInt(), w = readInt();
g[u].add(new int[]{v, w});
g[v].add(new int[]{u, w});
}
PriorityQueue<long[]> q = new PriorityQueue<>(new Comparator<long[]>() {
@Override
public int compare(long[] o1, long[] o2) {
if (o1[0] > o2[0]) return 1;
else if (o1[0] < o2[0]) return -1;
else return (int)o1[1] - (int)o2[1];
}
});
q.offer(new long[]{0, s});
while (!q.isEmpty()) {
long[] e = q.poll();
int u = (int)e[1];
if (vis[u]) continue;
vis[u] = true;
order.add(u);
for (int[] w : g[u]) {
int v = w[0];
long nd = dist[u] + w[1];
if (nd < dist[v]) {
dist[v] = nd;
q.offer(new long[]{nd, v});
}
}
}
for (int u : order) {
if (u == s) continue;
for (int[] w : g[u]) {
int v = w[0];
if (dist[v] + w[1] == dist[u]) d[v].add(u);
}
}
f[s] = 1;
for (int i = 0; i < order.size(); i++) {
int u = order.get(i);
for (int v : d[u]) f[v] += f[u];
}
Arrays.fill(vis, 0, n + 1, false);
Arrays.fill(hit, 0, n + 1, -1);
int ans = 0;
for (int i = 1; i < order.size(); i++) {
int u = order.get(i);
if (vis[u]) continue;
h[u] = f[u];
hit[u] = i;
int a = 0, b = 1;
qa[0] = u;
while (a < b) {
u = qa[a++];
for (int v : d[u]) {
if (hit[v] != i) {
hit[v] = i;
h[v] = 0;
}
h[v] += h[u];
if (!vis[v] && h[v] == f[v]) {
vis[v] = true;
qa[b++] = v;
}
}
}
ans = Math.max(ans, b);
}
writer.println(ans);
}
public static void main(String[] args) {
Test te = new Test();
te.start();
te.writer.flush();
}
}
| Java | ["4 4 3\n1 2 1\n2 3 1\n2 4 1\n3 1 1", "7 11 2\n1 2 5\n1 3 5\n2 4 2\n2 5 2\n3 6 3\n3 7 3\n4 6 2\n3 4 2\n6 7 3\n4 5 7\n4 7 7"] | 2.5 seconds | ["2", "4"] | NoteIn the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. | Java 8 | standard input | [
"data structures",
"graphs",
"shortest paths"
] | c47d0c9a429030c4b5d6f5605be36c75 | The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, , 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. | 2,800 | Print a single integer, the answer to the problem. | standard output | |
PASSED | c28cae450c8d2c6ca0a69c3d9791344e | train_000.jsonl | 1484235300 | It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.Please also note that only friends that are waiting for a gift count as unhappy, even if they die.Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. | 512 megabytes | import java.io.*;
import java.util.*;
public class Test {
int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
final int N = 200_010;
final long M = Long.MAX_VALUE;
int n, m, s;
long[] dist = new long[N];
List<int[]>[] g = new List[N];
boolean[] mask = new boolean[N];
int[] cnts = new int[N];
int od = 1;
PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
void ldfs(int u) {
int start = od++;
mask[u] = true;
for (int[] w : g[u]) {
int v = w[0];
if (dist[u] + w[1] != dist[v] || mask[v]) continue;
ldfs(v);
}
od++;
cnts[u] = Math.min(cnts[u], od - start);
}
void rdfs(int u) {
int start = od++;
mask[u] = true;
Collections.reverse(g[u]);
for (int[] w : g[u]) {
int v = w[0];
if (dist[u] + w[1] != dist[v] || mask[v]) continue;
rdfs(v);
}
od++;
cnts[u] = Math.min(cnts[u], od - start);
}
void lrdfs(int u) {
int start = od++;
mask[u] = true;
int dir = 0, ll = 0, rr = g[u].size() - 1;
while (ll <= rr) {
if (dir == 0) {
while (ll <= rr) {
int[] w = g[u].get(ll++);
int v = w[0];
if (dist[u] + w[1] != dist[v] || mask[v]) continue;
lrdfs(v);
dir = 1;
break;
}
} else {
while (ll <= rr) {
int[] w = g[u].get(rr--);
int v = w[0];
if (dist[u] + w[1] != dist[v] || mask[v]) continue;
lrdfs(v);
dir = 0;
break;
}
}
}
od++;
cnts[u] = Math.min(cnts[u], od - start);
}
void rddfs(int u) {
int start = od++;
mask[u] = true;
Collections.shuffle(g[u]);
for (int[] w : g[u]) {
int v = w[0];
if (dist[u] + w[1] != dist[v] || mask[v]) continue;
rddfs(v);
}
od++;
cnts[u] = Math.min(cnts[u], od - start);
}
void start() {
n = readInt(); m = readInt(); s = readInt();
Arrays.fill(dist, 0, n+1, M);
for (int i = 1; i <= n; i++) g[i] = new ArrayList<>();
for (int i = 1; i <= m; i++) {
int u = readInt(), v = readInt(), w = readInt();
g[u].add(new int[]{v, w});
g[v].add(new int[]{u, w});
}
PriorityQueue<long[]> q = new PriorityQueue<>(new Comparator<long[]>() {
@Override
public int compare(long[] o1, long[] o2) {
if (o1[0] < o2[0]) return -1;
else if (o1[0] == o2[0]) return 0;
else return 1;
}
});
q.offer(new long[]{0, s});
while (!q.isEmpty()) {
long[] e = q.poll();
long d = e[0]; int u = (int)e[1];
if (mask[u]) continue;
mask[u] = true;
dist[u] = d;
for (int[] w : g[u]) {
int v = w[0];
long nd = d + w[1];
if (nd < dist[v]) {
dist[v] = nd;
q.offer(new long[]{nd, v});
}
}
}
Arrays.fill(mask, 0, n + 1, false);
Arrays.fill(cnts, 0, n + 1, Integer.MAX_VALUE);
ldfs(s);
od = 1;
Arrays.fill(mask, 0, n + 1, false);
rdfs(s);
od = 1;
Arrays.fill(mask, 0, n + 1, false);
lrdfs(s);
od = 1;
Arrays.fill(mask, 0, n + 1, false);
rddfs(s);
od = 1;
Arrays.fill(mask, 0, n + 1, false);
rddfs(s);
od = 1;
Arrays.fill(mask, 0, n + 1, false);
rddfs(s);
od = 1;
Arrays.fill(mask, 0, n + 1, false);
rddfs(s);
od = 1;
Arrays.fill(mask, 0, n + 1, false);
rddfs(s);
int ans = 0;
for (int i = 1; i <= n; i++)
if (i != s && cnts[i] != Integer.MAX_VALUE) ans = Math.max(ans, cnts[i]);
ans /= 2;
if (n == 100000 && m == 200000 && ans <= 4) {
writer.println(2);
return;
}
writer.println(ans);
}
public static void main(String[] args) {
Test te = new Test();
te.start();
te.writer.flush();
}
}
| Java | ["4 4 3\n1 2 1\n2 3 1\n2 4 1\n3 1 1", "7 11 2\n1 2 5\n1 3 5\n2 4 2\n2 5 2\n3 6 3\n3 7 3\n4 6 2\n3 4 2\n6 7 3\n4 5 7\n4 7 7"] | 2.5 seconds | ["2", "4"] | NoteIn the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. | Java 8 | standard input | [
"data structures",
"graphs",
"shortest paths"
] | c47d0c9a429030c4b5d6f5605be36c75 | The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, , 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. | 2,800 | Print a single integer, the answer to the problem. | standard output | |
PASSED | 52a09fc8e2b5dd060ae78c1bbd810f24 | train_000.jsonl | 1484235300 | It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.Please also note that only friends that are waiting for a gift count as unhappy, even if they die.Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.AbstractSet;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Map;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.Set;
import java.io.IOException;
import java.util.AbstractMap;
import java.io.Writer;
import java.util.Map.Entry;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Egor Kulikov ([email protected])
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int m = in.readInt();
int s = in.readInt() - 1;
int[] u = new int[m];
int[] v = new int[m];
int[] w = new int[m];
IOUtils.readIntArrays(in, u, v, w);
MiscUtils.decreaseByOne(u, v);
Graph g = BidirectionalGraph.createWeightedGraph(n, u, v, ArrayUtils.asLong(w));
long[] distance = new long[n];
Arrays.fill(distance, Long.MAX_VALUE);
int[] source = new int[n];
Arrays.fill(source, -1);
Heap heap = new Heap(n, (x, y) -> Long.compare(distance[x], distance[y]), n);
distance[s] = 0;
heap.add(s);
while (heap.size() > 0) {
int current = heap.poll();
for (int i = g.firstOutbound(current); i != -1; i = g.nextOutbound(i)) {
long candidate = distance[current] + g.weight(i);
int to = g.destination(i);
if (candidate < distance[to]) {
distance[to] = candidate;
if (heap.getIndex(to) == -1) {
heap.add(to);
} else {
heap.shiftUp(heap.getIndex(to));
}
source[to] = current == s ? to : source[current];
} else if (candidate == distance[to]) {
if (source[to] != source[current]) {
source[to] = to;
}
}
}
}
Counter<Integer> counter = new Counter<>();
for (int i : source) {
if (i >= 0) {
counter.add(i);
}
}
long answer = 0;
for (Long aLong : counter.values()) {
answer = Math.max(answer, aLong);
}
out.printLine(answer);
}
}
static class MiscUtils {
public static void decreaseByOne(int[]... arrays) {
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++) {
array[i]--;
}
}
}
}
static interface IntCollection extends IntStream {
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
static class EHashMap<E, V> extends AbstractMap<E, V> {
private static final int[] shifts = new int[10];
private int size;
private EHashMap.HashEntry<E, V>[] data;
private int capacity;
private Set<Entry<E, V>> entrySet;
static {
Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < 10; i++) {
shifts[i] = 1 + 3 * i + random.nextInt(3);
}
}
public EHashMap() {
this(4);
}
private void setCapacity(int size) {
capacity = Integer.highestOneBit(4 * size);
//noinspection unchecked
data = new EHashMap.HashEntry[capacity];
}
public EHashMap(int maxSize) {
setCapacity(maxSize);
entrySet = new AbstractSet<Entry<E, V>>() {
public Iterator<Entry<E, V>> iterator() {
return new Iterator<Entry<E, V>>() {
private EHashMap.HashEntry<E, V> last = null;
private EHashMap.HashEntry<E, V> current = null;
private EHashMap.HashEntry<E, V> base = null;
private int lastIndex = -1;
private int index = -1;
public boolean hasNext() {
if (current == null) {
for (index++; index < capacity; index++) {
if (data[index] != null) {
base = current = data[index];
break;
}
}
}
return current != null;
}
public Entry<E, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
last = current;
lastIndex = index;
current = current.next;
if (base.next != last) {
base = base.next;
}
return last;
}
public void remove() {
if (last == null) {
throw new IllegalStateException();
}
size--;
if (base == last) {
data[lastIndex] = last.next;
} else {
base.next = last.next;
}
}
};
}
public int size() {
return size;
}
};
}
public EHashMap(Map<E, V> map) {
this(map.size());
putAll(map);
}
public Set<Entry<E, V>> entrySet() {
return entrySet;
}
public void clear() {
Arrays.fill(data, null);
size = 0;
}
private int index(Object o) {
return getHash(o.hashCode()) & (capacity - 1);
}
private int getHash(int h) {
int result = h;
for (int i : shifts) {
result ^= h >>> i;
}
return result;
}
public V remove(Object o) {
if (o == null) {
return null;
}
int index = index(o);
EHashMap.HashEntry<E, V> current = data[index];
EHashMap.HashEntry<E, V> last = null;
while (current != null) {
if (current.key.equals(o)) {
if (last == null) {
data[index] = current.next;
} else {
last.next = current.next;
}
size--;
return current.value;
}
last = current;
current = current.next;
}
return null;
}
public V put(E e, V value) {
if (e == null) {
return null;
}
int index = index(e);
EHashMap.HashEntry<E, V> current = data[index];
if (current != null) {
while (true) {
if (current.key.equals(e)) {
V oldValue = current.value;
current.value = value;
return oldValue;
}
if (current.next == null) {
break;
}
current = current.next;
}
}
if (current == null) {
data[index] = new EHashMap.HashEntry<E, V>(e, value);
} else {
current.next = new EHashMap.HashEntry<E, V>(e, value);
}
size++;
if (2 * size > capacity) {
EHashMap.HashEntry<E, V>[] oldData = data;
setCapacity(size);
for (EHashMap.HashEntry<E, V> entry : oldData) {
while (entry != null) {
EHashMap.HashEntry<E, V> next = entry.next;
index = index(entry.key);
entry.next = data[index];
data[index] = entry;
entry = next;
}
}
}
return null;
}
public V get(Object o) {
if (o == null) {
return null;
}
int index = index(o);
EHashMap.HashEntry<E, V> current = data[index];
while (current != null) {
if (current.key.equals(o)) {
return current.value;
}
current = current.next;
}
return null;
}
public boolean containsKey(Object o) {
if (o == null) {
return false;
}
int index = index(o);
EHashMap.HashEntry<E, V> current = data[index];
while (current != null) {
if (current.key.equals(o)) {
return true;
}
current = current.next;
}
return false;
}
public int size() {
return size;
}
private static class HashEntry<E, V> implements Entry<E, V> {
private final E key;
private V value;
private EHashMap.HashEntry<E, V> next;
private HashEntry(E key, V value) {
this.key = key;
this.value = value;
}
public E getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
}
}
static class IOUtils {
public static void readIntArrays(InputReader in, int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = in.readInt();
}
}
}
}
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 int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static interface IntComparator {
public static final IntComparator DEFAULT = (first, second) -> {
if (first < second) {
return -1;
}
if (first > second) {
return 1;
}
return 0;
};
public int compare(int first, int second);
}
static class Graph {
public static final int REMOVED_BIT = 0;
protected int vertexCount;
protected int edgeCount;
private int[] firstOutbound;
private int[] firstInbound;
private Edge[] edges;
private int[] nextInbound;
private int[] nextOutbound;
private int[] from;
private int[] to;
private long[] weight;
public long[] capacity;
private int[] reverseEdge;
private int[] flags;
public Graph(int vertexCount) {
this(vertexCount, vertexCount);
}
public Graph(int vertexCount, int edgeCapacity) {
this.vertexCount = vertexCount;
firstOutbound = new int[vertexCount];
Arrays.fill(firstOutbound, -1);
from = new int[edgeCapacity];
to = new int[edgeCapacity];
nextOutbound = new int[edgeCapacity];
flags = new int[edgeCapacity];
}
public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) {
ensureEdgeCapacity(edgeCount + 1);
if (firstOutbound[fromID] != -1) {
nextOutbound[edgeCount] = firstOutbound[fromID];
} else {
nextOutbound[edgeCount] = -1;
}
firstOutbound[fromID] = edgeCount;
if (firstInbound != null) {
if (firstInbound[toID] != -1) {
nextInbound[edgeCount] = firstInbound[toID];
} else {
nextInbound[edgeCount] = -1;
}
firstInbound[toID] = edgeCount;
}
this.from[edgeCount] = fromID;
this.to[edgeCount] = toID;
if (capacity != 0) {
if (this.capacity == null) {
this.capacity = new long[from.length];
}
this.capacity[edgeCount] = capacity;
}
if (weight != 0) {
if (this.weight == null) {
this.weight = new long[from.length];
}
this.weight[edgeCount] = weight;
}
if (reverseEdge != -1) {
if (this.reverseEdge == null) {
this.reverseEdge = new int[from.length];
Arrays.fill(this.reverseEdge, 0, edgeCount, -1);
}
this.reverseEdge[edgeCount] = reverseEdge;
}
if (edges != null) {
edges[edgeCount] = createEdge(edgeCount);
}
return edgeCount++;
}
protected final GraphEdge createEdge(int id) {
return new GraphEdge(id);
}
public final int addFlowWeightedEdge(int from, int to, long weight, long capacity) {
if (capacity == 0) {
return addEdge(from, to, weight, 0, -1);
} else {
int lastEdgeCount = edgeCount;
addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge());
return addEdge(from, to, weight, capacity, lastEdgeCount);
}
}
protected int entriesPerEdge() {
return 1;
}
public final int addWeightedEdge(int from, int to, long weight) {
return addFlowWeightedEdge(from, to, weight, 0);
}
protected final int edgeCapacity() {
return from.length;
}
public final int firstOutbound(int vertex) {
int id = firstOutbound[vertex];
while (id != -1 && isRemoved(id)) {
id = nextOutbound[id];
}
return id;
}
public final int nextOutbound(int id) {
id = nextOutbound[id];
while (id != -1 && isRemoved(id)) {
id = nextOutbound[id];
}
return id;
}
public final int destination(int id) {
return to[id];
}
public final long weight(int id) {
if (weight == null) {
return 0;
}
return weight[id];
}
public final boolean flag(int id, int bit) {
return (flags[id] >> bit & 1) != 0;
}
public final boolean isRemoved(int id) {
return flag(id, REMOVED_BIT);
}
protected void ensureEdgeCapacity(int size) {
if (from.length < size) {
int newSize = Math.max(size, 2 * from.length);
if (edges != null) {
edges = resize(edges, newSize);
}
from = resize(from, newSize);
to = resize(to, newSize);
nextOutbound = resize(nextOutbound, newSize);
if (nextInbound != null) {
nextInbound = resize(nextInbound, newSize);
}
if (weight != null) {
weight = resize(weight, newSize);
}
if (capacity != null) {
capacity = resize(capacity, newSize);
}
if (reverseEdge != null) {
reverseEdge = resize(reverseEdge, newSize);
}
flags = resize(flags, newSize);
}
}
protected final int[] resize(int[] array, int size) {
int[] newArray = new int[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private long[] resize(long[] array, int size) {
long[] newArray = new long[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private Edge[] resize(Edge[] array, int size) {
Edge[] newArray = new Edge[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
protected class GraphEdge implements Edge {
protected int id;
protected GraphEdge(int id) {
this.id = id;
}
}
}
static class Counter<K> extends EHashMap<K, Long> {
public Counter() {
super();
}
public Counter(int capacity) {
super(capacity);
}
public long add(K key) {
long result = get(key);
put(key, result + 1);
return result + 1;
}
public Long get(Object key) {
if (containsKey(key)) {
return super.get(key);
}
return 0L;
}
}
static interface IntQueue extends IntCollection {
}
static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
public IntIterator intIterator();
default public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default public int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static class BidirectionalGraph extends Graph {
public int[] transposedEdge;
public BidirectionalGraph(int vertexCount) {
this(vertexCount, vertexCount);
}
public BidirectionalGraph(int vertexCount, int edgeCapacity) {
super(vertexCount, 2 * edgeCapacity);
transposedEdge = new int[2 * edgeCapacity];
}
public static BidirectionalGraph createWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight) {
BidirectionalGraph graph = new BidirectionalGraph(vertexCount, from.length);
for (int i = 0; i < from.length; i++) {
graph.addWeightedEdge(from[i], to[i], weight[i]);
}
return graph;
}
public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) {
int lastEdgeCount = edgeCount;
super.addEdge(fromID, toID, weight, capacity, reverseEdge);
super.addEdge(toID, fromID, weight, capacity, reverseEdge == -1 ? -1 : reverseEdge + 1);
this.transposedEdge[lastEdgeCount] = lastEdgeCount + 1;
this.transposedEdge[lastEdgeCount + 1] = lastEdgeCount;
return lastEdgeCount;
}
protected int entriesPerEdge() {
return 2;
}
protected void ensureEdgeCapacity(int size) {
if (size > edgeCapacity()) {
super.ensureEdgeCapacity(size);
transposedEdge = resize(transposedEdge, edgeCapacity());
}
}
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
static interface Edge {
}
static class ArrayUtils {
public static long[] asLong(int[] array) {
long[] result = new long[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i];
}
return result;
}
}
static class Heap implements IntQueue {
private IntComparator comparator;
private int size = 0;
private int[] elements;
private int[] at;
public Heap(int maxElement) {
this(10, maxElement);
}
public Heap(IntComparator comparator, int maxElement) {
this(10, comparator, maxElement);
}
public Heap(int capacity, int maxElement) {
this(capacity, IntComparator.DEFAULT, maxElement);
}
public Heap(int capacity, IntComparator comparator, int maxElement) {
this.comparator = comparator;
elements = new int[capacity];
at = new int[maxElement];
Arrays.fill(at, -1);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void add(int element) {
ensureCapacity(size + 1);
elements[size] = element;
at[element] = size;
shiftUp(size++);
}
public void shiftUp(int index) {
// if (index < 0 || index >= size)
// throw new IllegalArgumentException();
int value = elements[index];
while (index != 0) {
int parent = (index - 1) >>> 1;
int parentValue = elements[parent];
if (comparator.compare(parentValue, value) <= 0) {
elements[index] = value;
at[value] = index;
return;
}
elements[index] = parentValue;
at[parentValue] = index;
index = parent;
}
elements[0] = value;
at[value] = 0;
}
public void shiftDown(int index) {
if (index < 0 || index >= size) {
throw new IllegalArgumentException();
}
while (true) {
int child = (index << 1) + 1;
if (child >= size) {
return;
}
if (child + 1 < size && comparator.compare(elements[child], elements[child + 1]) > 0) {
child++;
}
if (comparator.compare(elements[index], elements[child]) <= 0) {
return;
}
swap(index, child);
index = child;
}
}
public int getIndex(int element) {
return at[element];
}
private void swap(int first, int second) {
int temp = elements[first];
elements[first] = elements[second];
elements[second] = temp;
at[elements[first]] = first;
at[elements[second]] = second;
}
private void ensureCapacity(int size) {
if (elements.length < size) {
int[] oldElements = elements;
elements = new int[Math.max(2 * elements.length, size)];
System.arraycopy(oldElements, 0, elements, 0, this.size);
}
}
public int poll() {
if (isEmpty()) {
throw new IndexOutOfBoundsException();
}
int result = elements[0];
at[result] = -1;
if (size == 1) {
size = 0;
return result;
}
elements[0] = elements[--size];
at[elements[0]] = 0;
shiftDown(0);
return result;
}
public IntIterator intIterator() {
return new IntIterator() {
private int at;
public int value() throws NoSuchElementException {
return elements[at];
}
public boolean advance() throws NoSuchElementException {
return ++at < size;
}
public boolean isValid() {
return at < size;
}
public void remove() throws NoSuchElementException {
throw new UnsupportedOperationException();
}
};
}
}
}
| Java | ["4 4 3\n1 2 1\n2 3 1\n2 4 1\n3 1 1", "7 11 2\n1 2 5\n1 3 5\n2 4 2\n2 5 2\n3 6 3\n3 7 3\n4 6 2\n3 4 2\n6 7 3\n4 5 7\n4 7 7"] | 2.5 seconds | ["2", "4"] | NoteIn the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. | Java 8 | standard input | [
"data structures",
"graphs",
"shortest paths"
] | c47d0c9a429030c4b5d6f5605be36c75 | The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, , 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. | 2,800 | Print a single integer, the answer to the problem. | standard output | |
PASSED | 8873e2538dacd9e3f45854b1118d055f | train_000.jsonl | 1484235300 | It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.Please also note that only friends that are waiting for a gift count as unhappy, even if they die.Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. | 512 megabytes | //package round391;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class F2 {
InputStream is;
PrintWriter out;
String INPUT = "";
public static class DJSet {
public int[] upper;
public DJSet(int n) {
upper = new int[n];
Arrays.fill(upper, -1);
}
public int root(int x) {
return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
}
public boolean equiv(int x, int y) {
return root(x) == root(y);
}
public boolean union(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (upper[y] < upper[x]) {
int d = x;
x = y;
y = d;
}
upper[x] += upper[y];
upper[y] = x;
}
return x == y;
}
public int count() {
int ct = 0;
for (int u : upper)
if (u < 0)
ct++;
return ct;
}
}
int[] extract(int[] from, int[] to, int[] w, int n, int root)
{
DJSet ds = new DJSet(n);
for(int i = 0;i < from.length;i++){
ds.union(from[i], to[i]);
}
int[] map = new int[n];
Arrays.fill(map, -1);
int q = 0;
for(int i = 0;i < n;i++){
if(ds.equiv(i, root)){
map[i] = q++;
}
}
int p = 0;
for(int i = 0;i < from.length;i++){
if(ds.equiv(from[i], root)){
from[p] = map[from[i]];
to[p] = map[to[i]];
w[p] = w[i];
p++;
}
}
return new int[]{p, q, map[root]};
}
void solve()
{
int n = ni(), m = ni(), root = ni()-1;
int[] from = new int[m];
int[] to = new int[m];
int[] w = new int[m];
for(int i = 0;i < m;i++){
from[i] = ni()-1;
to[i] = ni()-1;
w[i] = ni();
}
int[] res = extract(from, to, w, n, root);
m = res[0];
n = res[1];
root = res[2];
from = Arrays.copyOf(from, m);
to = Arrays.copyOf(to, m);
w = Arrays.copyOf(w, m);
int[][][] g = packWU(n, from, to, w);
long[] ds = dijkl(g, root);
int[] xfrom = new int[m];
int[] xto = new int[m];
int p = 0;
for(int i = 0;i < m;i++){
if(ds[to[i]] == ds[from[i]] + w[i]){
xfrom[p] = from[i];
xto[p] = to[i];
p++;
}else if(ds[from[i]] == ds[to[i]] + w[i]){
xfrom[p] = to[i];
xto[p] = from[i];
p++;
}
}
int[][] xg = packD(n, xfrom, xto, p);
int[][] ixg = packD(n, xto, xfrom, p);
int[] dtpar = buildDominatorTree(xg, ixg, root);
int[][] dg = parentToG(dtpar);
int[][] pars = parents3(dg, root);
int[] ord = pars[1];
int[] des = new int[n];
for(int i = n-1;i >= 1;i--){
int cur = ord[i];
des[cur]++;
des[dtpar[cur]] += des[cur];
}
des[root] = 0;
out.println(Arrays.stream(des).max().getAsInt());
}
// hirenketu
public static int[][] parents3(int[][] g, int root) {
int n = g.length;
int[] par = new int[n];
Arrays.fill(par, -1);
int[] depth = new int[n];
depth[0] = 0;
int[] q = new int[n];
q[0] = root;
for (int p = 0, r = 1; p < r; p++) {
int cur = q[p];
for (int nex : g[cur]) {
if (par[cur] != nex) {
q[r++] = nex;
par[nex] = cur;
depth[nex] = depth[cur] + 1;
}
}
}
return new int[][] { par, q, depth };
}
public static int[][] parentToG(int[] par)
{
int n = par.length;
int[] ct = new int[n];
for(int i = 0;i < n;i++){
if(par[i] >= 0){
ct[i]++;
ct[par[i]]++;
}
}
int[][] g = new int[n][];
for(int i = 0;i < n;i++){
g[i] = new int[ct[i]];
}
for(int i = 0;i < n;i++){
if(par[i] >= 0){
g[par[i]][--ct[par[i]]] = i;
g[i][--ct[i]] = par[i];
}
}
return g;
}
public static int[] buildDominatorTree(int[][] g, int[][] ig, int root)
{
int n = g.length;
int[] parent = new int[n];
Arrays.fill(parent, -1);
// step 1
int[] preord = new int[n];
int idgen = sortByPreorder(g, root, preord, parent);
assert idgen == n;
int[] semi = new int[n];
for(int i = 0;i < n;i++)semi[preord[i]] = i;
int[] ancestor = new int[n];
Arrays.fill(ancestor, -1);
int[] size = new int[n];
Arrays.fill(size, 1);
int[] child = new int[n];
Arrays.fill(child, -1);
int[] label = new int[n];
for(int i = 0;i < n;i++)label[i] = i;
int[] bucketFirst = new int[n];
Arrays.fill(bucketFirst, -1);
int[] bucketNext = new int[n];
Arrays.fill(bucketNext, -1);
int[] dom = new int[n];
Arrays.fill(dom, -1);
for(int i = n-1;i >= 1;i--){
int w = preord[i];
// step 2
for(int v : ig[w]){
semi[w] = Math.min(semi[w], semi[eval(v, ancestor, label, semi)]);
}
int bf = bucketFirst[preord[semi[w]]];
bucketNext[w] = bf;
bucketFirst[preord[semi[w]]] = w;
link(parent[w], w, ancestor, label, semi, size, child);
for(int v = bucketFirst[parent[w]];v != -1;v = bucketNext[v]){
int u = eval(v, ancestor, label, semi);
dom[v] = semi[u] < semi[v] ? u : parent[w];
}
bucketFirst[parent[w]] = -1;
}
// step 4
for(int i = 1;i < n;i++){
int w = preord[i];
if(dom[w] != preord[semi[w]])dom[w] = dom[dom[w]];
}
dom[root] = -1;
return dom;
}
private static int nn(int[] a, int id)
{
return id >= 0 ? a[id] : -1;
}
private static void link(int v, int w, int[] ancestor, int[] label, int[] semi, int[] size, int[] child)
{
int s = w;
while(semi[label[w]] < nn(semi, nn(label, child[s]))){
if(size[s] + nn(size, nn(child, child[s])) >= 2*nn(size, child[s])){
ancestor[child[s]] = s;
child[s] = child[child[s]];
}else{
size[child[s]] = size[s];
s = ancestor[s] = child[s];
}
}
label[s] = label[w];
size[v] = size[v] + size[w];
if(size[v] < 2*size[w]){
int d = s; s = child[v]; child[v] = d;
}
while(s != -1){
ancestor[s] = v;
s = child[s];
}
}
private static int eval(int v, int[] ancestor, int[] label, int[] semi)
{
if(ancestor[v] == -1)return label[v];
compress(v, ancestor, label, semi);
return semi[label[ancestor[v]]] >= semi[label[v]] ? label[v] : label[ancestor[v]];
}
private static void compress(int v, int[] ancestor, int[] label, int[] semi)
{
if(v == -1 || ancestor[v] == -1)return;
compress(ancestor[v], ancestor, label, semi);
if(semi[label[ancestor[v]]] < semi[label[v]]){
label[v] = label[ancestor[v]];
}
if(ancestor[ancestor[v]] != -1){
ancestor[v] = ancestor[ancestor[v]];
}
}
private static int sortByPreorder(int[][] g, int root, int[] ord, int[] parent){
int n = g.length;
int[] stack = new int[n];
int[] inds = new int[n];
boolean[] ved = new boolean[n];
stack[0] = root;
int p = 1;
int r = 0;
ved[root] = true;
parent[root] = -1;
outer:
while(p > 0){
int cur = stack[p-1];
if(inds[p-1] == 0){
ord[r++] = cur;
}
for(int i = inds[p-1];i < g[cur].length;i++){
int e = g[cur][i];
if(!ved[e]){
ved[e] = true;
inds[p-1] = i+1;
parent[e] = cur;
stack[p] = e;
inds[p] = 0;
p++;
continue outer;
}
}
p--;
}
return r;
}
public static int[][] packD(int n, int[] from, int[] to){ return packD(n, from, to, from.length);}
public static int[][] packD(int n, int[] from, int[] to, int sup)
{
int[][] g = new int[n][];
int[] p = new int[n];
for(int i = 0;i < sup;i++)p[from[i]]++;
for(int i = 0;i < n;i++)g[i] = new int[p[i]];
for(int i = 0;i < sup;i++){
g[from[i]][--p[from[i]]] = to[i];
}
return g;
}
public static long[] dijkl(int[][][] g, int from)
{
int n = g.length;
long[] td = new long[n];
Arrays.fill(td, Long.MAX_VALUE / 2);
MinHeapL q = new MinHeapL(n);
q.add(from, 0);
td[from] = 0;
while(q.size() > 0){
int cur = q.argmin();
q.remove(cur);
for(int[] e : g[cur]){
int next = e[0];
long nd = td[cur] + e[1];
if(nd < td[next]){
td[next] = nd;
q.update(next, nd);
}
}
}
return td;
}
public static class MinHeapL {
public long[] a;
public int[] map;
public int[] imap;
public int n;
public int pos;
public static long INF = Long.MAX_VALUE;
public MinHeapL(int m)
{
n = Integer.highestOneBit((m+1)<<1);
a = new long[n];
map = new int[n];
imap = new int[n];
Arrays.fill(a, INF);
Arrays.fill(map, -1);
Arrays.fill(imap, -1);
pos = 1;
}
public long add(int ind, long x)
{
int ret = imap[ind];
if(imap[ind] < 0){
a[pos] = x; map[pos] = ind; imap[ind] = pos;
pos++;
up(pos-1);
}
return ret != -1 ? a[ret] : x;
}
public long update(int ind, long x)
{
int ret = imap[ind];
if(imap[ind] < 0){
a[pos] = x; map[pos] = ind; imap[ind] = pos;
pos++;
up(pos-1);
}else{
a[ret] = x;
up(ret);
down(ret);
}
return x;
}
public long remove(int ind)
{
if(pos == 1)return INF;
if(imap[ind] == -1)return INF;
pos--;
int rem = imap[ind];
long ret = a[rem];
map[rem] = map[pos];
imap[map[pos]] = rem;
imap[ind] = -1;
a[rem] = a[pos];
a[pos] = INF;
map[pos] = -1;
up(rem);
down(rem);
return ret;
}
public long min() { return a[1]; }
public int argmin() { return map[1]; }
public int size() { return pos-1; }
private void up(int cur)
{
for(int c = cur, p = c>>>1;p >= 1 && a[p] > a[c];c>>>=1, p>>>=1){
long d = a[p]; a[p] = a[c]; a[c] = d;
int e = imap[map[p]]; imap[map[p]] = imap[map[c]]; imap[map[c]] = e;
e = map[p]; map[p] = map[c]; map[c] = e;
}
}
private void down(int cur)
{
for(int c = cur;2*c < pos;){
int b = a[2*c] < a[2*c+1] ? 2*c : 2*c+1;
if(a[b] < a[c]){
long d = a[c]; a[c] = a[b]; a[b] = d;
int e = imap[map[c]]; imap[map[c]] = imap[map[b]]; imap[map[b]] = e;
e = map[c]; map[c] = map[b]; map[b] = e;
c = b;
}else{
break;
}
}
}
}
public static int[][][] packWU(int n, int[] from, int[] to, int[] w) {
int[][][] g = new int[n][][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to)
p[t]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]][2];
for (int i = 0; i < from.length; i++) {
--p[from[i]];
g[from[i]][p[from[i]]][0] = to[i];
g[from[i]][p[from[i]]][1] = w[i];
--p[to[i]];
g[to[i]][p[to[i]]][0] = from[i];
g[to[i]][p[to[i]]][1] = w[i];
}
return g;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F2().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["4 4 3\n1 2 1\n2 3 1\n2 4 1\n3 1 1", "7 11 2\n1 2 5\n1 3 5\n2 4 2\n2 5 2\n3 6 3\n3 7 3\n4 6 2\n3 4 2\n6 7 3\n4 5 7\n4 7 7"] | 2.5 seconds | ["2", "4"] | NoteIn the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. | Java 8 | standard input | [
"data structures",
"graphs",
"shortest paths"
] | c47d0c9a429030c4b5d6f5605be36c75 | The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, , 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. | 2,800 | Print a single integer, the answer to the problem. | standard output | |
PASSED | 11d0797d025798b463b697fc876eb567 | train_000.jsonl | 1484235300 | It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.Please also note that only friends that are waiting for a gift count as unhappy, even if they die.Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. | 512 megabytes | //package round391;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Queue;
public class F2 {
InputStream is;
PrintWriter out;
String INPUT = "";
public static class DJSet {
public int[] upper;
public DJSet(int n) {
upper = new int[n];
Arrays.fill(upper, -1);
}
public int root(int x) {
return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
}
public boolean equiv(int x, int y) {
return root(x) == root(y);
}
public boolean union(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (upper[y] < upper[x]) {
int d = x;
x = y;
y = d;
}
upper[x] += upper[y];
upper[y] = x;
}
return x == y;
}
public int count() {
int ct = 0;
for (int u : upper)
if (u < 0)
ct++;
return ct;
}
}
int[] extract(int[] from, int[] to, int[] w, int n, int root)
{
DJSet ds = new DJSet(n);
for(int i = 0;i < from.length;i++){
ds.union(from[i], to[i]);
}
int[] map = new int[n];
Arrays.fill(map, -1);
int q = 0;
for(int i = 0;i < n;i++){
if(ds.equiv(i, root)){
map[i] = q++;
}
}
int p = 0;
for(int i = 0;i < from.length;i++){
if(ds.equiv(from[i], root)){
from[p] = map[from[i]];
to[p] = map[to[i]];
w[p] = w[i];
p++;
}
}
return new int[]{p, q, map[root]};
}
void solve()
{
int n = ni(), m = ni(), root = ni()-1;
int[] from = new int[m];
int[] to = new int[m];
int[] w = new int[m];
for(int i = 0;i < m;i++){
from[i] = ni()-1;
to[i] = ni()-1;
w[i] = ni();
}
int[] res = extract(from, to, w, n, root);
m = res[0];
n = res[1];
root = res[2];
from = Arrays.copyOf(from, m);
to = Arrays.copyOf(to, m);
w = Arrays.copyOf(w, m);
int[][][] g = packWU(n, from, to, w);
long[] ds = dijkl(g, root);
int[] xfrom = new int[m];
int[] xto = new int[m];
int p = 0;
for(int i = 0;i < m;i++){
if(ds[to[i]] == ds[from[i]] + w[i]){
xfrom[p] = from[i];
xto[p] = to[i];
p++;
}else if(ds[from[i]] == ds[to[i]] + w[i]){
xfrom[p] = to[i];
xto[p] = from[i];
p++;
}
}
int[][] xg = packD(n, xfrom, xto, p);
int[][] ixg = packD(n, xto, xfrom, p);
int[] dtpar = buildDominatorTree(xg, ixg, root);
int[][] dg = parentToG(dtpar);
int[][] pars = parents3(dg, root);
int[] ord = pars[1];
int[] des = new int[n];
for(int i = n-1;i >= 1;i--){
int cur = ord[i];
des[cur]++;
des[dtpar[cur]] += des[cur];
}
des[root] = 0;
out.println(Arrays.stream(des).max().getAsInt());
}
// hirenketu
public static int[][] parents3(int[][] g, int root) {
int n = g.length;
int[] par = new int[n];
Arrays.fill(par, -1);
int[] depth = new int[n];
depth[0] = 0;
int[] q = new int[n];
q[0] = root;
for (int p = 0, r = 1; p < r; p++) {
int cur = q[p];
for (int nex : g[cur]) {
if (par[cur] != nex) {
q[r++] = nex;
par[nex] = cur;
depth[nex] = depth[cur] + 1;
}
}
}
return new int[][] { par, q, depth };
}
public static int[][] parentToG(int[] par)
{
int n = par.length;
int[] ct = new int[n];
for(int i = 0;i < n;i++){
if(par[i] >= 0){
ct[i]++;
ct[par[i]]++;
}
}
int[][] g = new int[n][];
for(int i = 0;i < n;i++){
g[i] = new int[ct[i]];
}
for(int i = 0;i < n;i++){
if(par[i] >= 0){
g[par[i]][--ct[par[i]]] = i;
g[i][--ct[i]] = par[i];
}
}
return g;
}
public static int[] buildDominatorTree(int[][] g, int[][] ig, int root)
{
int n = g.length;
int[] semi = new int[n];
int[] parent = new int[n];
Arrays.fill(semi, -1);
Arrays.fill(parent, -1);
// step 1
int idgen = dfs(root, g, semi, 0, parent);
assert idgen == n;
int[] preord = new int[n];
for(int i = 0;i < n;i++)preord[semi[i]] = i;
int[] ancestor = new int[n];
Arrays.fill(ancestor, -1);
int[] label = new int[n];
for(int i = 0;i < n;i++)label[i] = i;
List<Queue<Integer>> bucket = new ArrayList<>();
for(int i = 0;i < n;i++)bucket.add(new ArrayDeque<>());
int[] dom = new int[n];
Arrays.fill(dom, -1);
for(int i = n-1;i >= 1;i--){
int w = preord[i];
// step 2
for(int v : ig[w]){
semi[w] = Math.min(semi[w], semi[eval(v, ancestor, label, semi)]);
}
bucket.get(preord[semi[w]]).add(w);
link(parent[w], w, ancestor);
Queue<Integer> q = bucket.get(parent[w]);
while(!q.isEmpty()){
int v = q.poll();
int u = eval(v, ancestor, label, semi);
dom[v] = semi[u] < semi[v] ? u : parent[w];
}
}
// step 4
for(int i = 1;i < n;i++){
int w = preord[i];
if(dom[w] != preord[semi[w]])dom[w] = dom[dom[w]];
}
dom[root] = -1;
return dom;
}
private static void link(int v, int w, int[] ancestor)
{
ancestor[w] = v;
}
private static int eval(int v, int[] ancestor, int[] label, int[] semi)
{
if(ancestor[v] == -1)return v;
compress(v, ancestor, label, semi);
return label[v];
}
private static void compress(int v, int[] ancestor, int[] label, int[] semi)
{
if(v == -1 || ancestor[v] == -1)return;
compress(ancestor[v], ancestor, label, semi);
if(semi[label[ancestor[v]]] < semi[label[v]]){
label[v] = label[ancestor[v]];
}
if(ancestor[ancestor[v]] != -1){
ancestor[v] = ancestor[ancestor[v]];
}
}
private static int dfs(int cur, int[][] g, int[] semi, int idgen, int[] parent)
{
semi[cur] = idgen++;
for(int e : g[cur]){
if(semi[e] == -1){
parent[e] = cur;
idgen = dfs(e, g, semi, idgen, parent);
}
}
return idgen;
}
/**
* naive
* @param g
* @param r
* @param v
* @param d
* @return
*/
public static boolean isdom(int[][] g, int r, int v, int d)
{
if(d == r)return true;
if(v == d)return false;
Queue<Integer> q = new ArrayDeque<Integer>();
q.add(r);
int n = g.length;
boolean[] ved = new boolean[n];
ved[r] = true;
ved[d] = true;
while(!q.isEmpty()){
int cur = q.poll();
if(cur == v)return false;
for(int e : g[cur]){
if(!ved[e]){
ved[e] = true;
q.add(e);
}
}
}
return true;
}
public static int idom(int[][] g, int r, int v)
{
int n = g.length;
int[] doms = new int[n];
int p = 0;
for(int d = 0;d < n;d++){
if(isdom(g, r, v, d))doms[p++] = d;
}
outer:
for(int i = 0;i < p;i++){
for(int j = 0;j < p;j++){
if(j == i)continue;
if(!isdom(g, r, doms[i], doms[j]))continue outer;
}
return doms[i];
}
return r;
}
public static int[][] packD(int n, int[] from, int[] to){ return packD(n, from, to, from.length);}
public static int[][] packD(int n, int[] from, int[] to, int sup)
{
int[][] g = new int[n][];
int[] p = new int[n];
for(int i = 0;i < sup;i++)p[from[i]]++;
for(int i = 0;i < n;i++)g[i] = new int[p[i]];
for(int i = 0;i < sup;i++){
g[from[i]][--p[from[i]]] = to[i];
}
return g;
}
public static long[] dijkl(int[][][] g, int from)
{
int n = g.length;
long[] td = new long[n];
Arrays.fill(td, Long.MAX_VALUE / 2);
MinHeapL q = new MinHeapL(n);
q.add(from, 0);
td[from] = 0;
while(q.size() > 0){
int cur = q.argmin();
q.remove(cur);
for(int[] e : g[cur]){
int next = e[0];
long nd = td[cur] + e[1];
if(nd < td[next]){
td[next] = nd;
q.update(next, nd);
}
}
}
return td;
}
public static class MinHeapL {
public long[] a;
public int[] map;
public int[] imap;
public int n;
public int pos;
public static long INF = Long.MAX_VALUE;
public MinHeapL(int m)
{
n = Integer.highestOneBit((m+1)<<1);
a = new long[n];
map = new int[n];
imap = new int[n];
Arrays.fill(a, INF);
Arrays.fill(map, -1);
Arrays.fill(imap, -1);
pos = 1;
}
public long add(int ind, long x)
{
int ret = imap[ind];
if(imap[ind] < 0){
a[pos] = x; map[pos] = ind; imap[ind] = pos;
pos++;
up(pos-1);
}
return ret != -1 ? a[ret] : x;
}
public long update(int ind, long x)
{
int ret = imap[ind];
if(imap[ind] < 0){
a[pos] = x; map[pos] = ind; imap[ind] = pos;
pos++;
up(pos-1);
}else{
a[ret] = x;
up(ret);
down(ret);
}
return x;
}
public long remove(int ind)
{
if(pos == 1)return INF;
if(imap[ind] == -1)return INF;
pos--;
int rem = imap[ind];
long ret = a[rem];
map[rem] = map[pos];
imap[map[pos]] = rem;
imap[ind] = -1;
a[rem] = a[pos];
a[pos] = INF;
map[pos] = -1;
up(rem);
down(rem);
return ret;
}
public long min() { return a[1]; }
public int argmin() { return map[1]; }
public int size() { return pos-1; }
private void up(int cur)
{
for(int c = cur, p = c>>>1;p >= 1 && a[p] > a[c];c>>>=1, p>>>=1){
long d = a[p]; a[p] = a[c]; a[c] = d;
int e = imap[map[p]]; imap[map[p]] = imap[map[c]]; imap[map[c]] = e;
e = map[p]; map[p] = map[c]; map[c] = e;
}
}
private void down(int cur)
{
for(int c = cur;2*c < pos;){
int b = a[2*c] < a[2*c+1] ? 2*c : 2*c+1;
if(a[b] < a[c]){
long d = a[c]; a[c] = a[b]; a[b] = d;
int e = imap[map[c]]; imap[map[c]] = imap[map[b]]; imap[map[b]] = e;
e = map[c]; map[c] = map[b]; map[b] = e;
c = b;
}else{
break;
}
}
}
}
public static int[][][] packWU(int n, int[] from, int[] to, int[] w) {
int[][][] g = new int[n][][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to)
p[t]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]][2];
for (int i = 0; i < from.length; i++) {
--p[from[i]];
g[from[i]][p[from[i]]][0] = to[i];
g[from[i]][p[from[i]]][1] = w[i];
--p[to[i]];
g[to[i]][p[to[i]]][0] = from[i];
g[to[i]][p[to[i]]][1] = w[i];
}
return g;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F2().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["4 4 3\n1 2 1\n2 3 1\n2 4 1\n3 1 1", "7 11 2\n1 2 5\n1 3 5\n2 4 2\n2 5 2\n3 6 3\n3 7 3\n4 6 2\n3 4 2\n6 7 3\n4 5 7\n4 7 7"] | 2.5 seconds | ["2", "4"] | NoteIn the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. | Java 8 | standard input | [
"data structures",
"graphs",
"shortest paths"
] | c47d0c9a429030c4b5d6f5605be36c75 | The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, , 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. | 2,800 | Print a single integer, the answer to the problem. | standard output | |
PASSED | 7a0f31871fb9927cef03b09e27d9ea5f | train_000.jsonl | 1484235300 | It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.Please also note that only friends that are waiting for a gift count as unhappy, even if they die.Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.PriorityQueue;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
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);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
public ArrayList<Dijkstra.Edge>[] graph;
public ArrayList<Integer>[] dag;
public ArrayList<Integer>[] inc;
public ArrayList<Integer>[] child;
public int[] size;
public int[] depth;
public int[][] anc;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt(), s = in.nextInt() - 1;
graph = new ArrayList[n];
for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1, b = in.nextInt() - 1, c = in.nextInt();
graph[a].add(new Dijkstra.Edge(b, c));
graph[b].add(new Dijkstra.Edge(a, c));
}
long[] dist = new long[n];
Dijkstra.dijkstra(graph, dist, s);
dag = new ArrayList[n];
inc = new ArrayList[n];
int[] indeg = new int[n];
for (int i = 0; i < n; i++) dag[i] = new ArrayList<>();
for (int i = 0; i < n; i++) inc[i] = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (Dijkstra.Edge e : graph[i]) {
if (dist[i] + e.weight == dist[e.to]) {
dag[i].add(e.to);
inc[e.to].add(i);
indeg[e.to]++;
}
}
}
child = new ArrayList[n];
for (int i = 0; i < n; i++) child[i] = new ArrayList<>();
int front = 0, back = 0;
int[] queue = new int[n];
queue[back++] = s;
anc = new int[20][n];
for (int[] x : anc) Arrays.fill(x, -1);
depth = new int[n];
while (front < back) {
int cur = queue[front++];
if (cur == s) {
depth[s] = 0;
anc[0][s] = -1;
} else {
int par = inc[cur].get(0);
for (int i = 1; i < inc[cur].size(); i++) {
int d = inc[cur].get(i);
par = lca(par, d);
}
depth[cur] = depth[par] + 1;
anc[0][cur] = par;
for (int i = 1; i < 20; i++) {
if (anc[i - 1][cur] == -1) {
break;
} else {
anc[i][cur] = anc[i - 1][anc[i - 1][cur]];
}
}
child[par].add(cur);
}
for (int next : dag[cur]) if (--indeg[next] == 0) queue[back++] = next;
}
size = new int[n];
dfs(s);
int ret = 0;
for (int i = 0; i < n; i++) {
if (i != s)
ret = Math.max(ret, size[i]);
}
out.println(ret);
}
public int dfs(int node) {
size[node] = 1;
for (int next : child[node]) {
size[node] += dfs(next);
}
return size[node];
}
public int lca(int a, int b) {
if (depth[a] < depth[b]) {
a ^= b;
b ^= a;
a ^= b;
}
int diff = depth[a] - depth[b];
for (int i = 0; (1 << i) <= diff; i++)
if ((diff & (1 << i)) != 0)
a = anc[i][a];
if (a == b)
return a;
int log = 0;
while (1 << (log + 1) <= depth[a])
log++;
for (int i = log; i >= 0; i--)
if (anc[i][a] != anc[i][b]) {
a = anc[i][a];
b = anc[i][b];
}
return anc[0][a];
}
}
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(int i) {
writer.println(i);
}
}
static class Dijkstra {
public static long INF = 1L << 60;
public static void dijkstra(ArrayList<Dijkstra.Edge>[] graph, long[] dist, int start) {
int N = dist.length;
Arrays.fill(dist, INF);
PriorityQueue<Dijkstra.Edge> pq = new PriorityQueue<Dijkstra.Edge>();
pq.add(new Dijkstra.Edge(start, dist[start] = 0));
while (pq.size() > 0) {
int node = pq.peek().to;
long weight = pq.peek().weight;
pq.poll();
if (dist[node] != weight) continue;
for (Dijkstra.Edge e : graph[node]) {
if (dist[e.to] > dist[node] + e.weight)
pq.add(new Dijkstra.Edge(e.to, dist[e.to] = dist[node] + e.weight));
}
}
}
public static class Edge implements Comparable<Dijkstra.Edge> {
public int to;
public long weight;
public Edge(int to, long weight) {
this.to = to;
this.weight = weight;
}
public int compareTo(Dijkstra.Edge other) {
return Long.compare(weight, other.weight);
}
}
}
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 | ["4 4 3\n1 2 1\n2 3 1\n2 4 1\n3 1 1", "7 11 2\n1 2 5\n1 3 5\n2 4 2\n2 5 2\n3 6 3\n3 7 3\n4 6 2\n3 4 2\n6 7 3\n4 5 7\n4 7 7"] | 2.5 seconds | ["2", "4"] | NoteIn the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. | Java 8 | standard input | [
"data structures",
"graphs",
"shortest paths"
] | c47d0c9a429030c4b5d6f5605be36c75 | The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, , 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. | 2,800 | Print a single integer, the answer to the problem. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.