exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k ⌀ | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k ⌀ | difficulty int64 -1 3.5k ⌀ | prob_desc_output_spec stringlengths 17 1.47k ⌀ | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 184f9878df2567786022c757447b826e | train_003.jsonl | 1329750000 | One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
public class c {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
char[][] names = new char[n][m];
for(int i = 0; i<n; i++)
{
String s = input.next();
for(int j = 0; j<m; j++)
{
names[i][j] = s.charAt(j);
}
}
long res = 1;
for(int i = 0; i<m; i++)
{
boolean[] appear = new boolean[26];
for(int j = 0; j<n; j++)
appear[names[j][i]-'A'] = true;
int count = 0;
for(boolean b: appear)
if(b) count++;
res *= count;
res %= 1000000007;
}
System.out.println(res);
}
} | Java | ["2 3\nAAB\nBAA", "4 5\nABABA\nBCGDG\nAAAAA\nYABSA"] | 2 seconds | ["4", "216"] | NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB". | Java 8 | standard input | [
"combinatorics"
] | a37df9b239a40473516d1525d56a0da7 | The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters. | 1,400 | Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7). | standard output | |
PASSED | 92a4160b393c94d44058591b7bf79ebf | train_003.jsonl | 1441902600 | A tree of size n is an undirected connected graph consisting of n vertices without cycles.Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation. | 256 megabytes |
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.*;
public class Main
{
static FastScanner in = new FastScanner(System.in);
static StringBuilder sb = new StringBuilder();
static DecimalFormat df = new DecimalFormat();
public static void main(String[] args)
{
df.setMaximumFractionDigits(20);
df.setMinimumFractionDigits(20);
df.setRoundingMode(RoundingMode.DOWN);
// String formatted = df.format(0.2);
// Never sort array of primitive type
int N = in.nextInt();
int P[] = new int[N];
for (int i = 0; i < N; i++)
P[i] = in.nextInt() - 1;
int fixed = -1;
for (int i = 0; i < N; i++)
if (i == P[i])
fixed = i;
if (fixed >= 0)
{
System.out.println("YES");
for (int i = 0; i < N; i++)
{
if (i != fixed)
{
System.out.println((i + 1) + " " + (fixed + 1));
}
}
return;
}
int center = -1;
for (int i = 0; i < N; i++)
if (i == P[P[i]])
center = i;
if (center == -1)
{
System.out.println("NO");
return;
}
boolean seen[] = new boolean[N];
seen[center] = seen[P[center]] = true;
sb.append("YES\n");
sb.append(center + 1);
sb.append(' ');
sb.append(P[center] + 1);
sb.append('\n');
for (int i = 0; i < N; i++)
{
if (seen[i]) continue;
ArrayList<Integer> ary = new ArrayList<Integer>();
int cur = i;
while (!seen[cur])
{
ary.add(cur);
seen[cur] = true;
cur = P[cur];
}
if (ary.size() % 2 == 1)
{
System.out.println("NO");
return;
}
for (int j = 0; j < ary.size(); j++)
{
sb.append(ary.get(j) + 1);
sb.append(' ');
if (j % 2 == 0)
{
sb.append(center + 1);
}
else
{
sb.append(P[center] + 1);
}
sb.append('\n');
}
}
System.out.print(sb.toString());
}
static BigInteger b(long n) { return BigInteger.valueOf(n);}
static BigInteger b(String s) { return new BigInteger(s); }
static BigDecimal bd(double d) { return BigDecimal.valueOf(d);}
static BigDecimal bd(String s) { return new BigDecimal(s); }
}
class FastScanner
{
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner (InputStream inputStream)
{
reader = new BufferedReader(new InputStreamReader(inputStream));
}
String nextToken()
{
while (tokenizer == null || ! tokenizer.hasMoreTokens())
{
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e){}
}
return tokenizer.nextToken();
}
boolean hasNext()
{
if (tokenizer == null || ! tokenizer.hasMoreTokens())
{
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e){ return false; }
}
return true;
}
int nextInt()
{
return Integer.parseInt(nextToken());
}
}
| Java | ["4\n4 3 2 1", "3\n3 1 2"] | 1 second | ["YES\n4 1\n4 2\n1 3", "NO"] | NoteIn the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.It can be shown that in the second sample test no tree satisfies the given condition. | Java 7 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ecb8f82b073b374a603552fdd95391b | The first line contains number n (1 ≤ n ≤ 105) — the size of the permutation (also equal to the size of the sought tree). The second line contains permutation pi (1 ≤ pi ≤ n). | 2,100 | If the sought tree does not exist, print "NO" (without the quotes). Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers — the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter. If there are multiple solutions, output any of them. | standard output | |
PASSED | 2d56bf53aaf9ae02684e66441dbd3fc1 | train_003.jsonl | 1441902600 | A tree of size n is an undirected connected graph consisting of n vertices without cycles.Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main implements Runnable
{
class Cycle implements Comparable<Cycle>
{
int len;
ArrayList<Integer> v;
public int compareTo( Cycle o )
{
return len - o.len;
}
}
void solve() throws Exception
{
int n = nextInt();
int[] p = new int[ n + 1 ];
for( int i = 1; i <= n; i++ ) p[ i ] = nextInt();
int[] c = new int[ n + 1 ];
Cycle[] ca = new Cycle[ n + 1 ];
int cal = 0;
for( int i = 1; i <= n; i++ ) if( c[ i ] == 0 )
{
Cycle cc = new Cycle();
cc.len = 0;
cc.v = new ArrayList<Integer>();
for( int j = i; c[ j ] == 0; c[ j ] = -1, j = p[ j ], cc.len++ ) cc.v.add( j );
for( int j = i; c[ j ] == -1; c[ j ] = cc.len, j = p[ j ] );
ca[ cal++ ] = cc;
}
Arrays.sort( ca, 0, cal );
if( ca[ 0 ].len == 1 )
{
out.println( "YES" );
int center = ca[ 0 ].v.get( 0 );
for( int i = 1; i <= n; i++ ) if( i != center )
{
out.println( center + " " + i );
}
}
else
{
boolean ans = true;
for( int i = 0; i < cal; i++ )
{
if( ca[ i ].len % 2 != 0 ) ans = false;
}
ans &= ca[ 0 ].len == 2;
if( ans )
{
out.println( "YES" );
out.println( ca[ 0 ].v.get( 0 ) + " " + ca[ 0 ].v.get( 1 ) );
for( int i = 1; i < cal; i++ )
{
for( int j = 0; j < ca[ i ].len; j++ )
{
out.println( ca[ i ].v.get( j ) + " " + ca[ 0 ].v.get( j % 2 ) );
}
}
}
else
{
out.println( "NO" );
}
}
}
public static void main( String[] args )
{
new Thread( null, new Main(), "1", ( 1 << 27 ) ).start();
}
public void run()
{
try
{
Locale.setDefault( Locale.US );
in = new BufferedReader( new InputStreamReader( System.in ) );
out = new PrintWriter( System.out );
st = null;
solve();
}
catch( Exception e )
{
e.printStackTrace();
System.exit( 1 );
}
finally
{
out.close();
}
}
String nextToken() throws IOException
{
while( st == null || !st.hasMoreTokens() ) st = new StringTokenizer( in.readLine() );
return st.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt( nextToken() );
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
} | Java | ["4\n4 3 2 1", "3\n3 1 2"] | 1 second | ["YES\n4 1\n4 2\n1 3", "NO"] | NoteIn the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.It can be shown that in the second sample test no tree satisfies the given condition. | Java 7 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ecb8f82b073b374a603552fdd95391b | The first line contains number n (1 ≤ n ≤ 105) — the size of the permutation (also equal to the size of the sought tree). The second line contains permutation pi (1 ≤ pi ≤ n). | 2,100 | If the sought tree does not exist, print "NO" (without the quotes). Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers — the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter. If there are multiple solutions, output any of them. | standard output | |
PASSED | d498f87d668c10759768650383b0c5b5 | train_003.jsonl | 1441902600 | A tree of size n is an undirected connected graph consisting of n vertices without cycles.Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
/**
* @author Pavel Mavrin
*/
public class B {
private void solve() throws IOException {
int n = nextInt();
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = nextInt() - 1;
}
boolean[] z = new boolean[n];
List<List<Integer>> c = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!z[i]) {
int j = i;
List<Integer> cc = new ArrayList<>();
while (!z[j]) {
z[j] = true;
cc.add(j + 1);
j = p[j];
}
c.add(cc);
}
}
Collections.sort(c, new Comparator<List<Integer>>() {
@Override
public int compare(List<Integer> o1, List<Integer> o2) {
return Integer.compare(o1.size(), o2.size());
}
});
if (c.get(0).size() == 2) {
for (int i = 1; i < c.size(); i++) {
if (c.get(i).size() % 2 > 0) {
out.println("NO");
return;
}
}
out.println("YES");
out.println(c.get(0).get(0) + " " + c.get(0).get(1));
for (int i = 1; i < c.size(); i++) {
for (int j = 0; j < c.get(i).size(); j++) {
out.println(c.get(i).get(j) + " " + c.get(0).get(j % 2));
}
}
} else if (c.get(0).size() == 1) {
out.println("YES");
for (int i = 1; i < c.size() ; i++) {
for (int j = 0; j < c.get(i).size(); j++) {
out.println(c.get(i).get(j) + " " + c.get(0).get(0));
}
}
} else {
out.println("NO");
}
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
PrintWriter out = new PrintWriter(System.out);
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static void main(String[] args) throws IOException {
new B().run();
}
private void run() throws IOException {
solve();
out.close();
}
}
| Java | ["4\n4 3 2 1", "3\n3 1 2"] | 1 second | ["YES\n4 1\n4 2\n1 3", "NO"] | NoteIn the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.It can be shown that in the second sample test no tree satisfies the given condition. | Java 7 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ecb8f82b073b374a603552fdd95391b | The first line contains number n (1 ≤ n ≤ 105) — the size of the permutation (also equal to the size of the sought tree). The second line contains permutation pi (1 ≤ pi ≤ n). | 2,100 | If the sought tree does not exist, print "NO" (without the quotes). Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers — the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter. If there are multiple solutions, output any of them. | standard output | |
PASSED | 577fdddfe37b6209bc69208e6d4eb67a | train_003.jsonl | 1441902600 | A tree of size n is an undirected connected graph consisting of n vertices without cycles.Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation. | 256 megabytes | import java.util.*;
import java.io.*;
public class B576 {
public static void main(String[] args) throws Exception
{
EspyScanner input = new EspyScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt();
int[] p = new int[n];
for(int i =0 ;i <n; i++) p[i] = input.nextInt()-1;
boolean good = true;
int idx = -1, idx2 = -1;
boolean[] seen = new boolean[n];
for(int i = 0; i<n; i++)
{
if(i == p[i]) idx = i;
else if(i == p[p[i]]) idx2 = i;
else
{
int len = 0;
int at = i;
while(!seen[at])
{
seen[at] = true;
len++;
at = p[at];
}
if(len%2 == 1) good = false;
}
}
if(idx != -1)
{
out.println("YES");
for(int i = 0; i<n; i++)
{
if(i != idx) out.println((i+1)+" "+(idx+1));
}
}
else if(good && idx2 != -1)
{
boolean[] found = new boolean[n];
int[] as = new int[n-1], bs = new int[n-1];
int at = 0;
found[idx2] = found[p[idx2]] = true;
for(int i = 0; i<n; i++)
{
if(i == idx2)
{
as[at] = i;
bs[at++] = p[i];
}
else if(!found[i])
{
int cur = i;
while(!found[cur])
{
as[at] = idx2;
bs[at++] = cur;
as[at] = p[idx2];
bs[at++] = p[cur];
found[cur] = found[p[cur]] = true;
cur = p[p[cur]];
}
}
}
out.println("YES");
for(int i = 0; i<at; i++) out.println((as[i]+1)+" "+(bs[i]+1));
}
else out.println("NO");
out.close();
}
public static class EspyScanner {
public final int BASE_SPEED = 110;
public BufferedReader bf;
public StringTokenizer st;
public EspyScanner(InputStream in) throws Exception {
bf = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public String next() throws Exception {
if (st == null || !st.hasMoreTokens()) {
String line = bf.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
return next();
}
return st.nextToken();
}
}
} | Java | ["4\n4 3 2 1", "3\n3 1 2"] | 1 second | ["YES\n4 1\n4 2\n1 3", "NO"] | NoteIn the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.It can be shown that in the second sample test no tree satisfies the given condition. | Java 7 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ecb8f82b073b374a603552fdd95391b | The first line contains number n (1 ≤ n ≤ 105) — the size of the permutation (also equal to the size of the sought tree). The second line contains permutation pi (1 ≤ pi ≤ n). | 2,100 | If the sought tree does not exist, print "NO" (without the quotes). Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers — the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter. If there are multiple solutions, output any of them. | standard output | |
PASSED | ff3738525f56475b7737116c20df562e | train_003.jsonl | 1441902600 | A tree of size n is an undirected connected graph consisting of n vertices without cycles.Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation. | 256 megabytes | import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class InvarianceOfTree {
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
boolean one = false;
int idOne = -1;
boolean two = false;
int idTwoA = -1;
int idTwoB = -1;
boolean notEven = false;
int p[] = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i=0; i<n; i++){
p[i] = Integer.parseInt(st.nextToken())-1;
}
boolean visited[] = new boolean[n];
int size;
for(int i=0; i<n; i++){
if( p[i] == i ){
one = true;
idOne = i;
}
else if(p[ p[i] ] == i){
two = true;
idTwoA = i;
idTwoB = p[i];
}
}
if(one){
System.out.println("YES");
for(int i=0; i<n; i++){
if( i == idOne)
continue;
System.out.println( (i+1)+" "+(idOne+1) );
}
}else if(two){
int aux = 0;
x.add(idTwoA);
y.add(idTwoB);
for(int i=0; i<n; i++){
if(i==idTwoA || i== idTwoB)
continue;
if(visited[i])
continue;
int k = i;
while(!visited[k]){
visited[k]=true;
if(aux == 0){
x.add(idTwoA);
y.add(k);
}
else{
x.add(idTwoB);
y.add(k);
}
aux = 1-aux;
k = p[k];
}
if(aux == 1)
notEven = true;
}
if(notEven)
System.out.println("NO");
else{
System.out.println("YES");
for(int i=0; i<x.size(); i++){
System.out.println( (x.get(i)+1) + " " + (y.get(i)+1));
}
}
}else
System.out.println("NO");
}
}
| Java | ["4\n4 3 2 1", "3\n3 1 2"] | 1 second | ["YES\n4 1\n4 2\n1 3", "NO"] | NoteIn the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.It can be shown that in the second sample test no tree satisfies the given condition. | Java 7 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ecb8f82b073b374a603552fdd95391b | The first line contains number n (1 ≤ n ≤ 105) — the size of the permutation (also equal to the size of the sought tree). The second line contains permutation pi (1 ≤ pi ≤ n). | 2,100 | If the sought tree does not exist, print "NO" (without the quotes). Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers — the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter. If there are multiple solutions, output any of them. | standard output | |
PASSED | 5e30125b6f6f460eef16e1bb161f97a2 | train_003.jsonl | 1441902600 | A tree of size n is an undirected connected graph consisting of n vertices without cycles.Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation. | 256 megabytes | import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class B implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new B(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
int[] readIntArrayWithDecrease(int size) throws IOException {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
BigInteger readBigInteger() throws IOException {
return new BigInteger(readString());
}
BigDecimal readBigDecimal() throws IOException {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
throws IOException{
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
public IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
public int getRealIndex() {
return index + 1;
}
}
IntIndexPair[] readIntIndexArray(int size) throws IOException {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
protected int precision;
protected String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
static final boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
static final boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
static final long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
static final Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
static class DSU {
static Random rnd = new Random();
int[] parents;
public DSU(int size) {
parents = new int[size];
for (int i = 0; i < size; ++i) {
parents[i] = i;
}
}
int get(int v) {
if (v == parents[v]) return v;
return (parents[v] = get(parents[v]));
}
boolean union(int a, int b) {
a = get(a);
b = get(b);
if (a != b) {
if (rnd.nextBoolean()) {
parents[a] = b;
} else {
parents[b] = a;
}
return true;
} else {
return false;
}
}
}
void solve() throws IOException {
int n = readInt();
int[] p = readIntArrayWithDecrease(n);
List<List<Integer>> cycles = new ArrayList<List<Integer>>();
boolean[] used = new boolean[n];
for (int i = 0; i < n; ++i) {
if (!used[i]) {
List<Integer> cycle = new ArrayList<Integer>();
cycle.add(i);
used[i] = true;
for (int cur = p[i]; cur != i; cur = p[cur]) {
cycle.add(cur);
used[cur] = true;
}
cycles.add(cycle);
}
}
Collections.sort(cycles, new Comparator<List<Integer>>() {
@Override
public int compare(List<Integer> l1, List<Integer> l2) {
if (l1.size() < l2.size()) return 1;
if (l1.size() > l2.size()) return -1;
return 0;
}
});
int cyclesSize = cycles.size();
int[] sizeToIndexes = new int[n + 1];
Arrays.fill(sizeToIndexes, -1);
for (int index = 0; index < cyclesSize; ++index) {
sizeToIndexes[cycles.get(index).size()] = index;
}
int[] parents = new int[cyclesSize];
parents[cyclesSize - 1] = -1;
List<Integer> lastCycle = cycles.get(cyclesSize - 1);
Map<Integer, Integer> lastSizeIndexes = new HashMap<Integer, Integer>();
lastSizeIndexes.put(lastCycle.size(), cyclesSize - 1);
it: for (int index = cyclesSize - 2; index >= 0; --index) {
int curSize = cycles.get(index).size();
if (lastSizeIndexes.get(curSize) != null) {
parents[index] = lastSizeIndexes.get(curSize);
lastSizeIndexes.put(curSize, index);
continue;
}
lastSizeIndexes.put(curSize, index);
for (int d = 1; d * d <= curSize; ++d) {
if (curSize % d == 0) {
if (sizeToIndexes[d] != -1) {
parents[index] = sizeToIndexes[d];
continue it;
} else if (d != 1 && sizeToIndexes[curSize / d] != -1) {
parents[index] = sizeToIndexes[curSize / d];
continue it;
}
}
}
out.println("NO");
return;
}
List<Point> treeEdges = new ArrayList<Point>();
DSU dsu = new DSU(n);
for (int i = 0; i < cycles.size() - 1; ++i) {
List<Integer> curCycle = cycles.get(i);
List<Integer> nextCycle = cycles.get(parents[i]);
int curCycleSize = curCycle.size();
int nextCycleSize = nextCycle.size();
if (curCycleSize % nextCycleSize != 0) {
out.println("NO");
return;
}
for (int j = 0; j < curCycleSize; ++j) {
int from = curCycle.get(j);
int to = nextCycle.get(j % nextCycleSize);
treeEdges.add(new Point(from + 1, to + 1));
if (!dsu.union(from, to)) {
out.println("NO");
return;
}
}
}
if (lastCycle.size() == 1) {
} else if (lastCycle.size() == 2) {
int from = lastCycle.get(0);
int to = lastCycle.get(1);
treeEdges.add(new Point(from + 1, to + 1));
if (!dsu.union(from, to)) {
out.println("NO");
return;
}
}
int root = 0;
int rootParent = dsu.get(root);
for (int v = 0; v < n; ++v) {
if (dsu.get(v) != rootParent) {
out.println("NO");
return;
}
}
out.println("YES");
for (Point edge : treeEdges) {
out.println(edge.x + " " + edge.y);
}
}
}
| Java | ["4\n4 3 2 1", "3\n3 1 2"] | 1 second | ["YES\n4 1\n4 2\n1 3", "NO"] | NoteIn the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.It can be shown that in the second sample test no tree satisfies the given condition. | Java 7 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ecb8f82b073b374a603552fdd95391b | The first line contains number n (1 ≤ n ≤ 105) — the size of the permutation (also equal to the size of the sought tree). The second line contains permutation pi (1 ≤ pi ≤ n). | 2,100 | If the sought tree does not exist, print "NO" (without the quotes). Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers — the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter. If there are multiple solutions, output any of them. | standard output | |
PASSED | 08d9995a7bfdae4784ec40580d424615 | train_003.jsonl | 1441902600 | A tree of size n is an undirected connected graph consisting of n vertices without cycles.Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
/********************************************** a list of common variables **********************************************/
private MyScanner scan = new MyScanner();
private PrintWriter out = new PrintWriter(System.out);
private final long INF = Long.MAX_VALUE;
private final double PI = Math.acos(-1.0);
private final int SIZEN = (int)(1e5);
private final int MOD = (int)(1e9 + 7);
private final int[] DX = {0, 1, 0, -1}, DY = {-1, 0, 1, 0};
private ArrayList<Integer>[] edge;
private int[] f;
public void foo()
{
int n = scan.nextInt();
int[] p = new int[n];
int k = -1;
for(int i = 0;i < n;++i)
{
p[i] = scan.nextInt();
if(i == p[i] - 1)
{
k = i + 1;
}
}
if(k != -1)
{
out.println("YES");
for(int i = 1;i <= n;++i)
{
if(k != i)
{
out.println(k + " " + i);
}
}
return;
}
boolean[] vis = new boolean[n];
ArrayList<ArrayList<Integer>> loops = new ArrayList<ArrayList<Integer>>();
int indexOfLen2 = -1;
for(int i = 0;i < n;++i)
{
if(!vis[i])
{
int j = i;
ArrayList<Integer> arr = new ArrayList<Integer>();
do
{
vis[j] = true;
arr.add(p[j]);
j = p[j] - 1;
} while(j != i);
if(1 == arr.size() % 2)
{
out.println("NO");
return;
}
if(2 == arr.size())
{
indexOfLen2 = loops.size();
}
loops.add(arr);
}
}
if(-1 == indexOfLen2)
{
out.println("NO");
return;
}
out.println("YES");
int a = loops.get(indexOfLen2).get(0);
int b = loops.get(indexOfLen2).get(1);
out.println(a + " " + b);
for(int i = 0;i < loops.size();++i)
{
if(i != indexOfLen2)
{
ArrayList<Integer> arr = loops.get(i);
for(int j = 0;j < arr.size();++j)
{
if(0 == j % 2)
{
out.println(a + " " + arr.get(j));
}
else
{
out.println(b + " " + arr.get(j));
}
}
}
}
}
public static void main(String[] args)
{
Main m = new Main();
m.foo();
m.out.close();
}
/********************************************** a list of common algorithms **********************************************/
/**
* 1---Get greatest common divisor
* @param a : first number
* @param b : second number
* @return greatest common divisor
*/
public long gcd(long a, long b)
{
return 0 == b ? a : gcd(b, a % b);
}
/**
* 2---Get the distance from a point to a line
* @param x1 the x coordinate of one endpoint of the line
* @param y1 the y coordinate of one endpoint of the line
* @param x2 the x coordinate of the other endpoint of the line
* @param y2 the y coordinate of the other endpoint of the line
* @param x the x coordinate of the point
* @param y the x coordinate of the point
* @return the distance from a point to a line
*/
public double getDist(long x1, long y1, long x2, long y2, long x, long y)
{
long a = y2 - y1;
long b = x1 - x2;
long c = y1 * (x2 - x1) - x1 * (y2 - y1);
return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
}
/**
* 3---Get the distance from one point to a segment (not a line)
* @param x1 the x coordinate of one endpoint of the segment
* @param y1 the y coordinate of one endpoint of the segment
* @param x2 the x coordinate of the other endpoint of the segment
* @param y2 the y coordinate of the other endpoint of the segment
* @param x the x coordinate of the point
* @param y the y coordinate of the point
* @return the distance from one point to a segment (not a line)
*/
public double ptToSeg(long x1, long y1, long x2, long y2, long x, long y)
{
double cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1);
if(cross <= 0)
{
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
}
double d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
if(cross >= d)
{
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
double r = cross / d;
double px = x1 + (x2 - x1) * r;
double py = y1 + (y2 - y1) * r;
return (x - px) * (x - px) + (y - py) * (y - py);
}
/**
* 4---KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1.
* @param t: String to match.
* @param p: String to be matched.
* @return if can match, first index; otherwise -1.
*/
public int kmpMatch(char[] t, char[] p)
{
int n = t.length;
int m = p.length;
int[] next = new int[m + 1];
next[0] = -1;
int j = -1;
for(int i = 1;i < m;++i)
{
while(j >= 0 && p[i] != p[j + 1])
{
j = next[j];
}
if(p[i] == p[j + 1])
{
++j;
}
next[i] = j;
}
j = -1;
for(int i = 0;i < n;++i)
{
while(j >= 0 && t[i] != p[j + 1])
{
j = next[j];
}
if(t[i] == p[j + 1])
{
++j;
}
if(j == m - 1)
{
return i - m + 1;
}
}
return -1;
}
class MyScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
BufferedInputStream bis = new BufferedInputStream(System.in);
public int read()
{
if (-1 == numChars)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = bis.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 & 15;
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 & 15) * m;
c = read();
}
}
return res * sgn;
}
public String next()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c)
{
return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
}
}
} | Java | ["4\n4 3 2 1", "3\n3 1 2"] | 1 second | ["YES\n4 1\n4 2\n1 3", "NO"] | NoteIn the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.It can be shown that in the second sample test no tree satisfies the given condition. | Java 7 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ecb8f82b073b374a603552fdd95391b | The first line contains number n (1 ≤ n ≤ 105) — the size of the permutation (also equal to the size of the sought tree). The second line contains permutation pi (1 ≤ pi ≤ n). | 2,100 | If the sought tree does not exist, print "NO" (without the quotes). Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers — the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter. If there are multiple solutions, output any of them. | standard output | |
PASSED | 4d4fe768137985ab673018271df4bc5e | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.util.*;
public class j
{
public static void main(String[] args)
{
HashMap<String, String> H = new HashMap<String, String>();
int n;
Scanner cin = new Scanner(System.in);
n = cin.nextInt();
int i;
String s, value, aux;
for (i = 1; i <= n; i++)
{
s = cin.next();
value = cin.next();
if (H.containsKey(s))
{
aux = H.get(s);
H.remove(s);
H.put(value, aux);
}
else
H.put(value, s);
}
System.out.println(H.size());
for(Map.Entry pp: H.entrySet())
System.out.println(pp.getValue() + " " + pp.getKey());
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 8357a6c6e92a06102ac582a213167081 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] str = new String[n];
int nm = 0;
Map<String,String> map = new HashMap<>();
Set<String> set = new HashSet<>();
int count =0;
String[] ind = new String[n];
int j =0;
for(int i=0; i<n; i++){
String[] sr = br.readLine().split(" ");
if(!set.contains(sr[0])){
count++;
ind[j++] = sr[0];
}
set.add(sr[0]);
set.add(sr[1]);
map.put(sr[0], sr[1]);
}
System.out.println(count);
for(int i=0; i<j; i++){
String g = ind[i];
while(map.containsKey(g)){
String sd = map.get(g);
g = sd;
}
System.out.println(ind[i]+" "+g);
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | fde7b31c08d7a5e62eb1d3a92161ea48 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import static java.lang.Double.max;
import java.util.Map.Entry;
import java.util.Scanner;
/**
*
* @author ESC
*/
public class JavaApplication39 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner (System.in);
int n ,c; n=in.nextInt(); c=n;
boolean [] b1 = new boolean[n];
boolean [] b2 = new boolean[n];
String p[][] = new String[n][2];
for(int i=0;i<n;i++)
{p[i][0]=in.next(); p[i][1]=in.next(); b1[i]=b2[i]=false;}
for(int i = 0; i < n; i++)
for(int j = i+1;j<n; j++)
{
if( p[i][1].equals(p[j][0]))
{
p[i][1]=p[j][1]; c--; b1[i]=true; b2[i]=true; b2[j]=true;
p[j][0]=p[i][0];
}
}
System.out.println(c);
for(int i=0; i <n; i ++)
{
if(b1[i]==true||b2[i]==false)
{System.out.println(p[i][0]+" " +p[i][1]);}
}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 577234ed4f26718df0418260a2fcaed6 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
public class MeshaAndChangingHandles {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int q=sc.nextInt();
HashMap<String,String>map=new HashMap<String,String>();
while(q-->0) {
String a=sc.next();
String b=sc.next();
if(!map.containsKey(a)) {
map.put(b, a);
}
else {
String c=map.get(a);
map.remove(a);
map.put(b, c);
}
}
System.out.println(map.size());
for( String s:map.keySet()) {
System.out.println(map.get(s)+" "+s);
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
++start;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 8c1de0d2262fbf1116ce7f75dcbfda5b | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
public class MeshaAndChangingHandles {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int q=sc.nextInt();
HashMap<String,String>map=new HashMap<String,String>();
while(q-->0) {
String a=sc.next();
String b=sc.next();
if(!map.containsKey(a)) {
map.put(b, a);
}
else {
String c=map.get(a);
map.remove(a);
map.put(b, c);
}
}
System.out.println(map.size());
for( String s:map.keySet()) {
System.out.println(map.get(s)+" "+s);
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 4f81d86c180e033f133c0cd183d5a4c0 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class ACM2 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)) ;
StringTokenizer tk = new StringTokenizer(in.readLine());
int n = Integer.parseInt(tk.nextToken());
Map<String, String> map = new HashMap<>();
for (int i = 0; i < n; i++) {
tk = new StringTokenizer(in.readLine());
String s1 = tk.nextToken();
String s2 = tk.nextToken();
map.put(s1, s2);
}
ArrayList<String> L = new ArrayList<>();
for (String m : map.keySet()) {
String first = m;
String last = m;
while (map.get(last) != null) {
last = map.get(last);
map.put(first, last);
L.add(last) ;
}
}
for (int i = 0; i < L.size(); i++) {
map.remove(L.get(i));
}
out.write(map.size() + "");
out.newLine();
for(String m : map.keySet()){
out.write(m + " " + map.get(m));
out.newLine();
}
out.flush();
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | c69a1a8c3e6491fd002a0f50e60a1dfe | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class ACM2 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tk = new StringTokenizer(in.readLine());
int n = Integer.parseInt(tk.nextToken());
Map<String, String> map = new HashMap<>();
for (int i = 0; i < n; i++) {
tk = new StringTokenizer(in.readLine());
String s1 = tk.nextToken();
String s2 = tk.nextToken();
map.put(s1, s2);
}
ArrayList<String> L = new ArrayList<>();
for (String m : map.keySet()) {
String first = m;
String last = m;
while (map.get(last) != null) {
last = map.get(last);
map.put(first, last);
L.add(last) ;
}
}
for (int i = 0; i < L.size(); i++) {
map.remove(L.get(i));
}
System.out.println(map.size());
for(String m : map.keySet()){
System.out.println(m + " " + map.get(m));
}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | b175b954cc41d881db06ee303fa1db74 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class Misha {
public static void main(String[] args) throws Exception{
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
String line;
int q,c,i;
q =Integer.parseInt(bi.readLine());
String[] tt;
HashMap<String, String> list=new HashMap<String,String>();
tt=bi.readLine().split("\\s");
list.put(tt[0], tt[1]);
c=0;i=1;
while(i<q){
tt=bi.readLine().split("\\s");
Iterator<Entry<String, String>> it=list.entrySet().iterator();
int j=0;
while(it.hasNext()){
Map.Entry<String, String> kv=it.next();
if(tt[0].equals(kv.getValue())){
list.put(kv.getKey(), tt[1]);
break;
}
j++;
}
if(j>=list.size()){
list.put(tt[0], tt[1]);
}
i++;
}
System.out.println(list.size());
Iterator<Entry<String, String>> it=list.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, String> kv=it.next();
System.out.println(kv.getKey()+" "+kv.getValue());
}
System.exit(0);
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | b588c1984f6bc962534938b3bb5c81b2 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class Sol
{
static int[] vis;
static class qu
{
String f;
String s;
qu(String x,String y)
{
f=x;
s=y;
}
}
static qu[] arr;
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int q=Integer.parseInt(br.readLine());
arr=new qu[q];
ArrayList<qu> al=new ArrayList<>();
for(int i=0;i<q;i++)
{
String[] t1=br.readLine().split(" ");
qu que=new qu(t1[0],t1[1]);
arr[i]=que;
}
vis=new int[q];
int count=0;
Arrays.fill(vis,0);
for(int j=0;j<q;j++)
{
if(vis[j]==1)
{
continue;
}
else if(vis[j]==0)
{
count++;
vis[j]=1;
String a=arr[j].f;
String b="";
b=recur(arr[j].s,j,q);
//System.out.println(a+" "+b);
qu obj=new qu(a,b);
al.add(obj);
}
}
System.out.println(count);
for(qu xy:al)
{
System.out.println(xy.f+" "+xy.s);
}
}
public static String recur(String str,int ci,int si)
{
for(int l=ci+1;l<si;l++)
{
if((arr[l].f).equals(str)&&vis[l]==0)
{
vis[l]=1;
return recur(arr[l].s,l,si);
}
}
return str;
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | d6654bc72c1f2eb2ce977a3ee343b0fb | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Graph1 {
//static int flag=1;
//private static int n,l,r,z,way=0;
private static InputStream stream;
private static byte[] buf=new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
private static long count=0;
public static void main(String args[] ) throws Exception
{
InputReader(System.in);
pw=new PrintWriter(System.out);
soln();
pw.close();
}
public static boolean PointInTriangle(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8)
{
int s = p2 * p5 - p1 * p6 + (p6 - p2) * p7 + (p1 - p5) * p8;
int t = p1 * p4 - p2 * p3 + (p2 - p4) * p7 + (p3 - p1) * p8;
if ((s < 0) != (t < 0))
return false;
int A = -p4 * p5 + p2 * (p5 - p3) + p1 * (p4 - p6) + p3 * p6;
if (A < 0.0)
{
s = -s;
t = -t;
A = -A;
}
return s > 0 && t > 0 && (s + t) <= A;
}
public static float area(int x1, int y1, int x2, int y2, int x3, int y3){
return (float)Math.abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);
}
public static boolean isPrime(int n)
{
// Corner cases
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n%2 == 0 || n%3 == 0) return false;
for (int i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
//merge Sort
public static void Merge_sort(int a[]){
int len=a.length;
if(len <2)
return ;
int mid=len/2;
int l[]=new int[mid];
int r[] =new int[len-mid];
for(int i=0;i<mid;i++)
l[i]=a[i];
for(int i=mid;i<len;i++)
r[i-mid]=a[i];
Merge_sort(l);
Merge_sort(r);
Merge(l,r,a);
}
public static void Merge(int []l,int[]r,int a[]){
int nl=l.length;
int nr=r.length;
int i=0,j=0,k=0;
while(i <nl && j<nr){
if(l[i] > r[j]){
a[k]=l[i];
k++;
i++;
}
else{
a[k]=r[j];
k++;
j++;
}
while(i<nl){
a[k]=l[i];
k++;
i++;
}
while(j<nr){
a[k]=r[j];
k++;
j++;
}
}
}
public static boolean isSubSequence(String large,String small,int largeLen,int smallLen){
//base cases
if(largeLen==0)
return false;
if(smallLen==0)
return true;
// If last characters of two strings are matching
if(large.charAt(largeLen-1)==small.charAt(smallLen-1))
isSubSequence(large, small, largeLen-1, smallLen-1);
// If last characters are not matching
return isSubSequence(large, small, largeLen-1, smallLen);
}
// To Get Input
// Some Buffer Methods
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private static int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private static int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private static long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private static void pArray(int[] arr){
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static void pArray(long[] arr){
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static void pArray(boolean[] arr){
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
private static void soln() {
int n=nextInt();
String s[]=new String[n];
for(int i=0;i<n;i++)
s[i]=nextLine();
HashSet hs=new HashSet();
HashMap<String,String> hm=new HashMap<>();
for(int i=0;i<n;i++){
StringTokenizer str=new StringTokenizer(s[i]);
String t=str.nextToken().toString();
if(!hs.contains(t)){
hs.add(t);
String t1=str.nextToken().toString();
for(int j=i+1;j<n;j++){
StringTokenizer ss=new StringTokenizer(s[j]);
String i1=ss.nextToken().toString();
String i2=ss.nextToken().toString();
if(i1.equals(t1)){
hs.add(t1);
//StringTokenizer sr=new StringTokenizer(s[j]);
// hs.add(sr.nextToken().toString());
t1=i2;
hs.add(t1);
}
}
hm.put(t, t1);
//System.out.println(t+" "+t1);
}
}
System.out.println(hm.size());
Set setOfKeys = hm.keySet();
Iterator it=setOfKeys.iterator();
while(it.hasNext()){
String k=it.next().toString();
System.out.println(k+" "+hm.get(k));
}
}
}
class Dsu{
private int rank[], parent[] ,n;
Dsu(int size){
this.n=size+1;
rank=new int[n];
parent=new int[n];
makeSet();
}
void makeSet(){
for(int i=0;i<n;i++){
parent[i]=i;
}
}
int find(int x){
if(parent[x]!=x){
parent[x]=find(parent[x]);
}
return parent[x];
}
void union(int x,int y){
int xRoot=find(x);
int yRoot=find(y);
if(xRoot==yRoot)
return;
if(rank[xRoot]<rank[yRoot]){
parent[xRoot]=yRoot;
}else if(rank[yRoot]<rank[xRoot]){
parent[yRoot]=xRoot;
}else{
parent[yRoot]=xRoot;
rank[xRoot]++;
}
}
}
class Graph{
private long conse=0,co=0,mac_cons_cat=0;
private int V,flag=1;
private Stack <Integer>st=new Stack();
private LinkedList<Integer > adj[];
// boolean Visited[];
Graph(int V,int max_cat){
V++;
this.mac_cons_cat=max_cat;
this.V=(V);
adj=new LinkedList[V];
for(int i=0;i<V;i++)
adj[i]=new LinkedList();
//Visited=new boolean[V];
}
void addEdge(int v,int w){
adj[v].add(w);
}
public long dfs(int startVertex,int[] a,boolean[] b){
boolean Visited[]=new boolean[V];
//flag=1;
co=0;
conse=0;
if(!Visited[startVertex]) {
//co=1;
dfsUtil(startVertex,Visited,a,b);
}
return co;
}
private void dfsUtil(int startVertex, boolean[] Visited,int[] a,boolean[] b) {
//System.out.println(pre+" "+startVertex);
Visited[startVertex]=true;
if(a[startVertex-1]==1)
conse++;
st.push(startVertex);
while(!st.isEmpty()){
int top=st.pop();
//System.out.println(top);
//System.out.println(top);
Iterator<Integer> i=adj[top].listIterator();
while(i.hasNext()){
int n=i.next();
// System.out.println(n+"---");
if( !Visited[n]){
Visited[n]=true;
if(a[n-1]==1){
conse++;
}else{
if(a[n-1]==1)
conse=1;else
conse=0;
}
if(conse>mac_cons_cat)
{
Iterator<Integer> it=adj[n].listIterator();
while(it.hasNext()){
Visited[it.next()]=true;
}
//break;
}
else{
if(!b[n]){
co++;
}
}
st.push(n);
//count++;
}
}
}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | eb626f1e42afbdfd709511d56fc6f1c6 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.*;
public final class Solution{
public static void main(String args[]){
HashMap<String, String> map = new HashMap<>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String old = "a", news = "b";
int count = 0;
for(int i = 0; i < n; i++){
if(sc.hasNext()){
old = sc.next();
news = sc.next();}
if(!map.containsValue(old)){
map.put(old, news);
count++;
}
else{
Iterator hmIterator = map.entrySet().iterator();
while (hmIterator.hasNext()) {
Map.Entry mapElement = (Map.Entry)hmIterator.next();
String key = ((String)mapElement.getKey());
String val = ((String)mapElement.getValue());
if(val.equals(old)){
map.put(key, news);
break;
}
}
}
}
System.out.println(count);
Iterator hmIterator = map.entrySet().iterator();
while (hmIterator.hasNext()) {
Map.Entry mapElement = (Map.Entry)hmIterator.next();
String key = ((String)mapElement.getKey());
String val = ((String)mapElement.getValue());
System.out.println(key + " " + val);
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | c7ae71e2afc91d47ba880c4d59de349f | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.io.*;
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());
HashSet<String> hash = new HashSet<String>();
HashSet<String> firstTime = new HashSet<String>();
DisjointSet set = new DisjointSet();
while(n-- !=0)
{
String str[] = reader.readLine().split(" ");
if(!firstTime.contains(str[0]) && !hash.contains(str[1]) && !hash.contains(str[0]))
firstTime.add(str[0]);
if(!hash.contains(str[0]))
{
hash.add(str[0]);
set.makeSet(str[0]);
}
if(!hash.contains(str[1]))
{
hash.add(str[1]);
set.makeSet(str[1]);
}
set.union(str[0], str[1]);
}
System.out.println(firstTime.size());
for(String s : firstTime)
{
System.out.println(s+" "+set.findSet(s).data);
}
}
}
class Node
{
String data ;
int rank ;
int count;
Node parent ;
}
class DisjointSet
{
HashMap<String, Node> map ;
public DisjointSet() {
// TODO Auto-generated constructor stub
map = new HashMap<String, Node>();
}
void makeSet(String data)
{
Node node = new Node();
node.data = data;
node.parent = node;
node.count=1;
node.rank = 0;
map.put(data, node);
}
public Node findSet(String data)
{
// System.out.println(data);
return findSet(map.get(data));
}
private Node findSet(Node node)
{
Node parent = node.parent;
if (parent == node) {
return parent;
}
node.parent = findSet(node.parent);
return node.parent;
}
public boolean union(String data1, String data2)
{
Node node1 = map.get(data1);
Node node2 = map.get(data2);
Node parent1 = findSet(node1);
Node parent2 = findSet(node2);
//if they are part of same set do nothing
if (parent1.data == parent2.data) {
return false;
}
if (parent1.rank < parent2.rank)
{
//increment rank only if both sets have same rank
parent1.rank = (parent1.rank == parent2.rank) ? parent1.rank + 1 : parent1.rank;
parent2.parent = parent1;
}
else
{
parent1.parent = parent2;
}
return true;
}
public int findSize()
{
return map.size();
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 81ee1b8302a9ff60814819f4248c2599 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
TaskB Solver = new TaskB();
Solver.Solve();
}
public static class TaskB {
private static void Solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
ArrayList <User> ar = new ArrayList<>();
int l = 0;
for (int i = 0; i < n; i++) {
String old = in.next();
String cur = in.next();
boolean find = false;
for (int j = 0; j < l; j++)
if (ar.get(j).curName.equals(old)) {
ar.get(j).curName = new String(cur);
find = true;
break;
}
if (!find) {
ar.add(new User(old, cur));
l++;
}
}
System.out.println(l);
for (int i = 0; i < l; i++)
System.out.println(ar.get(i).oldName + " " + ar.get(i).curName);
}
private static class User {
private String oldName, curName;
public User(String oldName, String curName) {
this.oldName = oldName;
this.curName = curName;
}
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 6bf188742bb7dc14d63a3cef69953658 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
@SuppressWarnings("unused")
public class A {
public static Scanner scan = new Scanner(System.in);
public static void solve () {
int n=scan.nextInt();
HashMap<String , String> h= new HashMap<String, String>();
for(int i=0;i<n;i++) {
String a=scan.next(),b=scan.next();
if(h.containsKey(a)) {
String s=h.get(a);
h.remove(a);
a=s;
}
h.put(b, a);
}
System.out.println(h.size());
Set<Entry<String , String>> hmap=h.entrySet();
for (Entry<String, String> s : hmap) {
System.out.println(s.getValue()+" "+s.getKey());
}
}
public static void main(String[] args) {
solve();
scan.close();
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 1f175c431268b133a9468bcce952520d | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
public class JavaApplication3 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
StringTokenizer tok = new StringTokenizer(sc.nextLine());
int n = Integer.parseInt(tok.nextToken());
Map<String,String> m = new HashMap<>();
for (int i = 0; i < n; i++) {
tok = new StringTokenizer(sc.nextLine());
String v = tok.nextToken();
String k = tok.nextToken();
if(m.isEmpty())
{ m.put(k, v);
continue;
}
else if(m.containsKey(v)){
String vv = m.get(v);
m.remove(v,vv);
m.put(k, vv);
}
else
{
m.put(k, v);
}
}
System.out.println(m.size());
for(String q : m.keySet()){
System.out.println(m.get(q)+" "+q);
}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | ef09d16b29b0310f20a131f07af12b92 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class JavaApplication3 {
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer tok = new StringTokenizer(r.readLine());
int n = Integer.parseInt(tok.nextToken());
Map<String,String> m = new HashMap<>();
for (int i = 0; i < n; i++) {
tok = new StringTokenizer(r.readLine());
String v = tok.nextToken();
String k = tok.nextToken();
if(m.isEmpty())
{ m.put(k, v);
continue;
}
else if(m.containsKey(v)){
String vv = m.get(v);
m.remove(v,vv);
m.put(k, vv);
}
else
{
m.put(k, v);
}
}
w.write(m.size()+"");
w.newLine();
for(String q : m.keySet()){
w.write(m.get(q)+" "+q);
w.newLine();
}
w.flush();
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 6ccc9c91aa8dfcb9f76c524efcdfa9a2 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class runtimeError {
public static void main (String[] args) throws IOException , NumberFormatException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bf.readLine());
String [][] a = new String[n][2];
for (int i = 0 ; i < n ; i++) {
StringTokenizer st = new StringTokenizer(bf.readLine());
a[i][0] = st.nextToken();
a[i][1] = st.nextToken();
}
int count =0;
for (int i = 0 ; i < n ; i++){
String current = a[i][1];
for (int k = 0 ; k < n ; k++ ){
//if (k == i) continue;
if (current.equals(a[k][0])){
a[i][1] = a[k][1];
a[k][0] = "";
current = a[k][1];
k=0;
count++;
}
}
}
System.out.println(n-count);
for(int i = 0 ; i < n ; i++){
if (!a[i][0].equals("")){
System.out.print(a[i][0] + " " + a[i][1]);
System.out.println();
}
}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | dbea8fa6f085eaa06549b4787ee38eec | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class runtimeError {
public static void main (String[] args) throws IOException , NumberFormatException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bf.readLine());
String [][] a = new String[n][2];
for (int i = 0 ; i < n ; i++) {
StringTokenizer st = new StringTokenizer(bf.readLine());
a[i][0] = st.nextToken();
a[i][1] = st.nextToken();
}
int count =0;
for (int i = 0 ; i < n ; i++){
String current = a[i][1];
for (int k = 0 ; k < n ; k++ ){
//if (k == i) continue;
if (current.equals(a[k][0])){
a[i][1] = a[k][1];
a[k][0] = "";
current = a[k][1];
k=0;
count++;
}
}
}
System.out.println(n-count);
for(int i = 0 ; i < n ; i++){
if (!a[i][0].equals("")){
System.out.print(a[i][0] + " " + a[i][1]);
System.out.println();
}
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 5425b3419ae43cadd9529b705659f561 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | /*
█████╗ ██╗ ██╗████████╗██╗ ██╗ ██████╗ ██████╗ ███████╗██╗ ██╗ █████╗ ██████╗ ██╗ ██╗
██╔══██╗██║ ██║╚══██╔══╝██║ ██║██╔═══██╗██╔══██╗██╗ ██╔════╝██║ ██║██╔══██╗██╔══██╗╚██╗ ██╔╝
███████║██║ ██║ ██║ ███████║██║ ██║██████╔╝╚═╝ ███████╗███████║███████║██║ ██║ ╚████╔╝
██╔══██║██║ ██║ ██║ ██╔══██║██║ ██║██╔══██╗██╗ ╚════██║██╔══██║██╔══██║██║ ██║ ╚██╔╝
██║ ██║╚██████╔╝ ██║ ██║ ██║╚██████╔╝██║ ██║╚═╝ ███████║██║ ██║██║ ██║██████╔╝ ██║
╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═╝
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main {
private static Reader in;
private static PrintWriter out;
////////////////////////////////////////////////////////////////////////////////////////////////////
private static int min(int... a){int min=a[0]; for(int i:a) min=Math.min(min, i); return min;}
private static int max(int... a){int max=a[0]; for(int i:a) max=Math.max(max, i); return max;}
private static long min(long... a){long min=a[0]; for(long i:a)min=Math.min(min, i); return min;}
private static long max(long... a){long max=a[0]; for(long i:a)max=Math.max(max, i); return max;}
private static String strm(String str, long m) {
String ans="";
while(m>0) {
if(m%2==1) ans=ans.concat(str);
str=str.concat(str); m>>=1;
} return ans;
}
private static long mod(long a, long mod) {long res = a%mod; return res>=0 ? res : res+mod;}
private static int mod(int a, int mod) {int res = a%mod; return res>=0 ? res : res+mod;}
private static long modpow(long base, long exp, long mod) {
return new BigInteger(Long.toString(base)).modPow(new BigInteger(Long.toString(exp)), new BigInteger(Long.toString(mod))).longValueExact();
}
private static int modpow(int x, int n, int mod) {
int res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) {
if ((n & 1) != 0) {
res = (int) (res * p % mod);
}
}
return res;
}
private static long gcd(long a, long b) {return b == 0 ? Math.abs(a) : gcd(b, a % b);}
private static int gcd(int a, int b) {return b == 0 ? Math.abs(a) : gcd(b, a % b);}
private static long gcd(long... a) {long gcd=a[0]; for(long x:a) gcd=gcd(gcd, x); return gcd;}
private static int gcd(int... a) {int gcd=a[0]; for(int x:a) gcd=gcd(gcd, x); return gcd;}
private static class Pair {
public int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Pair)) return false;
Pair pair = (Pair)obj;
return this.x == pair.x && this.y == pair.y;
}
@Override
public int hashCode() {
return (this.x+" "+this.y).hashCode();
}
}
private static class Triplet {
public int x, y, z;
public Triplet(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Triplet)) return false;
Triplet triplet = (Triplet)obj;
return this.x == triplet.x && this.y == triplet.y && this.z == triplet.z;
}
@Override
public int hashCode() {
return (this.x+" "+this.y+" "+this.z).hashCode();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static class Reader {
private BufferedReader br;
private StringTokenizer token;
protected Reader(FileReader obj) {
br = new BufferedReader(obj, 32768);
token = null;
}
protected Reader() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
token = null;
}
protected String next() {
while(token == null || !token.hasMoreTokens()) {
try {
token = new StringTokenizer(br.readLine());
} catch (Exception e) {e.printStackTrace();}
} return token.nextToken();
}
protected String nextLine() {
String str="";
try {
str = br.readLine();
} catch (Exception e) {e.printStackTrace();}
return str;
}
protected int nextInt() {return Integer.parseInt(next());}
protected long nextLong() {return Long.parseLong(next());}
protected double nextDouble() {return Double.parseDouble(next());}
protected long[] nextLongArr(int n) {
long[] arr = new long[n]; for(int i=0; i<n; i++) arr[i] = nextLong(); return arr;
}
protected int[] nextIntArr(int n) {
int[] arr = new int[n]; for(int i=0; i<n; i++) arr[i] = nextInt(); return arr;
}
}
static class Node<T> {
T data;
Node parent;
int rank, setSize;
boolean first, last;
}
static class DisjointSet<T> {
private HashMap<T, Node> hm = new HashMap<>();
int numOfSets=0;
private void makeSet(T data) {
if (isPresent(data)) return;
Node node = new Node();
node.parent = node;
node.rank = 0;
node.data = data;
node.setSize = 1;
node.first = true; node.last = true;
hm.put(data, node);
numOfSets++;
}
private void union(T data1, T data2) {
if (!isPresent(data1)) makeSet(data1);
if (!isPresent(data2)) makeSet(data2);
Node node1 = hm.get(data1), node2 = hm.get(data2);
Node parent1 = findSet(hm.get(data1)), parent2 = findSet(hm.get(data2));
if (parent1.data == parent2.data) return;
if (parent1.rank >= parent2.rank) {
parent1.rank = parent1.rank == parent2.rank ? parent1.rank+1 : parent1.rank;
parent2.parent = parent1;
parent1.setSize += parent2.setSize;
} else {
parent1.parent = parent2;
parent2.setSize += parent1.setSize;
}
node1.last = false; node2.first = false; node2.last = true;
numOfSets--;
}
private boolean isPresent(T data) {
return hm.containsKey(data);
}
private Node findSet(Node node) {
Node parent = node.parent;
if (parent == node) return parent;
node.parent = findSet(node.parent);
return node.parent;
}
private int setSize(T data) {
if (!isPresent(data)) return 0;
return findSet(hm.get(data)).setSize;
}
}
private static void solve() {
DisjointSet<String> ds = new DisjointSet<>();
int q = in.nextInt();
while (q-->0) {
String s1 = in.next(), s2 = in.next();
ds.makeSet(s1); ds.makeSet(s2); ds.union(s1, s2);
}
out.printf("%d\n", ds.numOfSets);
HashMap<Node, ArrayList<String>> hashMap = new HashMap<>();
for (Map.Entry<String, Node> entry : ds.hm.entrySet()) {
Node parent = ds.findSet(entry.getValue());
ArrayList<String> temp;
if (hashMap.containsKey(parent)) temp = hashMap.get(parent);
else temp = new ArrayList<>(Arrays.asList("", ""));
if (entry.getValue().first) {
temp.set(0, entry.getKey());
hashMap.put(parent, temp);
} else if (entry.getValue().last) {
temp.set(1, entry.getKey());
hashMap.put(parent, temp);
}
}
for (Map.Entry<Node, ArrayList<String>> entry: hashMap.entrySet()) {
out.printf("%s %s\n", entry.getValue().get(0), entry.getValue().get(1));
}
}
public static void main(String[] args) throws IOException {
// in = new Reader(new FileReader("C:\\Users\\Suhaib\\Desktop\\input.txt"));
// out = new PrintWriter(new FileWriter("C:\\Users\\Suhaib\\Desktop\\output.txt"));
in = new Reader();
out = new PrintWriter(System.out);
solve();
out.close();
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 2ffb6ffe0e1d251942afe22328cbd330 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static class Reader {
private BufferedReader br;
private StringTokenizer token;
protected Reader(FileReader obj) {
br = new BufferedReader(obj, 32768);
token = null;
}
protected Reader() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
token = null;
}
protected String next() {
while(token == null || !token.hasMoreTokens()) {
try {
token = new StringTokenizer(br.readLine());
} catch (Exception e) {e.printStackTrace();}
} return token.nextToken();
}
protected int nextInt() {return Integer.parseInt(next());}
protected long nextLong() {return Long.parseLong(next());}
protected double nextDouble() {return Double.parseDouble(next());}
}
static class Node<T> {
Node parent;
int rank;
T data;
boolean first, last;
}
static class DisjointSet<T> {
private HashMap<T, Node> hm = new HashMap<>();
int numOfSets = 0;
private void makeSet(T data) {
if (isPresent(data)) return;
Node<T> node = new Node<>();
node.parent = node;
node.data = data;
node.rank = 0;
node.first = true; node.last = true;
hm.put(data, node);
numOfSets++;
}
private void union(T data1, T data2) {
Node node1 = hm.get(data1), node2 = hm.get(data2);
Node parent1 = findSet(node1), parent2 = findSet(node2);
if (parent1.data == parent2.data) return;
if (parent1.rank >= parent2.rank) {
parent1.rank = parent1.rank == parent2.rank ? parent1.rank+1:parent1.rank;
parent2.parent = parent1;
} else parent1.parent = parent2;
node1.last = false; node2.first = false; node2.last = true;
numOfSets--;
}
private boolean isPresent(T data) {
return hm.containsKey(data);
}
private Node findSet(Node node) {
Node parent = node.parent;
if (parent == node) {
return parent;
}
node.parent = findSet(node.parent);
return node.parent;
}
}
public static void main(String[] args) throws IOException {
Reader in = new Reader();
PrintWriter out = new PrintWriter(System.out);
DisjointSet<String> ds = new DisjointSet<>();
int n = in.nextInt();
for (int i=0; i<n; i++) {
String s1 = in.next(), s2 = in.next();
ds.makeSet(s1); ds.makeSet(s2); ds.union(s1, s2);
}
out.printf("%d\n", ds.numOfSets);
HashMap<Node, ArrayList<String>> ans = new HashMap<>();
for (Map.Entry<String, Node> entry: ds.hm.entrySet()) {
Node node = ds.findSet(entry.getValue());
ArrayList<String> temp;
if (ans.containsKey(node)) temp = ans.get(node);
else temp = new ArrayList<>(Arrays.asList("", ""));
if (entry.getValue().first) {
temp.set(0, entry.getKey());
ans.put(node, temp);
} else if (entry.getValue().last) {
temp.set(1, entry.getKey());
ans.put(node, temp);
}
}
for (Map.Entry<Node, ArrayList<String>> entry: ans.entrySet())
out.printf("%s %s\n", entry.getValue().get(0), entry.getValue().get(1));
out.close();
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | a798075978c4b8f3d7d3a09784defd62 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static class Reader {
private BufferedReader br;
private StringTokenizer token;
protected Reader(FileReader obj) {
br = new BufferedReader(obj, 32768);
token = null;
}
protected Reader() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
token = null;
}
protected String next() {
while(token == null || !token.hasMoreTokens()) {
try {
token = new StringTokenizer(br.readLine());
} catch (Exception e) {e.printStackTrace();}
} return token.nextToken();
}
protected int nextInt() {return Integer.parseInt(next());}
protected long nextLong() {return Long.parseLong(next());}
protected double nextDouble() {return Double.parseDouble(next());}
}
static class Node<T> {
Node parent;
int rank;
T data;
boolean first, last;
}
static class DisjointSet<T> {
private HashMap<T, Node> hm = new HashMap<>();
int numOfSets = 0;
private void makeSet(T data) {
if (isPresent(data)) return;
Node<T> node = new Node<>();
node.parent = node;
node.data = data;
node.rank = 0;
node.first = true; node.last = true;
hm.put(data, node);
numOfSets++;
}
private void union(T data1, T data2) {
if (!isPresent(data1)) makeSet(data1);
if (!isPresent(data2)) makeSet(data2);
Node node1 = hm.get(data1), node2 = hm.get(data2);
Node parent1 = findSet(node1), parent2 = findSet(node2);
if (parent1.data == parent2.data) return;
if (parent1.rank >= parent2.rank) {
parent1.rank = parent1.rank == parent2.rank ? parent1.rank+1:parent1.rank;
parent2.parent = parent1;
} else {
parent1.parent = parent2;
}
node1.last = false;
node2.first = false;
node2.last = true;
numOfSets--;
}
private boolean isPresent(T data) {
return hm.containsKey(data);
}
private Node findSet(Node node) {
Node parent = node.parent;
if (parent == node) {
return parent;
}
node.parent = findSet(node.parent);
return node.parent;
}
}
public static void main(String[] args) throws IOException {
Reader in = new Reader();
PrintWriter out = new PrintWriter(System.out);
DisjointSet<String> ds = new DisjointSet<>();
int n = in.nextInt();
for (int i=0; i<n; i++) {
String s1 = in.next(), s2 = in.next();
ds.makeSet(s1); ds.makeSet(s2); ds.union(s1, s2);
}
out.printf("%d\n", ds.numOfSets);
HashMap<Node, ArrayList<String>> ans = new HashMap<>();
for (Map.Entry<String, Node> entry: ds.hm.entrySet()) {
Node node = ds.findSet(entry.getValue());
ArrayList<String> temp;
if (ans.containsKey(node))
temp = ans.get(node);
else
temp = new ArrayList<>(Arrays.asList("", ""));
if (entry.getValue().first) {
temp.set(0, entry.getKey());
ans.put(node, temp);
} else if (entry.getValue().last) {
temp.set(1, entry.getKey());
ans.put(node, temp);
}
}
for (Map.Entry<Node, ArrayList<String>> entry: ans.entrySet()) {
out.printf("%s %s\n", entry.getValue().get(0), entry.getValue().get(1));
}
out.close();
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 00178fbc6a2bea2235ea9ab8ae18d875 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.*;
public class b {
public static void main(String[] arg)
{
new b();
}
public b()
{
Scanner in = new Scanner(System.in);
ArrayList<ArrayList<String>> eList = new ArrayList<ArrayList<String>>();
int size = in.nextInt();
for(int q = 0; q < size; q++)
{
String v1 = in.next();
String v2 = in.next();
boolean flag = true;
for(int i = 0; i < eList.size(); i++)
{
if(eList.get(i).get(eList.get(i).size()-1).equals(v1))
{
flag = false;
eList.get(i).add(v2);
break;
}
}
if(flag)
{
eList.add(new ArrayList<String>());
eList.get(eList.size()-1).add(v1);
eList.get(eList.size()-1).add(v2);
}
}
System.out.println(eList.size());
for(int i = 0; i < eList.size(); i++)
{
System.out.println(eList.get(i).get(0) + " " + eList.get(i).get(eList.get(i).size()-1));
}
in.close();
}
/*
public b()
{
Scanner in = new Scanner(System.in);
HashSet<String> original = new HashSet<String>();
HashMap<String, String> hm = new HashMap<String, String>();
int size = in.nextInt();
for(int i = 0; i < size; i++)
{
String v1 = in.next();
String v2 = in.next();
if(!hm.containsKey(v1))
{
original.add(v1);
hm.put(v1, v2);
hm.put(v2, null);
}
else
{
hm.put(v1, v2);
}
}
System.out.println(original.size());
for(String key: original)
{
System.out.print(key + " ");
System.out.println(solve(key, hm));
}
in.close();
}
public String solve(String key, HashMap<String, String> hm)
{
if(key == null) return null;
if(hm.get(key) == null) return key;
return solve(hm.get(key), hm);
}
*/
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 54d322b6963132f24a33c81164827d1a | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
import static java.lang.Integer.parseInt;
public class B_Misha_and_Changing_Handles {
static HashMap<String,String> map;
static String[] st;
static StringBuilder ans;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tk;
ans = new StringBuilder();
map = new HashMap<>();
int n = parseInt(in.readLine());
st = new String[n];
for (int i = 0; i < n; i++) {
tk = new StringTokenizer(in.readLine());
st[i] = tk.nextToken();
map.put(st[i],tk.nextToken());
}
for (int i = 0; i < n; i++) {
String val = map.get(st[i]);
String val2;
while(true){
if(map.containsKey(val)){
val2 = val;
val = map.get(val);
map.remove(val2);
}
else {
map.replace(st[i],val);
break;
}
}
}
int c = map.keySet().size();
ans.append(c).append("\n");
for (String key:map.keySet()){
ans.append(key).append(" ").append(map.get(key)).append("\n");
}
System.out.println(ans);
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 8876c3e95c4634d9bb4051ae49432b97 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.*;
public class ah{
public static void main (String []args){
Scanner sc=new Scanner(System.in);
int n=Integer.parseInt(sc.nextLine());
String old[]=new String[n];
String nw[]=new String[n];
int c=0;
for (int i=0;i<n;i++){
String s=sc.nextLine();
String h[]=s.split("\\s+");
boolean b=true;
for(int j=0;j<n &&b==true;j++){
if(h[0].equals(nw[j])){
b=false;
nw[j]=h[1];}
}
if (b){
old[c]=h[0];
nw[c]=h[1];
c++;
}
}
System.out.println(c);
if (c==1){
System.out.print(old[0]+" ");
System.out.print(nw[0]);}
else{
for(int p=c-1;p>=0;p--){
if (!(old[p]==null )){
System.out.print(old[p]+" ");
System.out.println(nw[p]);}
}}
}}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 963fc3add7665985e08002d9a7a7d0ff | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.*;
public class abc
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String arr[][]=new String[n][3];
int c=0;
sc.nextLine();
for(int i=1;i<=n;i++)
{
String temp=sc.nextLine();
String a=temp.substring(0,temp.indexOf(" "));
String b=temp.substring(1+temp.indexOf(" "));
int j;
for(j=0;j<c;j++)
{
if(a.equals(arr[j][2]))
break;
}
if(j==c)
{
arr[c][0]=arr[c][1]=a;
arr[c++][2]=b;
}
else
{
arr[j][1]=arr[j][2];
arr[j][2]=b;
}
}
System.out.println(c);
for(int i=0;i<c;i++)
{
System.out.println(arr[i][0]+" "+arr[i][2]);
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 2419b87fa98fc27569be09560c946055 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
public class B501Codeforces {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(bf.readLine());
String aold[]=new String [n];
String anew[]=new String [n];
for(int i=0;i<n;i++){
StringTokenizer ns =new StringTokenizer(bf.readLine());
aold[i]=ns.nextToken();
anew[i]=ns.nextToken();
}
int output=0;
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(anew[i]!="0" || aold[i]!="0")
if(aold[j].equals(anew[i])){
anew[i]=anew[j];
aold[j]="0";
anew[j]="0";
}
String s="";
for(int i=0;i<aold.length;i++)
if(anew[i]!="0" || aold[i]!="0"){
s+=aold[i]+" "+anew[i]+"\n";
output++;
}
System.out.println(output);
System.out.print(s);
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 1f909a61c6e1201f16e6c80033eca8f6 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
ArrayList<String> keys = new ArrayList<>();
ArrayList<String> values = new ArrayList<>();
Map<String,String> map = new HashMap<>();
Map<String,String> newMap = new HashMap<>();
for (int i = 0; i <n ; i++) {
keys.add(scanner.next());
values.add(scanner.next());
map.put(keys.get(i), values.get(i));
}
for (int i = 0; i <keys.size() ; i++) {
newMap.put(keys.get(i), posl(map,keys,values, keys.get(i), values.get(i)));
}
System.out.println(newMap.size());
for (Map.Entry<String, String> entry : newMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
public static String posl(Map<String,String> map,ArrayList<String> keys,ArrayList<String> values, String a, String now){
if(!map.containsKey(now)) return now;
else{
String s = map.get(now);
values.remove(keys.lastIndexOf(now));
keys.remove(now);
return posl(map,keys,values,a, s);
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 88fb99b69d282bf4779642362a01e7fb | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class Code2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
ArrayList<String> keys = new ArrayList<>();
ArrayList<String> values = new ArrayList<>();
Map<String,String> map = new LinkedHashMap<>();
Map<String,String> newMap = new LinkedHashMap<>();
for (int i = 0; i <n ; i++) {
keys.add(scanner.next());
values.add(scanner.next());
map.put(keys.get(i), values.get(i));
}
for (int i = 0; i <keys.size() ; i++) {
newMap.put(keys.get(i), posl(map,keys,values, keys.get(i), values.get(i)));
}
System.out.println(newMap.size());
for (Map.Entry<String, String> entry : newMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
public static String posl(Map<String,String> map,ArrayList<String> keys,ArrayList<String> values, String a, String now){
if(!map.containsKey(now)) return now;
else{
String s = map.get(now);
values.remove(keys.lastIndexOf(now));
keys.remove(now);
return posl(map,keys,values,a, s);
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 3595607ec17fc0a75cd6099b6f8c249f | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.*;
public class acm {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] old = new String[n];
String[] news = new String[n];
for(int i=0;i<n;i++)
{ old[i]=sc.next();
news[i]=sc.next();}
String result = "";int j=0;int i=0;int counter=0;
while(i<n)
if(contains(news,old[i]))
i++;
else
if(contains(old,news[i]))
{ j=i;
do{if(contains(old,news[j]))
j=getIndex(old,news[j]);
else break;
}while(true);
result=result+old[i]+" "+news[j]+'\n';counter++;
i++;}
else
{result=old[i]+" "+news[i]+'\n'+result;counter++;i++;}
System.out.println(counter);
System.out.println(result);
}
public static boolean contains(String[] s,String x){
for(int i=0;i<s.length;i++)
if(s[i].equals(x))
return true;
return false;
}
public static int getIndex(String[] s,String x){
for(int i=0;i<s.length;i++)
if(s[i].equals(x))
return i;
return -1;
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 62132e85c5bdb306415c75eb6319ddea | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class MishaandChangingHandles {
public static String getkey(HashMap<String, String> map, String value) {
for (String key : map.keySet()) {
if (value.equals(map.get(key)))
return key;
}
return null;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
HashMap<String, String> map = new HashMap<String, String>();
while (n > 0) {
String s[] = sc.nextLine().split(" ");
if (map.containsValue(s[0])) {
String str = getkey(map, s[0]);
map.put(str, s[1]);
} else {
map.put(s[0], s[1]);
}
--n;
}
System.out.println(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | fd1c10d01c2ccf65702952ba33e36bbb | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.*;
public class ninjaturtle {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n= sc.nextInt();
String[][]s=new String[n][2];
for(int i=0;i<n;i++)
{
s[i][0]= sc.next();
s[i][1]=sc.next();
}
int c=0;
for(int k=0;k<n;k++)
{
String nw=s[k][1];
for(int j=0;j<n;j++)
{
if(nw.equals(s[j][0]))
{
s[k][1]=s[j][1];
s[j][0]="";
nw=s[j][1];
j=0;
c++;
}
}
}
int a=n-c;
System.out.println(a);
for(int i=0;i<n;i++)
{
if(!s[i][0].equals(""))
{
System.out.println(s[i][0]+" "+s[i][1]);
}
}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | f1a594beb5693e11012784279f367854 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class hello2
{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 sc =new FastReader();
int n=sc.nextInt();
String arr[][]=new String[n][2];
int cnt=0;
for(int i=0;i<n;i++){
String old=sc.next(),newh=sc.next();
int j;
boolean pres=false;
for(j=0;j<cnt;j++){
if(old.equals(arr[j][1])){
arr[j][1]=newh;
pres=true;
break;
}
}
if(!pres){
cnt++;
arr[cnt-1][0]=old;
arr[cnt-1][1]=newh;
}
}
System.out.println(cnt);
for(int i=0;i<cnt;i++){
System.out.println(arr[i][0]+" "+arr[i][1]);
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | bf79555cd15489ee55c45947b90aa723 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.HashMap;
import java.lang.StringBuffer;
public class Main {
static Scanner in = new Scanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
int n = in.nextInt(), t = 0;
String[] str = new String[n];
StringBuffer sb = new StringBuffer();
HashMap<String, String> p = new HashMap<>(), map = new HashMap<>();
for(int i = 0; i < n; i++) {
str[i] = in.next();
String str2 = in.next();
p.put(str2, "");
map.put(str[i], str2);
}
for(int i = 0; i < n; i++)
if(!p.containsKey(str[i])) {
t++;
sb.append("\n" + str[i] + " ");
while(p.containsKey(map.get(str[i])))
str[i] = map.get(str[i]);
sb.append(str[i]);
}
out.print(t);
out.print(sb);
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
while(!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
String r = st.nextToken("\n");
st = new StringTokenizer(br.readLine(), " ");
return r;
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 6b79d4f6705a69ef4ad254ab0a29a162 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Problem3 {
static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
public static void display(String[][]a){
for(int i = 0;i<a.length;i++){
for(int j =0;j<a[i].length;j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public static String[][] input(int n) throws IOException{
String[][] a = new String[n][2];
for(int i =0;i<n;i++){
String s = bf.readLine();
StringTokenizer st = new StringTokenizer(s);
for(int j =0;j<2;j++){
a[i][j]=st.nextToken();
}
}
return a;
}
public static int check(String[][] a){
int n=0;
boolean b = true;
for(int i = 0;i<a.length;i++){
b = true;
for(int j = a.length-1;j>i;j--){
if((a[i][1].equals(a[j][0])))
b = false;
}
if (b)
n++;
}
return n;
}
public static void arrange(String[][] a){
for(int i = 0;i<a.length;i++){
for(int j = i+1;j<a.length;j++){
if(a[i][1].equals(a[j][0])){
a[i][1]=a[j][1];
}
}
}
}
public static String[][] IN(String[][] a,int row){
String[][]s = new String[row][2];
boolean b = true;
int r = 0;
for(int i = 0;i<a.length;i++){
b = true;
for(int j = i-1 ;j>=0;j--){
if((a[i][1].equals(a[j][1]))){
b = false;
}
}
if(b){
s[r][0]=a[i][0];
s[r][1]=a[i][1];
r++;
}
}
return s;
}
public static void main(String[] args) throws NumberFormatException, IOException {
int n = Integer.parseInt(bf.readLine());
String[][]a=input(n);
int row = check(a);
arrange(a);
String[][]s=IN(a,row);
System.out.println(row);
display(s);
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 820ea826dc7b93d2180949a60fe35e80 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class MishaChangingHandles
{
public static void main (String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int N = Integer.parseInt(br.readLine());
HashMap<String, String> finalNames = new HashMap<String, String>(); //first, current
HashMap<String, String> currentNames = new HashMap<String, String>(); //current, first
StringTokenizer st;
for (int i = 0; i<N; i++)
{
st = new StringTokenizer(br.readLine());
String a = st.nextToken(); // old name
String b = st.nextToken(); // new name
if (!currentNames.containsKey(a)) {
finalNames.put(a, b);
currentNames.put(b, a);
}
// if the name has showed up before
else
{
String first = currentNames.get(a);
currentNames.remove(a);
currentNames.put(b, first);
finalNames.put(first, b);
}
}
System.out.println(finalNames.size());
for (String key: finalNames.keySet()) {
System.out.println(key + " " + finalNames.get(key));
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | bcfcfde0916de2f3dc60b226b31db600 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.*;
public class dsal2 {
static class coordinates {
int x, y;
coordinates(int x, int y) {
this.x = x;
this.y = y;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static class friends {
int a, b, t;
friends(int t, int a, int b) {
this.t = t;
this.a = a;
this.b = b;
}
}
public static void main(String[] args) {
// Scan = new Scanner(System.in);
FastReader fr = new FastReader();
StringBuffer ans = new StringBuffer();
// int t = fr.nextInt();
////
// while (t-- > 0)
// {
//
// }
int n=fr.nextInt();
HashMap<String,String> ktv=new HashMap<>();
HashMap<String,String> vtk=new HashMap<>();
for(int i=0;i<n;i++)
{
String k=fr.next();
String v=fr.next();
if(!ktv.containsKey(k)&&vtk.containsKey(k))
{
String old=vtk.get(k);
ktv.put(old,v);
vtk.remove(k);
vtk.put(v,old);
}
else
{
if(!ktv.containsKey(k)&&!vtk.containsKey(v))
{ktv.put(k,v);
vtk.put(v,k);
}
}
}
ans.append(ktv.size()+"\n");
for(Map.Entry<String,String > i:ktv.entrySet())
{
ans.append(i.getKey()+" "+i.getValue()+"\n");
}
System.out.println(ans);
// System.out.println(ans);
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | db153589e76304a4612fd0359c2d1623 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class MishaAndChagingHandles_B501 {
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int q=Integer.parseInt(br.readLine());
TreeMap<String,Integer> originalsIdx=new TreeMap<>();
TreeMap<Integer,String> originals= new TreeMap<>();
TreeMap<Integer,String> others= new TreeMap<>();
TreeMap<String,Integer> othersIdx= new TreeMap<>();
StringTokenizer tk;
int idx=0;
for(int i=0;i<q;i++)
{
tk = new StringTokenizer(br.readLine());
String s1=tk.nextToken();
String s2=tk.nextToken();
if(!originals.containsValue(s1)&&!others.containsValue(s1))
{
originals.put(idx, s1);
originalsIdx.put(s1, idx);
others.put(idx, s2);
othersIdx.put(s2,idx);
idx++;
}
else if(others.containsValue(s1))
{
int curIdx=othersIdx.get(s1);
others.remove(curIdx);
others.put(curIdx, s2);
othersIdx.remove(s1);
othersIdx.put(s2, curIdx);
}
}
StringBuilder sb = new StringBuilder();
sb.append(originals.size()+"\n");
for(int i=0;i<originals.size();i++)
{
sb.append(originals.get(i)+" "+others.get(i)+"\n");
}
out.println(sb);
out.flush();
out.close();
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 6dbe0f1d6dfa4137335e035c6c12fdd9 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class MishaAndChagingHandles_B501 {
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int q=Integer.parseInt(br.readLine());
TreeMap<String,Integer> originalsIdx=new TreeMap<>();
TreeMap<Integer,String> originals= new TreeMap<>();
TreeMap<Integer,String> others= new TreeMap<>();
TreeMap<String,Integer> othersIdx= new TreeMap<>();
StringTokenizer tk;
int idx=0;
for(int i=0;i<q;i++)
{
tk = new StringTokenizer(br.readLine());
String s1=tk.nextToken();
String s2=tk.nextToken();
if(!originals.containsValue(s1)&&!others.containsValue(s1))
{
originals.put(idx, s1);
originalsIdx.put(s1, idx);
others.put(idx, s2);
othersIdx.put(s2,idx);
idx++;
}
else if(others.containsValue(s1))
{
int curIdx=othersIdx.get(s1);
others.remove(curIdx);
others.put(curIdx, s2);
othersIdx.remove(s1);
othersIdx.put(s2, curIdx);
}
}
StringBuilder sb = new StringBuilder();
sb.append(originals.size()+"\n");
for(int i=0;i<originals.size();i++)
{
sb.append(originals.get(i)+" "+others.get(i)+"\n");
}
out.println(sb);
out.flush();
out.close();
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | b67a1f011dcf58cf47019fd4cc4d672f | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] s = new String[2 * n];
for (int i = 0; i < 2 * n; i += 2) {
s[i] = sc.next();
s[i + 1] = sc.next();
}
int m = 0;
for (int i = 1; i < 2 * n; i += 2)
if (s[i - 1] != "AbC") {
m++;
for (int j = 0; j < 2 * n; j += 2) {
if (s[i].equals(s[j])) {
s[i] = s[j + 1];
s[j] = "AbC";
}
}
}
System.out.println(m);
for (int i = 0; i < 2 * n; i += 2) {
if (s[i] != "AbC")
System.out.println(s[i] + " " + s[i + 1]);
}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 9690840c67ce068cd3fc7eaf004e6e2e | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class Handle
{
public static void main (String [] args) throws IOException
{
InputStreamReader instream=new InputStreamReader (System.in);
BufferedReader input = new BufferedReader (instream);
int n=Integer.parseInt(input.readLine());
int j=1;
int c=0;
String [][]a=new String [n][2];
do{
String s=input.readLine();
StringTokenizer st=new StringTokenizer(s);
String s1=st.nextToken();
String s2=st.nextToken();
for (int i=0;i<n;i++)
{
if (a[i][0]==null)
{
a[i][0]=s1;
a[i][1]=s2;
c++;
break;
}
else if (a[i][1].equals(s1))
{
a[i][1]=s2;
break;
}
}
j++;
}
while(j<=n);
System.out.println(c);
for (int i=0;i<n;i++)
{
if (a[i][0]!=null)
System.out.print(a[i][0]+" "+a[i][1]);
else
break;
System.out.println();
}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 50c08eefb78276efb366632959a89cd9 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class MishaAndChangingHandles {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int q=sc.nextInt();
TreeMap<String,String> map=new TreeMap();
ArrayList<String> old=new ArrayList();
while(q-->0)
{
String a=sc.next(),b=sc.next();
if(!map.containsValue(a))
{
map.put(a, b);
old.add(a);
}
else
map.put(a, b);
}
System.out.println(old.size());
for(String s:old)
{
String y=map.get(s);
while(map.containsKey(y))
y=map.get(y);
System.out.println(s+" "+y);
}
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream S)
{
br=new BufferedReader(new InputStreamReader(S));
}
public String nextLine() throws IOException
{
return br.readLine();
}
public String next() throws IOException
{
while(st==null || !st.hasMoreTokens())
st=new StringTokenizer(nextLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
public boolean ready() throws IOException
{
return br.ready();
}
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | b2224046aaf7753f6b49c43e56c2bef1 | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* User: faer Date: 2/20/16
*/
public class ChangingHandles {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
Map<String, Pair> seenNames = new HashMap<>(n);
for (int i = 0; i < n; i++) {
String[] ar = in.nextLine().split(" ");
String oldName = ar[0];
String newName = ar[1];
if (seenNames.containsKey(oldName)) {
Pair pair = seenNames.remove(oldName);
pair.newName = newName;
seenNames.put(newName, pair);
} else {
Pair pair = new Pair();
pair.oldName = oldName;
pair.newName = newName;
seenNames.put(newName, pair);
}
}
System.out.println(seenNames.size());
for (Pair pair : seenNames.values()) {
System.out.println(pair.oldName + " " + pair.newName);
}
}
static class Pair {
String oldName;
String newName;
}
}
| Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | d759485525f67cf10e686b150e17312d | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
public void solve() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String [] str = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
String [] lectureWords = new String[n];
Map<String,String> map = new HashMap<String,String>();
Map<String,Boolean> mymap = new HashMap<String,Boolean>();
List<String> list = new LinkedList<String>();
for(int i=0;i<n;i++){
str = br.readLine().split(" ");
map.put(str[0],str[1]);
mymap.put(str[1],true);
if(mymap.get(str[0]) == null)
list.add(str[0]);
}
System.out.println(list.size());
for(String spr : list){
String s = spr;
String prev = s;
while((s=map.get(prev))!=null)
prev = s;
System.out.println(spr + " " + prev);
}
}
public static void main(String [] args) throws IOException{
new Solution().solve();
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 0bfbeeea1132711e66bf42726fe62eea | train_003.jsonl | 1421053200 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class ab22
{
public static void main(String agrs[])
{
int n;
int count=0;
Scanner s=new Scanner(System.in);
n=s.nextInt();
HashMap<String,String>hm=new HashMap<String,String>();
HashMap<String,String>hm1=new HashMap<String,String>();
for(int i=0;i<n;i++)
{
String str1=s.next();
String str2=s.next();
if(hm.containsKey(str1))
{
hm.put(str2,hm.get(str1));
hm.remove(str1);
}
else
{count=count+1;
hm.put(str2,str1);
}
}
System.out.println(count);
for( String key : hm.keySet())
{
System.out.println(hm.get(key)+" "+key);
}
}
} | Java | ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"] | 1 second | ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"strings"
] | bdd98d17ff0d804d88d662cba6a61e8f | The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. | 1,100 | In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. | standard output | |
PASSED | 0bae7bc54958607917d26e9a398c6664 | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner SC = new Scanner(System.in);
int n=SC.nextInt();
long minendch=Long.MAX_VALUE, minendp=Long.MAX_VALUE, maxstartch=Long.MIN_VALUE, maxstartp=Long.MIN_VALUE;
for(int i=0; i<n; i++){
maxstartch=Math.max(maxstartch, SC.nextInt());
minendch=Math.min(minendch, SC.nextInt());
}
n=SC.nextInt();
for(int i=0; i<n; i++){
maxstartp=Math.max(maxstartp, SC.nextInt());
minendp=Math.min(minendp, SC.nextInt());
}
System.out.println(Math.max(0, Math.max(maxstartch-minendp, maxstartp-minendch)));
}
} | Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | ec21971cf6eae18eaedff5354cd9a823 | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.io.*;
import java.util.*;
public class S {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException{
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
public static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void main(String args[]) throws IOException{
S.init(System.in);
int n = S.nextInt();
int l1[] = new int[n];
int l2[] = new int[n];
for(int i = 0 ; i < n ; i++) {
int d = S.nextInt();
l1[i] = d;
d = S.nextInt();
l2[i] = d;
}
int m = S.nextInt();
int r1[] = new int[m];
int r2[] = new int[m];
for(int i = 0 ; i < m ; i++) {
int d = S.nextInt();
r1[i] = d;
d = S.nextInt();
r2[i] = d;
}
Arrays.parallelSort(l1);
Arrays.parallelSort(r1);
Arrays.parallelSort(r2);
Arrays.parallelSort(l2);
int ans1 = r1[m - 1] - l2[0];
int ans2 = l1[n - 1] - r2[0];
if(ans1 < 0 && ans2 < 0) {
System.out.println(0);
}else {
System.out.println(Math.max(ans1, ans2));
}
}
} | Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 955f3084e693b249bbf1cd9ca9407423 | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class antonAndClasses {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int l1[] = new int[n];
int r1[] = new int[n];
for (int i = 0; i < n; i++)
{
l1[i] = sc.nextInt();
r1[i] = sc.nextInt();
}
int m = sc.nextInt();
int l2[] = new int[m];
int r2[] = new int[m];
for (int i = 0; i < m; i++)
{
l2[i] = sc.nextInt();
r2[i] = sc.nextInt();
}
int ans1 = 0; int ans2 = 0;
Arrays.sort(r1);
Arrays.sort(l2);
Arrays.sort(l1);
Arrays.sort(r2);
if(l2[m-1] >= r1[0])
ans1 = l2[m-1] - r1[0];
if(l1[n-1] >= r2[0])
ans2 = l1[n-1] - r2[0] ;
System.out.println(Math.max(ans1, ans2));
sc.close();
}
} | Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 2e39764214b895b5664ad2f189474ce0 | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.util.*;import java.io.*;import java.math.*;
public class Main
{
public static void process()throws IOException
{
int n=ni(),l_chess=0,r_chess=Integer.MAX_VALUE,l_prog=0,r_prog=Integer.MAX_VALUE;
//max l, min r
while(n-->0){
l_chess=Math.max(l_chess, ni());
r_chess=Math.min(r_chess, ni());
}
n=ni();
while(n-->0){
l_prog=Math.max(l_prog, ni());
r_prog=Math.min(r_prog, ni());
}
pn(Math.max(0, Math.max(l_prog-r_chess, l_chess-r_prog)));
}
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");
System.out.close();
}
static void pn(Object o){out.println(o);}
static void p(Object o){out.print(o);}
static void pni(Object o){out.println(o);System.out.flush();}
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 boolean multipleTC=false;
static long mod=(long)1e9+7l;
static<T> void r_sort(T arr[],int n){
Random r = new Random();
for (int i = n-1; i > 0; i--){
int j = r.nextInt(i+1);
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Arrays.sort(arr);
}
static long mpow(long x, long n) {
if(n == 0)
return 1;
if(n % 2 == 0) {
long root = mpow(x, n / 2);
return root * root % mod;
}else {
return x * mpow(x, n - 1) % mod;
}
}
static long mcomb(long a, long b) {
if(b > a - b)
return mcomb(a, a - b);
long m = 1;
long d = 1;
long i;
for(i = 0; i < b; i++) {
m *= (a - i);
m %= mod;
d *= (i + 1);
d %= mod;
}
long ans = m * mpow(d, mod - 2) % mod;
return ans;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
} | Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 3bc063225d4f4cc145bfd76a707fd52b | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.util.Scanner;
public class anton_and_classes_785B{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int first_temp, second_temp;
int n = in.nextInt();
int chs_first_max, chs_second_min;
chs_first_max = Integer.MIN_VALUE;
chs_second_min = Integer.MAX_VALUE;
while(n > 0){
first_temp = in.nextInt();
second_temp = in.nextInt();
chs_first_max = Math.max(chs_first_max, first_temp);
chs_second_min = Math.min(chs_second_min, second_temp);
n--;
}
int m = in.nextInt();
int prog_first_max, prog_second_min;
prog_first_max = Integer.MIN_VALUE;
prog_second_min = Integer.MAX_VALUE;
while(m > 0){
first_temp = in.nextInt();
second_temp = in.nextInt();
prog_first_max = Math.max(prog_first_max, first_temp);
prog_second_min = Math.min(prog_second_min, second_temp);
m--;
}
int gap = Math.max(prog_first_max- chs_second_min,
chs_first_max-prog_second_min);
System.out.println( gap>0 ? gap : 0 );
}
} | Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 3a05e65fa83696b368708bea604f8cff | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.util.*;
import static java.lang.Math.*;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.math.BigInteger;
public class Main
{
static int mod = 1000000007;
static int MOD = 1000000007;
static final long M = (int)1e9+7;
static class Pair implements Comparable<Pair>
{
int a, b;
public Pair(int aa, int bb)
{
a = aa; b = bb;
}
public int compareTo(Pair p)
{
if(a == p.a) return b - p.b;
return a - p.a;
}
}
/*
* IO FOR 2D GRID IN JAVA
* char[][] arr = new char[n][m]; //grid in Q.
for(int i = 0;i<n;i++)
{
char[] nowLine = sc.next().toCharArray();
for(int j = 0;j<m;j++)
{
arr[i][j] = nowLine[i];
}
}
* */
public static void main(String[] args) throws IOException
{
Reader sc = new Reader();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int maxLeft = 0, minRight = MOD;
int res = 0;
while(n-- > 0)
{
int l = sc.nextInt(), r = sc.nextInt();
minRight = min(minRight,r);
maxLeft = max(maxLeft,l);
}
n = sc.nextInt();
while(n-- > 0)
{
int l = sc.nextInt(), r = sc.nextInt();
res = max(res,l - minRight);
res = max(res,maxLeft - r);
}
System.out.println(res);
out.close();
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
int[] readArray(int n) throws IOException {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
public BigInteger nextBigInteger() {
// TODO Auto-generated method stub
return null;
}
}
public static boolean isPrime(int n) {
if(n == 1)
{
return false;
}
for(int i = 2;i*i<=n;i++)
{
if(n%i == 0)
{
return false;
}
}
return true;
}
public static ArrayList<Integer> sieveList(int n)
{
ArrayList<Integer> list = new ArrayList<>();
boolean prime[]=new boolean[n+2];
for(int i=0;i<(n+1);i++)
{
prime[i]=true;
}
for(int i=2;i*i<=(n+1);i++)
{
if(prime[i]==true)
for(int p=i*2;p<=(n+1);p+=i)
prime[p]=false;
}
for(int i=2;i<=(n+1);i++)
{
if(prime[i]==true)
list.add(i);
}
return list;
}
public static int gcd(int a, int b)
{
if(b == 0)
return a;
else
return gcd(b,a%b);
}
public static long LongGCD(long a, long b)
{
if(b == 0)
return a;
else
return LongGCD(b,a%b);
}
public static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
public static int phi(int n) //euler totient function
{
int result = 1;
for (int i = 2; i < n; i++)
if (gcd(i, n) == 1)
result++;
return result;
}
public static int[] computePrefix(int arr[], int n)
{
int[] prefix = new int[n];
prefix[0] = arr[0];
for(int i = 1;i<n;i++)
{
prefix[i] = prefix[i-1]+arr[i];
}
return prefix;
}
public static int fastPow(int x, int n) //include mod at each step if asked and in args of fn too
{
if(n == 0)
return 1;
else if(n%2 == 0)
return fastPow(x*x,n/2);
else
return x*fastPow(x*x,(n-1)/2);
}
static int LowerBound(int a[], int x) {
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int UpperBound(int a[], int x) {
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static int power(int x, int y, int p)
{
int res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
//Fermat's little theorem for nCr % p.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
if (r == 0)
return 1;
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
public static void Sort(int[] a) {
List<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
//Collections.reverse(l); //Use to Sort decreasingly
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
}
| Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 9e11a55c6840b8858beadecc7bc69d27 | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | /* package codechef; // don't place package name! */
import java.math.BigInteger;
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 Solution
{
// Complete the maximumSum function below.
public static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
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);
}
}
static boolean prime(long a){
if(a==2||a==3)
return true;
if((a-1)%6==0)
return true;
if((a+1)%6==0)
return true;
return false;
}
public static long gcd(long a,long b){
if(b==0)
return a;
long r=a%b;
return gcd(b,r);
}
static long lcm(long a, long b)
{
return (a*b)/gcd(a, b);
}
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
}
public ListNode insert(ListNode node,int ele){
if(node==null||node.val>ele){
ListNode head=new ListNode();
head.val=ele;
head.next=node;
return head;
}
int p=node.val;
ListNode temp=insert(node.next,ele);
ListNode head=new ListNode();
head.val=p;
head.next=temp;
return head;
}
public ListNode sortList(ListNode head) {
if(head==null)
return null;
if(head.next==null)
return head;
int a=head.val;
head=head.next;
head=sortList(head);
return insert(head,a);
}
// private static final FastReader scanner = new FastReader();
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader scanner = new InputReader(inputStream);
PrintWriter w = new PrintWriter(outputStream);
int n=scanner.nextInt();
int minr=Integer.MAX_VALUE;
int arr[][]=new int[n][2];
for(int i=0;i<n;i++){
arr[i][0]=scanner.nextInt();
arr[i][1]=scanner.nextInt();
minr=Math.min(minr,arr[i][1]);
}
int min2r=Integer.MAX_VALUE;
n=scanner.nextInt();
int brr[][]=new int[n][2];
for(int j=0;j<n;j++){
brr[j][0]=scanner.nextInt();
brr[j][1]=scanner.nextInt();
min2r=Math.min(min2r,brr[j][1]);
}
int maxa=0,maxb=0;
for(int i=0;i<arr.length;i++){
if(arr[i][0]>=min2r)
maxa=Math.max(maxa,arr[i][0]-min2r);
}
for(int i=0;i<brr.length;i++){
if(brr[i][0]>=minr)
maxb=Math.max(maxb,brr[i][0]-minr);
}
w.print(Math.max(maxa,maxb));
w.close();
}
} | Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 354148e2cf9cdd7a196aa5a283c1062d | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) {
HashMap <String,Integer> map = new HashMap<String,Integer>();
int maxValue = Integer.MIN_VALUE;
int minValue = Integer.MAX_VALUE;
int maxValue2 = Integer.MIN_VALUE;
int minValue2 = Integer.MAX_VALUE;
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int i =0; i<a;i++) {
maxValue = Math.max(sc.nextInt(), maxValue);
minValue = Math.min(sc.nextInt(), minValue);
}
int b = sc.nextInt();
for (int j =0; j<b;j++) {
maxValue2 = Math.max(sc.nextInt(), maxValue2);
minValue2 = Math.min(sc.nextInt(), minValue2);
}
System.out.print(Math.max(0,Math.max(maxValue-minValue2,maxValue2-minValue)));
}
}
| Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 2b33fd7d864504fab45567f40cfdc543 | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) {
HashMap <String,Integer> map = new HashMap<String,Integer>();
int maxValue = 0;
int minValue = 1000000001;
int maxStep = 0;
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int i =0; i<a;i++) {
sc.nextLine();
maxValue = Math.max(sc.nextInt(), maxValue);
minValue = Math.min(sc.nextInt(), minValue);
}
sc.nextLine();
int b = sc.nextInt();
for (int j =0; j<b;j++) {
sc.nextLine();
maxStep = Math.max(sc.nextInt() - minValue, maxStep);
maxStep = Math.max(maxValue - sc.nextInt(), maxStep);
}
System.out.print(maxStep);
}
}
| Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | dcb25ed42f586f5e6717754cff09c31b | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes |
/**
* @author egaeus
* @mail sebegaeusprogram@gmail.com
* @veredict Not sended
* @url <https://codeforces.com/problemset/problem/>
* @category ?
* @date 5/06/2020
**/
import java.io.*;
import java.util.*;
import static java.lang.Integer.*;
import static java.lang.Math.*;
public class CF785B {
public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (String ln; (ln = in.readLine()) != null && !ln.equals(""); ) {
StringTokenizer st = new StringTokenizer(ln);
int N = parseInt(st.nextToken());
int[][] arr = new int[N][];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(in.readLine());
arr[i] = new int[]{parseInt(st.nextToken()), parseInt(st.nextToken())};
}
int M = parseInt(in.readLine());
int[][] arr1 = new int[M][];
for (int i = 0; i < M; i++) {
st = new StringTokenizer(in.readLine());
arr1[i] = new int[]{parseInt(st.nextToken()), parseInt(st.nextToken())};
}
System.out.println(Math.max(f(arr, arr1), f(arr1, arr)));
}
}
static int f(int[][] arr, int[][] arr1) {
int maxT = 0;
for(int i=0;i<arr1.length;i++)
maxT = Math.max(maxT, arr1[i][0]);
int max = 0;
for (int i = 0; i < arr.length; i++)
max = Math.max(max, maxT - arr[i][1]);
return max;
}
}
| Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | d8abcb34441b29a37c9ce64abae2e345 | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) throws IOException{
FastScanner sc = new FastScanner();
// int yo = sc.nextInt();
// while(yo-->0) {
// }
int n = sc.nextInt();
List<Pair> list1 = new ArrayList<>();
int min1 = Integer.MAX_VALUE;
int max1 = Integer.MIN_VALUE;
for(int i = 0; i < n; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
list1.add(new Pair(a,b));
min1 = Math.min(min1, b);
max1 = Math.max(max1, a);
}
int m = sc.nextInt();
List<Pair> list2 = new ArrayList<>();
int max2 = Integer.MIN_VALUE;
int min2 = Integer.MAX_VALUE;
for(int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
list2.add(new Pair(a,b));
max2 = Math.max(max2, a);
min2 = Math.min(min2, b);
}
// System.out.println(max + " " + min);
int a = Math.max(max1-min2, max2-min1);
System.out.println( a <= 0 ? 0 : a );
}
static class Pair{
int start;
int end;
public Pair(int start, int y) {
this.start = start;
this.end = end;
}
}
static int mod = 1000000007;
static long pow(int a, int b) {
if(b == 0) {
return 1;
}
if(b == 1) {
return a;
}
if(b%2 == 0) {
long ans = pow(a,b/2);
return ans*ans;
}
else {
long ans = pow(a,(b-1)/2);
return a * ans * ans;
}
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static int gcd(int a, int b) {
return a%b == 0 ? b : gcd(b,a%b);
}
static boolean[] sieve(int n) {
boolean isPrime[] = new boolean[n+1];
for(int i = 2; i <= n; i++) {
if(isPrime[i]) continue;
for(int j = 2*i; j <= n; j+=i) {
isPrime[j] = true;
}
}
return isPrime;
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
// sc.nextLine()
}
| Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | fc8430ae86250b19eb7255edef50b655 | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import com.sun.jdi.ArrayReference;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
FastScanner fs = new FastScanner();
int n = fs.nextInt();
int l1 = 2000000000;
int r1 = 0;
int l2 = 2000000000;
int r2 = 0;
for (int i = 0; i<n; i++) {
int a = fs.nextInt(), b = fs.nextInt();
r2 = Math.max(r2, a);
l1 = Math.min(b, l1);
}
int m = fs.nextInt();
for (int i = 0; i<m; i++) {
int a = fs.nextInt(), b = fs.nextInt();
r1 = Math.max(a,r1);
l2 = Math.min(b, l2);
}
System.out.println(Math.max(Math.max(r1-l1, r2-l2), 0));
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | ca470e2621d96f016b8b9b8fc04ef4d4 | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
//Mann Shah [ DAIICT ].
public class Main {
static long mod = (long) (1e9+7);
static InputReader in;
static PrintWriter out;
static Debugger deb;
public static void main(String args[] ) throws NumberFormatException, IOException {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
deb = new Debugger();
int n = in.nextInt();
Pair[] a1 = new Pair[n];
int min1= Integer.MAX_VALUE,max1 = 0;
for(int i=0;i<n;i++) {
a1[i] = new Pair(in.nextInt(),in.nextInt());
max1 = Math.max(max1, a1[i].l);
min1 = Math.min(min1, a1[i].r);
}
int m = in.nextInt();
int min2= Integer.MAX_VALUE,max2 = 0;
Pair[] a2 = new Pair[m];
for(int i=0;i<m;i++) {
a2[i] = new Pair(in.nextInt(),in.nextInt());
max2 = Math.max(max2, a2[i].l);
min2 = Math.min(min2, a2[i].r);
}
int ans = Math.max(max2 - min1, max1 - min2);
out.println(ans<0 ? 0 : ans);
out.close();
}
/* TC space
*/
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream){
this.stream = stream;
}
public int snext(){
if (snumChars == -1) throw new InputMismatchException();
if (curChar >= snumChars){
curChar = 0;
try{
snumChars = stream.read(buf);
} catch (IOException e){
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt(){
int c = snext();
while (isSpaceChar(c)){
c = snext();
}
int sgn = 1;
if (c == '-'){
sgn = -1;
c = snext();
}
int res = 0;
do{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public ArrayList<Integer> nextArrayList(int n){
ArrayList<Integer> x = new ArrayList<Integer>();
for(int i=0;i<n;i++) {
int v = in.nextInt();
x.add(v);
}
return x;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(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;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
static class Debugger{
public void n(int x) {
out.println(x);
}
public void a(int[] a) {
StringBuilder sb = new StringBuilder();
for(int i=0;i<a.length;i++) {
sb.append(a[i]+" ");
}
out.println(sb.toString());
}
}
}
class Pair {
int l;
int r;
public Pair(int l,int r) {
this.l = l;
this.r = r;
}
}
| Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 5edecd63d4bc11c82858b30cb6b02eeb | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
// File file = new File("input.txt");
// Scanner in = new Scanner(file);
// PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
FastReader in = new FastReader();
int n = in.nextInt();
int[][] chess = new int[n][2];
int a = Integer.MIN_VALUE, a1 = Integer.MIN_VALUE, b = Integer.MAX_VALUE, b1 = Integer.MAX_VALUE;
for(int i = 0; i<n; i++) {
chess[i][0] = in.nextInt();
chess[i][1] = in.nextInt();
a = Math.max(a, chess[i][0]);
b = Math.min(b, chess[i][1]);
}
int m = in.nextInt();
int[][] coding = new int[m][2];
for(int i = 0; i<m; i++) {
coding[i][0] = in.nextInt();
coding[i][1] = in.nextInt();
a1 = Math.max(a1, coding[i][0]);
b1 = Math.min(b1, coding[i][1]);
}
long rest = 0;
if(b1<a) {
rest = Math.max(rest, a-b1);
}
if(b<a1) {
rest = Math.max(rest, a1-b);
}
System.out.println(rest);
}
private static int gcd(int a, int b) {
if(b==0) return a;
return gcd(b, a%b);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 85b63913395935e956ff397189a42c5e | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.util.*;
import java.lang.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[][]=new int[n][2];
int mina=Integer.MAX_VALUE,maxa=0,minb=Integer.MAX_VALUE,maxb=0;
for(int i=0;i<n;i++){
a[i][0]=sc.nextInt();a[i][1]=sc.nextInt();
mina=Math.min(mina,a[i][1]);
maxa=Math.max(maxa,a[i][0]);
}
int m=sc.nextInt();
int b[][]=new int[m][2];
for(int i=0;i<m;i++){
b[i][0]=sc.nextInt();b[i][1]=sc.nextInt();
maxb=Math.max(maxb,b[i][0]);
minb=Math.min(minb,b[i][1]);
}
int ans=Math.max(0,Math.max(maxb-mina,maxa-minb));
System.out.println(ans);
}
} | Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 5060eef7cb32e84516e3f59e4b4e151b | train_003.jsonl | 1489590300 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number! | 256 megabytes | import java.io.*;
import java.util.*;
public class d2prac implements Runnable
{
private boolean console=false;
public void solve()
{
int i;
int n=in.ni();
Integer cs[]=new Integer[n];
Integer ce[]=new Integer[n];
for(i=0;i<n;i++)
{
cs[i]=in.ni(); ce[i]=in.ni();
}
int m=in.ni();
Integer ps[]=new Integer[m];
Integer pe[]=new Integer[m];
for(i=0;i<m;i++)
{
ps[i]= in.ni();
pe[i]=in.ni();
}
Arrays.sort(cs); Arrays.sort(ce);
Arrays.sort(pe); Arrays.sort(ps);
int ans=Math.max(0,Math.max(cs[n-1]-pe[0] ,ps[m-1]-ce[0]));
out.println(ans);
}
@Override
public void run() {
try { init(); }
catch (FileNotFoundException e) { e.printStackTrace(); }
int t= 1;
while (t-->0) {
solve();
out.flush(); }
}
private FastInput in; private PrintWriter out;
public static void main(String[] args) throws Exception { new d2prac().run(); }
private void init() throws FileNotFoundException {
InputStream inputStream = System.in; OutputStream outputStream = System.out;
try { if (!console && System.getProperty("user.name").equals("sachan")) {
outputStream = new FileOutputStream("/home/sachan/Desktop/output.txt");
inputStream = new FileInputStream("/home/sachan/Desktop/input.txt"); }
} catch (Exception ignored) { }
out = new PrintWriter(outputStream); in = new FastInput(inputStream);
}
static class FastInput { InputStream obj;
public FastInput(InputStream obj) { this.obj = obj; }
byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0;
int readByte() { if (lenbuffer == -1) throw new InputMismatchException();
if (ptrbuffer >= lenbuffer) { ptrbuffer = 0;
try { lenbuffer = obj.read(inbuffer); }
catch (IOException e) { throw new InputMismatchException(); } }
if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; }
String ns() { int b = skip();StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { sb.appendCodePoint(b);b = readByte(); }return sb.toString();}
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(); }}
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 * 10L + (b - '0'); } else {
return minus ? -num : num; }b = readByte(); } }
boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); }
int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; }
float nf() {return Float.parseFloat(ns());}
double nd() {return Double.parseDouble(ns());}
char nc() {return (char) skip();}
}
}
| Java | ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"] | 4 seconds | ["3", "0"] | NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Java 11 | standard input | [
"sortings",
"greedy"
] | 4849a1f65afe69aad12c010302465ccd | The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes. | 1,100 | Output one integer — the maximal possible distance between time periods. | standard output | |
PASSED | 1e4940a940d6ff43754a6edcac61613a | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes | import java.util.*;
public class LeastRoundWay {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int [][] board2 = new int[n][n];
boolean [][] prev2 = new boolean[n][n];
int [][] board5 = new int[n][n];
boolean [][] prev5 = new boolean[n][n];
boolean haveZero = false;
int zX = 0;
int zY = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int value = scan.nextInt();
int fac5 = numFactors(value, 5);
int fac2 = numFactors(value, 2);
int above2 = Integer.MAX_VALUE;
int above5 = Integer.MAX_VALUE;
if(value == 0) {
haveZero = true;
zY = i;
zX = j;
}
if(i > 0) {
// Not along top row.
above2 = board2[i-1][j];
above5 = board5[i-1][j];
}
int left2 = Integer.MAX_VALUE;
int left5 = Integer.MAX_VALUE;
if(j > 0) {
// Not along leftmost column.
left2 = board2[i][j-1];
left5 = board5[i][j-1];
}
if(i == 0 && j == 0) {
board2[i][j] = fac2;
board5[i][j] = fac5;
} else {
board2[i][j] = Math.min(above2, left2) + fac2;
prev2[i][j] = (left2 > above2);
board5[i][j] = Math.min(above5, left5) + fac5;
prev5[i][j] = (left5 > above5);
}
}
}
int min = Math.min(board2[n-1][n-1], board5[n-1][n-1]);
boolean picked2 = (min == board2[n-1][n-1]);
if(haveZero && min > 1) {
System.out.println(1);
for(int i = 0; i < zX; i++) {
System.out.print('R');
}
for(int i = 0; i < zY; i++) {
System.out.print('D');
}
for(int i = zX + 1; i < n; i++) {
System.out.print('R');
}
for(int i = zY + 1; i < n; i++) {
System.out.print('D');
}
} else {
char [] path = new char[2 * (n - 1)];
System.out.println(min);
int x = n - 1;
int y = n - 1;
boolean dir = false;
for(int i = 2 * n - 3; i >= 0; i--) {
//System.out.println(x + " . " + y);
if(picked2) {
dir = prev2[x][y];
} else {
dir = prev5[x][y];
}
if(dir) {
path[i] = 'D';
x--;
} else {
path[i] = 'R';
y--;
}
}
for(char c : path) {
if(c == 'D' || c == 'R') {
System.out.print(c);
}
}
}
System.out.println();
}
private static int numFactors(int num, int divisor) {
int factors = 0;
while(num > 0 && num % divisor == 0) {
factors++;
num /= divisor;
}
return factors;
}
} | Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | 9f847c9492285542725c6543e16b2f79 | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes |
import java.io.*;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringTokenizer;
/**
* CodeForces 2B. The least round way
* Created by Darren on 14-9-3.
*/
public class Main {
Reader in = new Reader(System.in);
PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
new Main().run();
}
int n;
int[][] matrixOf2, matrixOf5;
int[][] dp2, dp5;
void run() throws IOException {
n = in.nextInt();
matrixOf2 = new int[n][n];
matrixOf5 = new int[n][n];
dp2 = new int[n][n];
dp5 = new int[n][n];
int zerox = -1, zeroy = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int value = in.nextInt();
if (value == 0) {
matrixOf2[i][j] = matrixOf5[i][j] = 1;
zerox = i;
zeroy = j;
} else {
int count = 0;
while (value % 2 == 0) {
count++;
value /= 2;
}
matrixOf2[i][j] = count;
count = 0;
while (value % 5 == 0) {
count++;
value /= 5;
}
matrixOf5[i][j] = count;
}
}
}
runDP(matrixOf2, dp2);
runDP(matrixOf5, dp5);
if (zerox < 0 || Math.min(dp2[n-1][n-1], dp5[n-1][n-1]) == 0) {
if (dp2[n-1][n-1] < dp5[n-1][n-1])
output(matrixOf2, dp2);
else
output(matrixOf5, dp5);
} else {
out.println(1);
for (int i = 0; i < zerox; i++)
out.print('D');
for (int j = 0; j < zeroy; j++)
out.print('R');
for (int i = zerox; i < n-1; i++)
out.print('D');
for (int j = zeroy; j < n-1; j++)
out.print('R');
out.println();
}
out.flush();
}
void runDP(int[][] matrix, int[][] dp) {
dp[0][0] = matrix[0][0];
for (int j = 1; j < n; j++)
dp[0][j] = dp[0][j-1] + matrix[0][j];
for (int i = 1; i < n; i++)
dp[i][0] = dp[i-1][0] + matrix[i][0];
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++)
dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + matrix[i][j];
}
}
void output(int[][] matrix, int[][] dp) {
out.println(dp[n-1][n-1]);
Deque<Character> stack = new ArrayDeque<Character>();
int i = n-1, j = n-1;
while (i != 0 || j != 0) {
if (i == 0) {
stack.push('R');
j--;
} else if (j == 0) {
stack.push('D');
i--;
} else {
if (dp[i][j]-matrix[i][j] == dp[i-1][j]) {
stack.push('D');
i--;
} else {
stack.push('R');
j--;
}
}
}
while (!stack.isEmpty()) {
out.print(stack.pop());
}
out.println();
}
void solve() throws IOException {
}
static class Reader {
BufferedReader reader;
StringTokenizer tokenizer;
public Reader(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/** get next word */
String nextToken() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer( reader.readLine() );
}
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt( nextToken() );
}
long nextLong() throws IOException {
return Long.parseLong( nextToken() );
}
double nextDouble() throws IOException {
return Double.parseDouble( nextToken() );
}
}
}
| Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | dccf208161a38f47ccde8e659c0241c8 | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class TheLeastRoundWay {
static int [][] memo;
static int [][] twos;
static int [][] fives;
static int [][] memo1;
static int [][] memo2;
static String [][] way;
static String [][] way1;
static String [][] way2;
static int n;
static int counter = 0;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader rdr = new BufferedReader (new InputStreamReader(System.in));
n = Integer.parseInt(rdr.readLine());
memo = new int [n + 1][n + 1];
twos = new int [n + 1][n + 1];
fives = new int [n + 1][n + 1];
memo1 = new int [n + 1][n + 1];
memo2 = new int [n + 1][n + 1];
way = new String [n + 1][n + 1];
way1 = new String [n + 1][n + 1];
way2 = new String [n + 1][n + 1];
for(int i = 0; i < n + 1; i++) {
Arrays.fill(memo1[i],-1);
Arrays.fill(memo2[i],-1);
Arrays.fill(way1[i],"A");
Arrays.fill(way2[i],"A");
}
int posX = -1; int posY = -1;
for(int i = 0; i < n; i++) {
String [] line = rdr.readLine().split(" ");
for(int j = 0; j < n; j++) {
int x = Integer.parseInt(line[j]);
if(x == 0) {
posX = i;
posY = j;
continue;
}
while ((x&1) == 0) {
twos[i][j]++;
x >>=1;
}
while(x%5 == 0) {
fives[i][j]++;
x /=5;
}
}
}
memo = memo1;
way = way1;
int minTwo = DP(0,0,twos);
memo = memo2;
way = way2;
int minFive = DP(0,0,fives);
int Min = Math.min(minTwo,minFive);
if(Min > 1 && posX != -1) {
System.out.println(1);
for(int i = 0; i < posX;i++) System.out.print("D");
for(int j = 0; j < posY;j++) System.out.print("R");
for(int i = posX + 1; i < n;i++) System.out.print("D");
for(int i = posY + 1; i < n;i++) System.out.print("R");
return;
}
if(minTwo < minFive) {
System.out.println(minTwo);
int i = 0; int j = 0; char c = ' '; boolean found = false;
for(i = 0; i < n && !found; i++)
for(j = 0; j < n; j++) {
if(!way1[i][j].equals("A")) {
c = way1[i][j].charAt(0);
System.out.print(way1[i][j]);
found = true;
break;
}
}
i--;
while(i != n - 1 || j != n - 1) {
if(c == 'R') {
j++;
c = way1[i][j].charAt(0);
if(way1[i][j] != "A")
System.out.print(c);
}
else if(c == 'D'){
i++;
c = way1[i][j].charAt(0);
if(way1[i][j] != "A")
System.out.print(c);
}
}
return;
}
System.out.println(minFive);
int i = 0; int j = 0; char c = ' '; boolean found = false;
for(i = 0; i < n && !found; i++)
for(j = 0; j < n; j++) {
if(!way2[i][j].equals("A")) {
c = way2[i][j].charAt(0);
System.out.print(way2[i][j]);
found = true;
break;
}
}
i--;
while(i != n - 1 || j != n - 1) {
if(c == 'R') {
j++;
c = way2[i][j].charAt(0);
if(way2[i][j] != "A")
System.out.print(c);
}
else if(c == 'D'){
i++;
c = way2[i][j].charAt(0);
if(way2[i][j] != "A")
System.out.print(c);
}
}
}
public static int DP (int i , int j , int [][] B) {
if(i >= n || j >= n)
return 1000000001;
if(i == n - 1 && j == n - 1)
return B[i][j];
if(memo[i][j] != -1) return memo[i][j];
int result = B[i][j] + Math.min(DP(i + 1 , j , B) , DP(i , j + 1, B));
if(DP(i + 1 , j , B) < DP(i , j + 1, B))
way[i][j] = "D";
else
way[i][j] = "R";
return memo[i][j] = result;
}
}
| Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | ebaaa7a47fea30e2f33596887271e9bb | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class R002B {
static int n;
public static void main(String[] args) {
FastScanner in=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
n=in.nextInt();
int[][] dp2=new int[n][n];
int[][] dp5=new int[n][n];
boolean foundzero=false;
int zerox=0,zeroy=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
int a=in.nextInt();
if(a==0){
foundzero=true;
zerox=i;
zeroy=j;
}else{
while(a%5==0){
dp5[i][j]++;
a/=5;
}
while(a%2==0){
dp2[i][j]++;
a/=2;
}
}
}
}
search(dp2,2);
search(dp5,5);
int best=Math.min(foundzero?1:Integer.MAX_VALUE,Math.min(dp2[n-1][n-1],dp5[n-1][n-1]));
out.println(best);
if(best==1&&foundzero){
for(int i=0;i<zerox;i++)
out.print("D");
for(int j=0;j<zeroy;j++)
out.print("R");
for(int i=0;i<n-zerox-1;i++)
out.print("D");
for(int j=0;j<n-zeroy-1;j++)
out.print("R");
out.println();
}else if(best==dp5[n-1][n-1]){
out.println(printPath(n-1,n-1,dp5));
}else{
out.println(printPath(n-1,n-1,dp2));
}
out.flush();
}
static StringBuffer printPath(int i,int j,int[][] dp){
StringBuffer ret=new StringBuffer("");
if(i==0){
for(int m=0;m<j;m++)
ret.append("R");
}else if(j==0){
for(int m=0;m<i;m++)
ret.append("D");
}else{
if(dp[i][j-1]<=dp[i-1][j]){
ret.append(printPath(i,j-1,dp));
ret.append("R");
}else{
ret.append(printPath(i-1,j,dp));
ret.append("D");
}
}
return ret;
}
static void search(int[][] dp,int div){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==0&&j==0)
continue;
else if(i==0)
dp[i][j]+=dp[i][j-1];
else if(j==0)
dp[i][j]+=dp[i-1][j];
else
dp[i][j]+=Math.min(dp[i][j-1],dp[i-1][j]);
}
}
}
static class FastScanner{
BufferedReader br;
StringTokenizer st;
public FastScanner(){br=new BufferedReader(new InputStreamReader(System.in));}
String nextToken(){
while(st==null||!st.hasMoreElements())
try{st=new StringTokenizer(br.readLine());}catch(Exception e){}
return st.nextToken();
}
int nextInt(){return Integer.parseInt(nextToken());}
long nextLong(){return Long.parseLong(nextToken());}
double nextDouble(){return Double.parseDouble(nextToken());}
}
} | Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | b37086df267f67ba4fcfa2971508784c | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes | //package hw5;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class LeastRound {
public static void solve(int n, Scanner readInput) {
int[][] twos = new int[n][n];
int[][] fives = new int[n][n];
int[][] twosTable = new int[n][n];
int[][] fivesTable = new int[n][n];
int x = -1;
int y = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int num = readInput.nextInt();
if (num == 0) {
twos[i][j] = 1;
fives[i][j] = 1;
x = i;
y = j;
}
else {
twos[i][j] = count(num, 2);
fives[i][j] = count(num, 5);
}
}
}
makeTable(twos, twosTable, n);
makeTable(fives, fivesTable, n);
if (x < 0 || Math.min(twosTable[n-1][n-1], fivesTable[n-1][n-1]) == 0) {
if (twosTable[n-1][n-1] < fivesTable[n-1][n-1]) printSolution(twos, twosTable, n);
else printSolution(fives, fivesTable, n);
}
else {
String outPut = "";
for (int i = 0; i < x; i++) outPut += 'D';
for (int j = 0; j < y; j++) outPut += 'R';
for (int i = x; i < n-1; i++) outPut += 'D';
for (int j = y; j < n-1; j++) outPut += 'R';
System.out.println(1);
System.out.println(outPut);
} }
static void makeTable(int[][] table, int[][] dynamic, int n) {
dynamic[0][0] = table[0][0];
for (int i = 1; i < n; i++) dynamic[0][i] = dynamic[0][i-1] + table[0][i];
for (int i = 1; i < n; i++) dynamic[i][0] = dynamic[i-1][0] + table[i][0];
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++) dynamic[i][j] = Math.min(dynamic[i-1][j], dynamic[i][j-1]) + table[i][j];
}
}
static void printSolution(int[][] table, int[][] dynamic, int n) {
System.out.println(dynamic[n-1][n-1]);
ArrayList<String> output = new ArrayList<String>();
int i = n-1;
int j = n-1;
while (i != 0 || j != 0) {
if (i == 0) {
output.add("R");
j--;
}
else if (j == 0) {
output.add("D");
i--;
}
else {
if (dynamic[i][j]-table[i][j] == dynamic[i-1][j]) {
output.add("D");
i--;
}
else {
output.add("R");
j--;
}
}
}
for(int k = output.size()-1; k >= 0; k--) System.out.print(output.get(k));
System.out.println();
}
public static int count(int num, int divisor) {
int count = 0;
while(num % divisor == 0) {
count++;
num /= divisor;
}
return count;
}
public static void main(String[] args) throws IOException {
Scanner readInput = new Scanner(System.in);
int n = readInput.nextInt();
solve(n, readInput);
}
} | Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | b85e98e84d9b1b47119ce1279e2c0b10 | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 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 Lokesh Khandelwal aka (codeKNIGHT | phantom11)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
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(),i,j;
int five[][]=new int[n][n],two[][]=new int[n][n],a[][]=new int[n][n];
char path[][]=new char[n][n];
boolean status=false;
char path1[][]=new char[n][n];
int row=0,col=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
int k=in.nextInt();
if(k==0)
{
status=true;
k=10;
row=i;
col=j;
}
a[i][j]=k;
}
two[0][0]=count(a[0][0],2);
five[0][0]=count(a[0][0],5);
for(i=1;i<n;i++)
{
two[0][i]=two[0][i-1]+count(a[0][i],2);
five[0][i]=five[0][i-1]+count(a[0][i],5);
two[i][0]=two[i-1][0]+count(a[i][0],2);
five[i][0]=five[i-1][0]+count(a[i][0],5);
path[i][0]='D';
path[0][i]='R';
path1[i][0]='D';
path1[0][i]='R';
}
for (i=1;i<n;i++)
{
for(j=1;j<n;j++)
{
two[i][j]=count(a[i][j],2);
if(two[i-1][j]<two[i][j-1])
{
two[i][j]+=two[i-1][j];
path[i][j]='D';
}
else
{
two[i][j]+=two[i][j-1];
path[i][j]='R';
}
five[i][j]=count(a[i][j],5);
if(five[i][j-1]<five[i-1][j])
{
five[i][j]+=five[i][j-1];
path1[i][j]='R';
}
else
{
five[i][j]+=five[i-1][j];
path1[i][j]='D';
}
}
}
//for(i=0;i<n;i++)
// for(j=0;j<n;j++)
// System.out.println(two[i][j]+" "+five[i][j]);
i=n-1;
j=n-1;
if(status)
{
if(Math.min(two[i][j],five[i][j])>=1)
{
out.println(1);
for(int p=0;p<row;p++)
out.print("D");
for(int p=0;p<n-1;p++)
out.print("R");
for(int p=row+1;p<n;p++)
out.print("D");
out.println();
return;
}
}
if(two[i][j]<=five[i][j])
{
out.println(two[i][j]);
out.println(printpath(path));
}
else
{
out.println(five[i][j]);
out.println(printpath(path1));
}
}
public String printpath(char a[][])
{
StringBuilder s=new StringBuilder("");
int i=a.length-1,j=a.length-1;
while (i>0||j>0)
{
s.append(a[i][j]);
if(a[i][j]=='R')
{
j-=1;
}
else i-=1;
}
s=s.reverse();
return s.toString();
}
public int count(int n,int digit)
{
int c=0;
while (n%digit==0)
{
c++;
n/=digit;
}
return c;
}
}
class InputReader
{
BufferedReader in;
StringTokenizer tokenizer=null;
public InputReader(InputStream inputStream)
{
in=new BufferedReader(new InputStreamReader(inputStream));
}
public String next()
{
try{
while (tokenizer==null||!tokenizer.hasMoreTokens())
{
tokenizer=new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
catch (IOException e)
{
return null;
}
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
| Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | 2944ff1038beaedd62b0f8336be66743 | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes | import java.util.Scanner;
public class Code_2B {
public static void main(String[] args) {
int INF = 100000000;
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] p5 = new int[n][n];
int[][] p2 = new int[n][n];
boolean[][] isZero = new boolean[n][n];
boolean haveZero = false;
int zeroI = -1;
int zeroJ = -1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int a = scan.nextInt();
if (a == 0) {
isZero[i][j] = true;
haveZero = true;
zeroI = i;
zeroJ = j;
p5[i][j] = INF;
p2[i][j] = INF;
} else {
while (a % 5 == 0) {
++p5[i][j];
a /= 5;
}
while (a % 2 == 0) {
++p2[i][j];
a /= 2;
}
}
}
}
onePath(n, p2);
onePath(n, p5);
int best = Math.min(haveZero ? 1 : INF, Math.min(p5[n-1][n-1], p2[n-1][n-1]));
System.out.println(best);
if (best == 1 && haveZero) {
for (int i = 0; i < zeroI; ++i)
System.out.print("D");
for (int j = 0; j < zeroJ; ++j)
System.out.print("R");
for (int i = 0; i < n - 1 - zeroI; ++i)
System.out.print("D");
for (int j = 0; j < n - 1 - zeroJ; ++j)
System.out.print("R");
} else if (best == p5[n-1][n-1]) {
printPath(n - 1, n - 1, p5);
} else {
printPath(n - 1, n - 1, p2);
}
}
private static void printPath(int i, int j, int[][] path) {
if (i == 0){
for(int m=0;m<j;m++)
System.out.print("R");
}else if(j == 0){
for(int m=0;m<i;m++)
System.out.print("D");
}else{
if (path[i][j-1]<=path[i-1][j]) {
printPath(i, j - 1, path);
System.out.print("R");
} else {
printPath(i - 1, j, path);
System.out.print("D");
}
}
}
private static void onePath(int n, int[][] p) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0)
continue;
if (i == 0) {
p[i][j] = p[i][j - 1] + p[i][j];
} else if (j == 0) {
p[i][j] = p[i - 1][j] + p[i][j];
} else {
p[i][j] = Math.min(p[i][j - 1], p[i - 1][j]) + p[i][j];
}
}
}
}
} | Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | 5bd2a14d6e19ad0dc36ee1d21f20a01b | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes | import java.io.DataInputStream;
import java.io.InputStream;
public class TheLeastWay {
public static void main (String args[]) throws Exception{
FS in = new FS(System.in);
int n=in.nextInt();
int a[][]=new int[n][2];
boolean paret[][][]= new boolean[n][n][2];
int v= Integer.MAX_VALUE/2;
for(int i=1;i<n;i++){
a[i][0]=a[i][1]=v;
}
int zi = -1;
for(int i=0;i<n;i++){
int x=in.nextInt();
int [] c=new int[2];
if(x==0) zi = i;
else{
while(x%10==0){c[0]++ ; c[1]++ ; x/=10;}
while(x%5==0){
c[0]++;
x/=5;
}
while((x&1)==0){
c[1]++;
x>>=1;
}
}
a[0][0]+=c[0];
a[0][1]+=c[1];
paret[i][0][0]=true;
paret[i][0][1]=true;
for(int j=1;j<n;j++){
x=in.nextInt();
c=new int[2];
if(x==0) zi = i;
else{
while(x%10==0){c[0]++ ; c[1]++ ; x/=10;}
while(x%5==0){
c[0]++;
x/=5;
}
while((x&1)==0){
c[1]++;
x>>=1;
}
}
for(int k = 0 ; k < 2 ; k++){
if(a[j][k]<a[j-1][k]){
a[j][k]+=c[k];
paret[i][j][k]=true;
}
else {
a[j][k]=a[j-1][k]+c[k];
}
}
}
}
StringBuffer s= new StringBuffer();
int z = 1;
if(a[n-1][0]<a[n-1][1])z=0;
if(a[n-1][z]>1 && zi!= -1){
System.out.println(1);
for(int i = 0 ; i < zi ; i++){
System.out.print("D");
}
for(int j = 0 ; j < n-1 ; j++){
System.out.print("R");
}
for(int i = zi ; i < n-1 ; i++){
System.out.print("D");
}
}
else{
System.out.println(a[n-1][z]);
int k=n-1;
int j=n-1;
for(int i=0;i<2*n-2;i++){
if(paret[k][j][z]){
k--;
s.append("D");
}
else{
s.append("R");
j--;
}
}
System.out.println(s.reverse());
}
}
}
class FS
{
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FS(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception
{
StringBuffer sb=new StringBuffer("");
byte c = read();
while (c <= ' ') c = read();
do
{
sb.append((char)c);
c=read();
}while(c>' ');
return sb.toString();
}
public char nextChar() throws Exception
{
byte c=read();
while(c<=' ') c= read();
return (char)c;
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
| Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | e5d5509a0f81fb895492df30a5fbba9e | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes | import java.io.DataInputStream;
import java.io.InputStream;
public class TheLeastWay {
public static void main (String args[]) throws Exception{
FS in = new FS(System.in);
Printer out = new Printer(System.out);
int n=in.nextInt();
int a[][]=new int[n][2];
boolean paret[][][]= new boolean[n][n][2];
int v= Integer.MAX_VALUE/2;
for(int i=1;i<n;i++){
a[i][0]=a[i][1]=v;
}
int zi = -1;
for(int i=0;i<n;i++){
int x=in.nextInt();
int [] c=new int[2];
if(x==0) zi = i;
else{
while(x%10==0){c[0]++ ; c[1]++ ; x/=10;}
while(x%5==0){
c[0]++;
x/=5;
}
while((x&1)==0){
c[1]++;
x>>=1;
}
}
a[0][0]+=c[0];
a[0][1]+=c[1];
paret[i][0][0]=true;
paret[i][0][1]=true;
for(int j=1;j<n;j++){
x=in.nextInt();
c=new int[2];
if(x==0) zi = i;
else{
while(x%10==0){c[0]++ ; c[1]++ ; x/=10;}
while(x%5==0){
c[0]++;
x/=5;
}
while((x&1)==0){
c[1]++;
x>>=1;
}
}
for(int k = 0 ; k < 2 ; k++){
if(a[j][k]<a[j-1][k]){
a[j][k]+=c[k];
paret[i][j][k]=true;
}
else {
a[j][k]=a[j-1][k]+c[k];
}
}
}
}
StringBuffer s= new StringBuffer();
int z = 1;
if(a[n-1][0]<a[n-1][1])z=0;
if(a[n-1][z]>1 && zi!= -1){
out.println(1);
for(int i = 0 ; i < zi ; i++){
out.print("D");
}
for(int j = 0 ; j < n-1 ; j++){
out.print("R");
}
for(int i = zi ; i < n-1 ; i++){
out.print("D");
}
}
else{
out.println(a[n-1][z]);
int k=n-1;
int j=n-1;
for(int i=0;i<2*n-2;i++){
if(paret[k][j][z]){
k--;
s.append("D");
}
else{
s.append("R");
j--;
}
}
out.println(s.reverse().toString());
}
out.close();
}
}
class FS
{
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FS(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception
{
StringBuffer sb=new StringBuffer("");
byte c = read();
while (c <= ' ') c = read();
do
{
sb.append((char)c);
c=read();
}while(c>' ');
return sb.toString();
}
public char nextChar() throws Exception
{
byte c=read();
while(c<=' ') c= read();
return (char)c;
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
class Printer
{
final private int BUFFER_SIZE = 1 << 16;
private java.io.DataOutputStream dout;
private byte[] buffer;
private int bufferPointer;
Printer(java.io.OutputStream out) throws Exception
{
dout = new java.io.DataOutputStream(out);
buffer = new byte[BUFFER_SIZE];
bufferPointer = 0;
}
public void println() throws Exception
{
write((byte) '\n');
}
// print int
public void println(int n) throws Exception
{
print(n);
println();
}
public void print(int n) throws Exception
{
if (n >= 0)
print(n, true);
else
{
write((byte) '-');
print(-n, true);
}
}
private void print(int n, boolean first) throws Exception
{
if (n == 0)
{
if (first)
write((byte) (n + '0'));
}
else
{
print(n / 10, false);
write((byte) ((n % 10) + '0'));
}
}
// print long
public void println(long n) throws Exception
{
print(n);
println();
}
public void print(long n) throws Exception
{
if (n >= 0)
print(n, true);
else
{
write((byte) '-');
print(-n, true);
}
}
private void print(long n, boolean first) throws Exception
{
if (n == 0)
{
if (first)
write((byte) (n + '0'));
}
else
{
print(n / 10, false);
write((byte) ((n % 10) + '0'));
}
}
// print double
public void println(double d) throws Exception
{
print(d);
println();
}
public void print(double d) throws Exception
{
print("double printing is not yet implemented!");
}
// print char
public void println(char c) throws Exception
{
print(c);
println();
}
public void print(char c) throws Exception
{
write((byte) c);
}
// print String
public void println(String s) throws Exception
{
print(s);
println();
}
public void print(String s) throws Exception
{
int len = s.length();
for (int i = 0; i < len; i++)
print(s.charAt(i));
}
public void print(char[] S) throws Exception
{
int len = S.length;
for (int i=0; i<len; ++i)
print(S[i]);
}
public void println(char[] S) throws Exception
{
print(S);
println();
}
public void close() throws Exception
{
flushBuffer();
}
public void flushBuffer() throws Exception
{
dout.write(buffer, 0, bufferPointer);
bufferPointer = 0;
}
private void write(byte b) throws Exception
{
buffer[bufferPointer++] = b;
if (bufferPointer == BUFFER_SIZE)
flushBuffer();
}
}
| Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | 1d7342e0559ae526a140e7168f443030 | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
//Input
//The first line contains an integer number n (2 <= n <= 1000), n is the size of the matrix.
//Then following n lines containing the matrix elements (non-negative integer numbers not exceeding 10^9).
//Output
//In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
public class leastroundway {
public static void main(String[] args) {
int INF = 100000000;
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
int[][] power5 = new int[N][N];
int[][] power2 = new int[N][N];
boolean[][] isZero = new boolean[N][N];
boolean haveZero = false;
int zeroI = -1;
int zeroJ = -1;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
int a = scan.nextInt();
if (a == 0) {
isZero[i][j] = true;
haveZero = true;
zeroI = i;
zeroJ = j;
power5[i][j] = INF;
power2[i][j] = INF;
} else {
while (a % 5 == 0) {
++power5[i][j];
a /= 5;
}
while (a % 2 == 0) {
++power2[i][j];
a /= 2;
}
}
}
}
findPath(N, power2);
findPath(N, power5);
int best = Math.min(haveZero ? 1 : INF, Math.min(power5[N-1][N-1], power2[N-1][N-1]));
System.out.println(best);
if (best == 1 && haveZero) {
for (int i = 0; i < zeroI; ++i)
System.out.print("D");
for (int j = 0; j < zeroJ; ++j)
System.out.print("R");
for (int i = 0; i < N - 1 - zeroI; ++i)
System.out.print("D");
for (int j = 0; j < N - 1 - zeroJ; ++j)
System.out.print("R");
} else if (best == power5[N-1][N-1]) {
printPath(N - 1, N - 1, power5);
} else {
printPath(N - 1, N - 1, power2);
}
}
private static void printPath(int i, int j, int[][] path) {
if (i == 0){
for(int m=0;m<j;m++)
System.out.print("R");
}else if(j == 0){
for(int m=0;m<i;m++)
System.out.print("D");
}else{
if (path[i][j-1]<=path[i-1][j]) {
printPath(i, j - 1, path);
System.out.print("R");
} else {
printPath(i - 1, j, path);
System.out.print("D");
}
}
}
private static void findPath(int n, int[][] p) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0)
continue;
if (i == 0) {
p[i][j] = p[i][j - 1] + p[i][j];
} else if (j == 0) {
p[i][j] = p[i - 1][j] + p[i][j];
} else {
p[i][j] = Math.min(p[i][j - 1], p[i - 1][j]) + p[i][j];
}
}
}
}
}
| Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | 9729fa34b58276eb8c0e93b74bb4b4ab | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class C2B {
static int n, twos[][], fives[][];
static int rowNull = -1, colNull = -1;
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
n = Integer.valueOf(in.readLine());
twos = new int[n][n];
fives = new int[n][n];
StringTokenizer st;
for (int i = 0; i < n; i++) {
st = new StringTokenizer(in.readLine());
for (int j = 0; j < n; j++) {
int elem = Integer.valueOf(st.nextToken());
if(elem == 0){
twos[i][j] = 2000000;
fives[i][j] = 2000000;
rowNull = i;
colNull = j;
continue;
}
while (elem % 2 == 0) {
twos[i][j]++;
elem /= 2;
}
while (elem % 5 == 0) {
fives[i][j]++;
elem /= 5;
}
}
}
int ansT[][] = new int[n][n], ansF[][] = new int[n][n];
for (int i = 0; i < n; i++) {
ansT[0][i] = (i != 0 ? ansT[0][i - 1] : 0) + twos[0][i];
ansF[0][i] = (i != 0 ? ansF[0][i - 1] : 0) + fives[0][i];
ansT[i][0] = (i != 0 ? ansT[i - 1][0] : 0) + twos[i][0];
ansF[i][0] = (i != 0 ? ansF[i - 1][0] : 0) + fives[i][0];
}
for (int i = 1; i < n; i++)
for (int j = 1; j < n; j++) {
if (ansT[i - 1][j] < ansT[i][j - 1])
ansT[i][j] = twos[i][j] + ansT[i - 1][j];
else
ansT[i][j] = twos[i][j] + ansT[i][j - 1];
if (ansF[i - 1][j] < ansF[i][j - 1])
ansF[i][j] = fives[i][j] + ansF[i - 1][j];
else
ansF[i][j] = fives[i][j] + ansF[i][j - 1];
}
if( rowNull != -1 && Math.min(ansF[n - 1][n - 1], ansT[n - 1][n - 1]) > 1){
System.out.println(1);
int i = 0, j = 0;
while(i < rowNull){
System.out.print("D");
i ++;
}
while(j < n - 1){
System.out.print("R");
j ++;
}
while(i < n - 1){
System.out.print("D");
i ++;
}
return;
}
out.write("" + Math.min(ansF[n - 1][n - 1], ansT[n - 1][n - 1]));
out.newLine();
int i = n - 1, j = i;
char ans[] = new char[2*(n-1)] ;
int schot = 2*(n-1) - 1;
if (ansF[n - 1][n - 1] > ansT[n - 1][n - 1]) {
while (!(i == 0 && j == 0)) {
if (i == 0) {
ans[schot -- ] = 'R';
j--;
} else if (j == 0) {
ans[schot -- ] = 'D';
i--;
} else if (ansT[i - 1][j] < ansT[i][j - 1]) {
ans[schot -- ] = 'D';
i--;
} else {
ans[schot -- ] = 'R';
j--;
}
}
} else {
while (!(i == 0 && j == 0)) {
if (i == 0) {
ans[schot -- ] = 'R';
j--;
} else if (j == 0) {
ans[schot -- ] = 'D';
i--;
} else if (ansF[i - 1][j] < ansF[i][j - 1]) {
ans[schot -- ] = 'D';
i--;
} else {
ans[schot -- ] = 'R';
j--;
}
}
}
out.write(ans);
out.close();
}
}
class Pair {
int two, five;
public Pair(int two, int five) {
this.two = two;
this.five = five;
}
}
| Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | 3366de4f9521058d39b13cbc98dd9c95 | train_003.jsonl | 1267117200 | There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. | 64 megabytes | import java.io.*;
import java.util.*;
public class Problem2BUsingDPRevised
{
static boolean DEBUG=false;
static long startTime=0,endTime=0,totalTime=0;
public static void main(String[] args) throws Exception
{
if(DEBUG) startTime = System.currentTimeMillis();
BufferedReader br;
if(DEBUG)
br = new BufferedReader(new FileReader(new File("data3.txt")));
else br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st;
st = getst(br);
//Scanner sc = new Scanner(System.in);
//Scanner sc = new Scanner(new File("data2.txt"));
int n=nextInt(st);
int[][] twos=new int[n][n];
int[][] fives=new int[n][n];
boolean found=false;
int foundX=0,foundY=0;
for(int i=0; i<n; i++)
{
st=getst(br);
for(int j=0; j<n; j++)
{
int r = nextInt(st);
if(r==0){
found=true;
foundX=i;
foundY=j;
}
while(r%2==0 && r>0)
{
twos[i][j]++;
r/=2;
}
while(r%5==0 && r>0)
{
fives[i][j]++;
r/=5;
}
}
}
best(twos);
best(fives);
int lastTwo=twos[n-1][n-1];
int lastFive=fives[n-1][n-1];
if(found && lastTwo>0 && lastFive>0)
{
pw.println(1);
int i=0;
int j=0;
for(; i<foundX; i++)
pw.print("D");
for(; j<foundY; j++)
pw.print("R");
for(; i<n-1; i++)
pw.print("D");
for(; j<n-1; j++)
pw.print("R");
}
else if(lastTwo<lastFive)
{
pw.println(lastTwo);
pw.println(calcPath(twos));
}
else
{
pw.println(lastFive);
pw.println(calcPath(fives));
}
if(DEBUG){
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;
pw.println("\n"+totalTime);
}
pw.close();
}
public static void best(int[][] arr)
{
for(int i=0; i<arr.length; i++)
{
for(int j=0; j<arr.length; j++)
{
if(i==0 && j==0)
continue;
int down=Integer.MAX_VALUE;
int right=Integer.MAX_VALUE;
String path="";
int best=0;
if(i>0)down=arr[i-1][j];
if(j>0)right=arr[i][j-1];
if(down<right){
best=down;
}
else{
best=right;
}
arr[i][j]+=best;
}
}
}
public static String calcPath(int[][] arr)
{
String retStr="";
int x=arr.length-1;
int y=arr.length-1;
while(x>0 || y>0)
{
if(x==0) {
retStr="R"+retStr;
y--;
}
else if(y==0) {
retStr="D"+retStr;
x--;
}
else{
if(arr[x-1][y]>arr[x][y-1])
{
retStr="R"+retStr;
y--;
}
else {
retStr="D"+retStr;
x--;
}
}
}
return retStr;
}
public static StringTokenizer getst(BufferedReader br) throws Exception{
return new StringTokenizer(br.readLine(), " ");
}
public static int nextInt(StringTokenizer st) throws Exception{
return Integer.parseInt(st.nextToken());
}
} | Java | ["3\n1 2 3\n4 5 6\n7 8 9"] | 2 seconds | ["0\nDDRR"] | null | Java 7 | standard input | [
"dp",
"math"
] | 13c58291ab9cf7ad1b8c466c3e36aacf | The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). | 2,000 | In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. | standard output | |
PASSED | 6608486b8687c43d945d51b846d1b06a | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.util.*;
import java.io.*;
public class NewYear {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter( System.out);
int alen = sc.nextInt();
int blen = sc.nextInt();
String[] a = new String[alen];
for(int i = 0; i<alen; i++)
a[i] = sc.next();
String[] b = new String[blen];
for(int i = 0; i<blen; i++)
b[i] = sc.next();
int t = sc.nextInt();
for(int i = 0; i<t; i++) {
int n = sc.nextInt()-1;
out.println(a[n%alen]+b[n%blen]);
}
sc.close();
out.close();
}
} | Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 1b75b6340b6a947aeadd16539e99c8c8 | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.io.*;
import java.util.*;
public class d2prac implements Runnable
{
private boolean console=false;
public void solve()
{
int i; int n=in.ni(); int m=in.ni(); String s[]=new String[n]; String t[]=new String[m];
for(i=0;i<n;i++)
s[i]=in.ns();
for(i=0;i<m;i++)
t[i]=in.ns();
int q=in.ni();
for(i=0;i<q;i++)
{
int v=in.ni();
int u=(v-1)%n; int d=(v-1)%m;
System.out.println(s[u]+t[d]);
}
}
@Override
public void run() {
try { init(); }
catch (FileNotFoundException e) { e.printStackTrace(); }
int t= 1;
while (t-->0) {
solve();
out.flush(); }
}
private FastInput in; private PrintWriter out;
public static void main(String[] args) throws Exception { new d2prac().run(); }
private void init() throws FileNotFoundException {
InputStream inputStream = System.in; OutputStream outputStream = System.out;
try { if (!console && System.getProperty("user.name").equals("sachan")) {
outputStream = new FileOutputStream("/home/sachan/Desktop/output.txt");
inputStream = new FileInputStream("/home/sachan/Desktop/input.txt"); }
} catch (Exception ignored) { }
out = new PrintWriter(outputStream); in = new FastInput(inputStream);
}
static class FastInput { InputStream obj;
public FastInput(InputStream obj) { this.obj = obj; }
byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0;
int readByte() { if (lenbuffer == -1) throw new InputMismatchException();
if (ptrbuffer >= lenbuffer) { ptrbuffer = 0;
try { lenbuffer = obj.read(inbuffer); }
catch (IOException e) { throw new InputMismatchException(); } }
if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; }
String ns() { int b = skip();StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { sb.appendCodePoint(b);b = readByte(); }return sb.toString();}
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(); }}
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 * 10L + (b - '0'); } else {
return minus ? -num : num; }b = readByte(); } }
boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); }
int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; }
float nf() {return Float.parseFloat(ns());}
double nd() {return Double.parseDouble(ns());}
char nc() {return (char) skip();}
}
} | Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | eb615478239800ff5398cb703058b148 | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int length_str1 = input.nextInt();
int length_str2 = input.nextInt();
String[] array1 = new String[length_str1];
String[] array2 = new String[length_str2];
for(int i = 0; i < length_str1; i++){
array1[i] = input.next();
}
for(int i = 0; i < length_str2; i++){
array2[i] = input.next();
}
int count = input.nextInt();
for(int i = 0; i < count; i++){
int temp = input.nextInt() - 1;
System.out.println(array1[temp % length_str1] + array2[temp % length_str2 ]);
}
}
}
| Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | a68febd77b38a7dd26243a30a2d6d1d4 | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jaynil
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
String x[] = new String[n];
String y[] = new String[m];
for (int i = 0; i < n; i++) x[i] = in.next();
for (int i = 0; i < m; i++) y[i] = in.next();
int q = in.nextInt();
while (q-- > 0) {
int a = in.nextInt() - 1;
out.println(x[a % n] + y[a % m]);
}
}
}
}
| Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 871120292d17a1d306976656f72b02bc | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jaynil
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
String x[] = new String[n];
String y[] = new String[m];
for (int i = 0; i < n; i++) x[i] = in.next();
for (int i = 0; i < m; i++) y[i] = in.next();
int q = in.nextInt();
while (q-- > 0) {
int a = in.nextInt() - 1;
out.println(x[a % n] + y[a % m]);
}
}
}
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 | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 9c7073d74c288bc2fb9aeab0d942a504 | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.util.Scanner;
public class x1284A {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int m=input.nextInt();
String[] s=new String[n];
String[] t=new String[m];
for(int i=0;i<n;i++){
s[i]=input.next();
}
for(int i=0;i<m;i++){
t[i]=input.next();
}
int q=input.nextInt();
for(int k=0;k<q;k++){
int year=input.nextInt();
System.out.println(s[(year-1)%n]+t[(year-1)%m]);
}
}
}
| Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 491364afb0e3d957f3478e00523e44db | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
FastScanner cin = new FastScanner(System.in);
int n = cin.nextInt();
int m = cin.nextInt();
String[] nStrings = cin.nextLine().split(" ");
String[] mStrings = cin.nextLine().split(" ");
int q = cin.nextInt();
for (int i = 0; i < q; i++) {
int y = cin.nextInt();
int nI = y % n > 0 ? y % n - 1 : n - 1;
int mI = y % m > 0 ? y % m - 1 : m - 1;
System.out.println(nStrings[nI] + mStrings[mI]);
}
}
static class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} | Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 564407e84871cbaddec4eb62a2724ac8 | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Scanner;
public class codeforces {
static Scanner stdin = new Scanner(System.in);
private int n, m, q;
private void solution() {
ArrayList<String>S = new ArrayList<String>();
ArrayList<String>T = new ArrayList<String>();
n = stdin.nextInt();
m = stdin.nextInt();
for (int i = 0; i < n; i++) {
S.add(stdin.next());
}
for (int i = 0; i < m; i++) {
T.add(stdin.next());
}
q = stdin.nextInt();
for (int i = 0; i < q; i++) {
int year = stdin.nextInt() -1;
System.out.println(S.get(year % n)+ T.get(year % m));
}
}
public static void main(String args[]) {
codeforces obj = new codeforces();
obj.solution();
}
} | Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 8dc4b59c1031f418fbf764c7b2a74243 | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.util.Scanner;
public class AAA {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
String str;
String[] str1 = new String[222];
int l1 = 0;
for (int i = 0; i < n; i++) {
str = input.next();
str1[i] = str;
l1++;
}
int l2 = 0;
String[] str2 = new String[222];
for (int i = 0; i < m; i++) {
str = input.next();
str2[i] = str;
l2++;
}
int q = input.nextInt();
for (int i = 1; i <= q; i++) {
int val = input.nextInt();
int div1, div2, pos1, pos2;
if (val >= n) {
div1 = val % n;
pos1 = val / n;
if (div1 == 0) {
System.out.print(str1[n - 1]);
} else {
System.out.print(str1[div1-1]);
}
} else {
System.out.print(str1[val - 1]);
}
if (val >= m) {
div2 = val % m;
pos2 = val / m;
if (div2 == 0) {
System.out.print(str2[m - 1]);
} else {
System.out.print(str2[div2-1]);
}
} else {
System.out.print(str2[val - 1]);
}
System.out.println();
}
}
} | Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 01cca612c7faa529a4d78f9a9325afe2 | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes |
import java.io.*;
import java.util.*;
public class Solution {
//--START helper submission code
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] s = new String[sc.nextInt()];
String[] t = new String[sc.nextInt()];
for (int i = 0; i < s.length; ++i) {
s[i] = sc.next();
}
for (int i = 0; i < t.length; ++i) {
t[i] = sc.next();
}
int q = sc.nextInt();
int qi;
while(q-- > 0) {
qi = sc.nextInt();
int idxA = (qi % s.length) - 1;
int idxB = (qi % t.length) - 1;
if(idxA == -1) idxA = s.length - 1;
if(idxB == -1) idxB = t.length - 1;
System.out.println(s[idxA] + t[idxB]);
}
}
//--END helper submission code
} | Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 1bcd00322337149f28f5ba27b17773c1 | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes |
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] s = new String[sc.nextInt()];
String[] t = new String[sc.nextInt()];
for (int i = 0; i < s.length; ++i) {
s[i] = sc.next();
}
for (int i = 0; i < t.length; ++i) {
t[i] = sc.next();
}
int q = sc.nextInt();
int qi;
while(q-- > 0) {
qi = sc.nextInt();
System.out.println(solution(s, t, qi));
}
}
public static String solution(String[] s, String[] t, int qi) {
int idxA = (qi % s.length) - 1;
int idxB = (qi % t.length) - 1;
if(idxA == -1) idxA = s.length - 1;
if(idxB == -1) idxB = t.length - 1;
return s[idxA] + t[idxB];
}
}
| Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 219b1779452a0984ffd7da1538a3f3cf | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n,m,q;
n=scanner.nextInt();
m=scanner.nextInt();
String[] s = new String[n];
String[] t = new String[m];
for (int i = 0; i < n; i++) {
s[i] = scanner.next();
}
for (int i = 0; i < m; i++) {
t[i] = scanner.next();
}
q = scanner.nextInt();
for (int i = 0; i < q; i++) {
int w = scanner.nextInt();
System.out.println(s[(w-1)%n] + t[(w-1)%m]);
}
}
}
| Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 8854998109be42440f6b158781e5d7fe | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | //problem: https://codeforces.com/problemset/problem/1284/A
import java.util.Scanner;
public class NewYearName{
public static void main(String[] args){
Scanner sObj = new Scanner(System.in);
int fLen = sObj.nextInt();
int sLen = sObj.nextInt();
sObj.nextLine();
String[] firstStr = sObj.nextLine().split(" ");
String[] secondStr = sObj.nextLine().split(" ");
int qryCnt = sObj.nextInt();
int year = 0;
for(int i=0; i<qryCnt; i++){
year = sObj.nextInt() -1;
sObj.nextLine();
System.out.println(firstStr[year%fLen] + secondStr[year%sLen]);
}
}
} | Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | 9b930e6800e0c16a7b3253451a26eb40 | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 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));
String nm[]=br.readLine().split(" ");
int n=Integer.parseInt(nm[0]);
int m=Integer.parseInt(nm[1]);
String n1[]=br.readLine().split(" ");
String m1[]=br.readLine().split(" ");
int t=Integer.parseInt(br.readLine());
while(t-->0){
int year=Integer.parseInt(br.readLine());
int indexn,indexm;
if(year%n==0){
indexn=n-1;
}
else
indexn=(year%n)-1;
if(year%m==0){
indexm=m-1;
}
else
indexm=(year%m)-1;
String ans=n1[indexn]+m1[indexm];
System.out.println(ans);
}
}
} | Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | e5067398f5facae23b43548614fec72d | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.util.*;
public class yearNames {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
scan.nextLine();
String s = scan.nextLine();
String t = scan.nextLine();
String[] sequenceS = s.split("\\s+");
String[] sequenceT = t.split("\\s+");
int q = scan.nextInt();
for(int i = 0; i < q; i++) {
int year = scan.nextInt();
String out = sequenceS[(year - 1) % sequenceS.length] + sequenceT[(year - 1) % sequenceT.length];
System.out.println(out);
}
}
} | Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | d656522b9253d05031b23256bacccb6d | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class decdfault_t {
public static void main(String[] args) {
in = new FastReader();
int n=ni();
int m=ni();
String[] arr1=new String[n];
String[] arr2=new String[m];
for (int i=0;i<n;i++){
arr1[i]=n();
}
for (int i=0;i<m;i++){
arr2[i]=n();
}
int i=0;int j=0;
int q=ni();
int max=0;
int[] inp=new int[q];
for (int ii=0;ii<q;ii++){
inp[ii]=ni();
}
for (int a:inp)max=Math.max(max,a);
// String[] ans=new String[max];
StringBuilder sb=new StringBuilder();
for (int a=0;a<inp.length;a++){
int no=inp[a]-1;
int xxx=no%n;
int yyy=no%m;
sb.append(arr1[xxx]).append(arr2[yyy]).append("\n");
}
System.out.println(sb.toString());
}
static class pair{
int x;
int y;
pair(int x,int y){
this.x=x;
this.y=y;
}
}
public static long binarySearch(long low, long high) {
while (high - low > 1) {
long mid = (high - low)/2 + low;
//System.out.println(mid);
if (works(mid)) {
high = mid;
} else {
low = mid;
}
}
return (works(low) ? low : high);
}
static long fast_exp_with_mod(long base, long exp) {
long MOD=1000000000+7;
long res=1;
while(exp>0) {
if(exp%2==1) res=(res*base)%MOD;
base=(base*base)%MOD;
exp/=2;
}
return res%MOD;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class my_no{
long num;
long denom;
@Override
public String toString() {
if (denom<0){
this.num=-this.num;
this.denom=-this.denom;
}
if (num==0)return "0";
return (num+"/"+denom);
}
my_no(int no){
this.num=no;
this.denom=1;
}
my_no(long num,long denom){
this.num=num;
this.denom=denom;
}
my_no multiply(my_no obj){
long num1=obj.num;
long denom1=obj.denom;
long n=num1*num;
long d=denom1*denom;
long gcd=gcd(n,d);
n/=gcd;
d/=gcd;
return new my_no(n,d);
}
// my_no multiply(my_no obj){
// long num1=obj.num;
// long denom1=obj.denom;
// long num2=this.num;
// long denom2=this.denom;
//
// }
my_no multiply(int no){
long n=num*no;
long d=denom;
long gcd=gcd(n,d);
n/=gcd;
d/=gcd;
return new my_no(n,d);
}
}
static void memset(int[][] arr,int val){
for (int i=0;i<arr.length;i++){
for (int j=0;j<arr[i].length;j++){
arr[i][j]=val;
}
}
}
static void memset(int[] arr,int val){
for (int i=0;i<arr.length;i++){
arr[i]=val;
}
}
static void memset(long[][] arr,long val){
for (int i=0;i<arr.length;i++){
for (int j=0;j<arr[i].length;j++){
arr[i][j]=val;
}
}
}
static void memset(long[] arr,long val){
for (int i=0;i<arr.length;i++){
arr[i]=val;
}
}
static private boolean works(long test){
return true;
}
public static int upperBound(int[] array,
int value)
{
int low = 0;
int high = array.length;
while (low < high)
{
final int mid = (low + high) / 2;
if (value >= array[mid])
{
low = mid + 1;
}
else
{
high = mid;
}
}
return low;
}
static void reverse(char[] arr ,int i,int j){
if (i==j)
return;
while (i<j){
char temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
++i;
--j;
}
}
static int[] takeIntegerArrayInput(int no){
int[] arr=new int[no];
for (int i=0;i<no;++i){
arr[i]=ni();
}
return arr;
}
static long fast_Multiply(long no , long pow){
long result=1;
while (pow>0){
if ((pow&1)==1){
result=result*no;
}
no=no*no;
pow>>=1;
}
return result;
}
static long[] takeLongArrayInput(int no){
long[] arr=new long[no];
for (int i=0;i<no;++i){
arr[i]=ni();
}
return arr;
}
static final long MOD = (long)1e9+7;
static FastReader in;
static void p(Object o){
System.out.print(o);
}
static void pn(Object o){
System.out.println(o);
}
static String n(){
return in.next();
}
static String nln(){
return in.nextLine();
}
static int ni(){
return Integer.parseInt(in.next());
}
static int[] ia(int N){
int[] a = new int[N];
for(int i = 0; i<N; i++)a[i] = ni();
return a;
}
static long[] la(int N){
long[] a = new long[N];
for(int i = 0; i<N; i++)a[i] = nl();
return a;
}
static long nl(){
return Long.parseLong(in.next());
}
static double nd(){
return Double.parseDouble(in.next());
}
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;
}
}
static void println(String[] arr){
for (int i=0;i<arr.length;++i){
System.out.println(arr[i]);
}
}
}
| Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | c6f8a392b4de20d71bf9db606f6a7549 | train_003.jsonl | 1578139500 | Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system? | 1024 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
String[] table1 = new String[n];
String[] table2 = new String[m];
for (int i = 0; i < n; i++) {
table1[i] = scanner.next();
}
for (int i = 0; i < m; i++) {
table2[i] = scanner.next();
}
int q = scanner.nextInt();
for (int i = 0; i < q; i++) {
int input = scanner.nextInt();
System.out.println(table1[(input-1)%n] + table2[(input-1)%m]);
}
}
}
| Java | ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"] | 1 second | ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"] | NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | Java 11 | standard input | [
"implementation",
"strings"
] | efa201456f8703fcdc29230248d91c54 | The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for. | 800 | Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above. | standard output | |
PASSED | af963437612f6ff48b072eed966a13d2 | train_003.jsonl | 1533737100 | Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 < i_2 < \ldots < i_k\leq n$$$ is called increasing if $$$a_{i_1} < a_{i_2} < a_{i_3} < \ldots < a_{i_k}$$$. If $$$a_{i_1} > a_{i_2} > a_{i_3} > \ldots > a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS. | 256 megabytes |
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import static java.lang.Integer.max;
public class ThePhoneNumber implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
public void solve() {
int n = in.ni(), m = (int) Math.sqrt(n);
for (int i = 0; i < n; i++) {
out.print(max(n - m * (i / m + 1), 0) + i % m + 1);
out.print(' ');
}
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (ThePhoneNumber instance = new ThePhoneNumber()) {
instance.solve();
}
}
}
| Java | ["4", "2"] | 1 second | ["3 4 1 2", "2 1"] | NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid. | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 6ea899e915cfc95a43f0e16d6d08cc1e | The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build. | 1,600 | Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any. | standard output | |
PASSED | 1e2d42e6c1c765ebc6cdd1bc110f0fbd | train_003.jsonl | 1533737100 | Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 < i_2 < \ldots < i_k\leq n$$$ is called increasing if $$$a_{i_1} < a_{i_2} < a_{i_3} < \ldots < a_{i_k}$$$. If $$$a_{i_1} > a_{i_2} > a_{i_3} > \ldots > a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS. | 256 megabytes | /*
* Author: Minho Kim (ISKU)
* Date: August 8, 2018
* E-mail: minho.kim093@gmail.com
*
* https://github.com/ISKU/Algorithm
* http://codeforces.com/problemset/problem/1017/C
*/
import java.io.*;
public class C {
private static void solve() {
int N = io.nextInt();
int lis = (int) Math.sqrt(N);
int lds = (int) Math.ceil((double) N / (double) lis);
for (int i = 1; i <= lds; i++) {
int element = N - (i * lis) + 1;
for (int j = 0; j < lis; j++, element++)
if (element >= 1)
io.printls(element);
}
}
private static FastIO io;
public static void main(String... args) {
io = new FastIO(System.in, System.out);
solve();
io.close();
}
/**
* https://github.com/ISKU/FastIO-Java
*
* @author Minho Kim <minho.kim093@gmail.com>
*/
private static class FastIO {
public static final int DEFAULT_BUFFER_SIZE = 65536;
public static final int DEFAULT_INTEGER_SIZE = 10;
public static final int DEFAULT_LONG_SIZE = 19;
public static final int DEFAULT_WORD_SIZE = 256;
public static final int DEFAULT_LINE_SIZE = 1024;
public static final int EOF = -1;
private final InputStream in;
private final OutputStream out;
private byte[] inBuffer;
private int nextIn, inLength;
private byte[] outBuffer;
private int nextOut;
private char[] charBuffer;
private byte[] byteBuffer;
public FastIO(InputStream in, OutputStream out, int inBufferSize, int outBufferSize) {
this.in = in;
this.inBuffer = new byte[inBufferSize];
this.nextIn = 0;
this.inLength = 0;
this.out = out;
this.outBuffer = new byte[outBufferSize];
this.nextOut = 0;
this.charBuffer = new char[DEFAULT_LINE_SIZE];
this.byteBuffer = new byte[DEFAULT_LONG_SIZE];
}
public FastIO(InputStream in, OutputStream out) {
this(in, out, DEFAULT_BUFFER_SIZE, DEFAULT_BUFFER_SIZE);
}
public FastIO(InputStream in, OutputStream out, int bufferSize) {
this(in, out, bufferSize, bufferSize);
}
public char nextChar() {
byte b;
while (isSpace(b = read()))
;
return (char) b;
}
public String next() {
byte b;
while (isSpace(b = read()))
;
int pos = 0;
do {
charBuffer[pos++] = (char) b;
} while (!isSpace(b = read()));
return new String(charBuffer, 0, pos);
}
public String nextLine() {
byte b;
int pos = 0;
while (!isLine(b = read()))
charBuffer[pos++] = (char) b;
return new String(charBuffer, 0, pos);
}
public int nextInt() {
byte b;
while (isSpace(b = read()))
;
boolean negative = false;
int result = b - '0';
if (b == '-') {
negative = true;
result = 0;
}
while (isDigit(b = read()))
result = (result * 10) + (b - '0');
return negative ? -result : result;
}
public long nextLong() {
byte b;
while (isSpace(b = read()))
;
boolean negative = false;
long result = b - '0';
if (b == '-') {
negative = true;
result = 0;
}
while (isDigit(b = read()))
result = (result * 10) + (b - '0');
return negative ? -result : result;
}
public float nextFloat() {
byte b;
while (isSpace(b = read()))
;
int pos = 0;
do {
charBuffer[pos++] = (char) b;
} while (!isSpace(b = read()));
return Float.parseFloat(new String(charBuffer, 0, pos));
}
public float nextFloat2() {
byte b;
while (isSpace(b = read()))
;
boolean negative = false;
float result = b - '0';
if (b == '-') {
negative = true;
result = 0;
}
while (isDigit(b = read()))
result = (result * 10) + (b - '0');
float d = 1;
if (b == '.') {
while (isDigit(b = read()))
result += (b - '0') / (d *= 10);
}
return negative ? -result : result;
}
public double nextDouble() {
byte b;
while (isSpace(b = read()))
;
int pos = 0;
do {
charBuffer[pos++] = (char) b;
} while (!isSpace(b = read()));
return Double.parseDouble(new String(charBuffer, 0, pos));
}
public double nextDouble2() {
byte b;
while (isSpace(b = read()))
;
boolean negative = false;
double result = b - '0';
if (b == '-') {
negative = true;
result = 0;
}
while (isDigit(b = read()))
result = (result * 10) + (b - '0');
double d = 1;
if (b == '.') {
while (isDigit(b = read()))
result += (b - '0') / (d *= 10);
}
return negative ? -result : result;
}
public char[] nextToCharArray() {
byte b;
while (isSpace(b = read()))
;
int pos = 0;
do {
charBuffer[pos++] = (char) b;
} while (!isSpace(b = read()));
char[] array = new char[pos];
System.arraycopy(charBuffer, 0, array, 0, pos);
return array;
}
public int[] nextIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = nextInt();
return array;
}
public long[] nextLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++)
array[i] = nextLong();
return array;
}
public int[][] nextInt2DArray(int Y, int X) {
int[][] array = new int[Y][X];
for (int y = 0; y < Y; y++)
for (int x = 0; x < X; x++)
array[y][x] = nextInt();
return array;
}
public void print(char c) {
write((byte) c);
}
public void print(String s) {
for (int i = 0; i < s.length(); i++)
write((byte) s.charAt(i));
}
public void print(int i) {
if (i == 0) {
write((byte) '0');
return;
}
if (i == Integer.MIN_VALUE) {
write((byte) '-');
write((byte) '2');
write((byte) '1');
write((byte) '4');
write((byte) '7');
write((byte) '4');
write((byte) '8');
write((byte) '3');
write((byte) '6');
write((byte) '4');
write((byte) '8');
return;
}
if (i < 0) {
write((byte) '-');
i = -i;
}
int pos = 0;
while (i > 0) {
byteBuffer[pos++] = (byte) ((i % 10) + '0');
i /= 10;
}
while (pos-- > 0)
write(byteBuffer[pos]);
}
public void print(long l) {
if (l == 0) {
write((byte) '0');
return;
}
if (l == Long.MIN_VALUE) {
write((byte) '-');
write((byte) '9');
write((byte) '2');
write((byte) '2');
write((byte) '3');
write((byte) '3');
write((byte) '7');
write((byte) '2');
write((byte) '0');
write((byte) '3');
write((byte) '6');
write((byte) '8');
write((byte) '5');
write((byte) '4');
write((byte) '7');
write((byte) '7');
write((byte) '5');
write((byte) '8');
write((byte) '0');
write((byte) '8');
return;
}
if (l < 0) {
write((byte) '-');
l = -l;
}
int pos = 0;
while (l > 0) {
byteBuffer[pos++] = (byte) ((l % 10) + '0');
l /= 10;
}
while (pos-- > 0)
write(byteBuffer[pos]);
}
public void print(float f) {
String sf = Float.toString(f);
for (int i = 0; i < sf.length(); i++)
write((byte) sf.charAt(i));
}
public void print(double d) {
String sd = Double.toString(d);
for (int i = 0; i < sd.length(); i++)
write((byte) sd.charAt(i));
}
public void printls(char c) {
print(c);
write((byte) ' ');
}
public void printls(String s) {
print(s);
write((byte) ' ');
}
public void printls(int i) {
print(i);
write((byte) ' ');
}
public void printls(long l) {
print(l);
write((byte) ' ');
}
public void printls(float f) {
print(f);
write((byte) ' ');
}
public void printls(double d) {
print(d);
write((byte) ' ');
}
public void println(char c) {
print(c);
write((byte) '\n');
}
public void println(String s) {
print(s);
write((byte) '\n');
}
public void println(int i) {
print(i);
write((byte) '\n');
}
public void println(long l) {
print(l);
write((byte) '\n');
}
public void println(float f) {
print(f);
write((byte) '\n');
}
public void println(double d) {
print(d);
write((byte) '\n');
}
public void printf(String format, Object... args) {
String s = String.format(format, args);
for (int i = 0; i < s.length(); i++)
write((byte) s.charAt(i));
}
public void fprint(char c) {
print(c);
flushBuffer();
}
public void fprint(String s) {
print(s);
flushBuffer();
}
public void fprint(int i) {
print(i);
flushBuffer();
}
public void fprint(long l) {
print(l);
flushBuffer();
}
public void fprint(float f) {
print(f);
flushBuffer();
}
public void fprint(double d) {
print(d);
flushBuffer();
}
public void fprintf(String format, Object... args) {
printf(format, args);
flushBuffer();
}
private byte read() {
if (nextIn >= inLength) {
if ((inLength = fill()) == EOF)
return EOF;
nextIn = 0;
}
return inBuffer[nextIn++];
}
private void write(byte b) {
if (nextOut >= outBuffer.length)
flushBuffer();
outBuffer[nextOut++] = b;
}
private int fill() {
try {
return in.read(inBuffer, 0, inBuffer.length);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void flush() {
if (nextOut == 0)
return;
flushBuffer();
}
private void flushBuffer() {
try {
out.write(outBuffer, 0, nextOut);
} catch (Exception e) {
throw new RuntimeException(e);
}
nextOut = 0;
}
public void close() {
flush();
}
private boolean isDigit(byte b) {
return b >= '0' && b <= '9';
}
private boolean isLine(byte b) {
return b == '\n' || b == '\r' || b == EOF;
}
private boolean isSpace(byte b) {
return b == ' ' || b == '\t' || b == '\n' || b == '\r' || b == '\f' || b == EOF;
}
}
} | Java | ["4", "2"] | 1 second | ["3 4 1 2", "2 1"] | NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid. | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 6ea899e915cfc95a43f0e16d6d08cc1e | The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build. | 1,600 | Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any. | standard output | |
PASSED | bd3b3ebded297ebc3a46541f47113072 | train_003.jsonl | 1533737100 | Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 < i_2 < \ldots < i_k\leq n$$$ is called increasing if $$$a_{i_1} < a_{i_2} < a_{i_3} < \ldots < a_{i_k}$$$. If $$$a_{i_1} > a_{i_2} > a_{i_3} > \ldots > a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author bacali
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CThePhoneNumber solver = new CThePhoneNumber();
solver.solve(1, in, out);
out.close();
}
static class CThePhoneNumber {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int l = (int) Math.sqrt(n);
ArrayList<Integer> tab = new ArrayList<>(n + 1);
int i = 0;
int j = n;
boolean[] vis = new boolean[n];
while (j > 0) {
for (int k = 0; k < l && j > 0; k++) {
tab.add(i * l, j--);
vis[j] = true;
}
i++;
}
i = tab.size();
for (int k = n; k > 0; k--) {
if (!vis[k - 1]) {
tab.add(i, k);
}
}
for (int k = 0; k < n; k++) {
out.print(tab.get(k) + " ");
}
}
}
static class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["4", "2"] | 1 second | ["3 4 1 2", "2 1"] | NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid. | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 6ea899e915cfc95a43f0e16d6d08cc1e | The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build. | 1,600 | Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.