exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | d14c1fe7aaf42de7ebfbe138f186aaa6 | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.util.*;
import java.io.*;
import java.util.Scanner;
public class main {
public static void main (String [] args) throws Exception {
new main();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
public String next() throws Exception { //takes next word from input
if (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public double nextDouble() throws Exception {
return Double.parseDouble(next());
}
public main() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public void solve() throws Exception {
int n = nextInt();
long A[] = new long[n];
long ans[] = new long[n];
for (int i = 0; i < n; ++i) {
A[i] = nextInt();
}
long max = -1000;
for (int i = n - 1; i >= 0; --i) {
if (A[i] > max) {
max = A[i];
ans[i] = 0;
}
else if (A[i] <= max) {
ans[i] = max - A[i] + 1;
}
}
for (int i = 0; i < n; ++i) {
out.print(ans[i] + " ");
}
}
}
//1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | 2727f80bfa73dd14b32db88c55f324e4 | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.util.*;
public class Spoj {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=in.nextInt();
int right[]=new int[n];
for(int i=n-2;i>=0;i--)
right[i]=Math.max(arr[i+1], right[i+1]);
for(int i=0;i<n;i++){
int ans=0;
if(arr[i]<=right[i])
ans=right[i]-arr[i]+1;
System.out.print(ans+" ");
}
in.close();
}
}
| Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | 4bfc7370b2fd3c5d2d2b58d90578e9b5 | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main2 {
public static void main(String[] args) throws IOException {
File file = new File("in");
BufferedReader in;
if (file.exists()) {
in = new BufferedReader(new FileReader(file));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
}
String line, lines[];
int n = Integer.parseInt(in.readLine());
int arr[] = readInts(in.readLine());
int max = arr[n-1];
arr[n-1] = 0;
StringBuilder out = new StringBuilder("");
for( int i = n-2; i >= 0; i-- )
{
if ( arr[i] > max )
{
max = arr[i];
arr[i] = 0;
}
else
{
arr[i] = (max+1-arr[i]);
}
}
for( int i = 0; i< n-1; i++ ) out.append(arr[i]+" ");
out.append(arr[n-1]);
System.out.println(out);
}
public static int[] readInts(String line) {
String lines[] = line.split("\\s+");
int[] result = new int[line.length()];
for (int i = 0; i < lines.length; i++)
result[i] = Integer.parseInt(lines[i]);
return result;
}
}
| Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | a5766c92f7bebf3bb138a0ab8c3e3373 | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[]in = br.readLine().split(" ");
int[] arr = new int[n];
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(in[i]);
int[][]max = new int[n][2];
max[n-1][0]=arr[n-1];
max[n-1][1]=n-1;
for(int i=n-2;i>=0;i--){
if(max[i+1][0]>=arr[i]){
max[i][0]=max[i+1][0];
max[i][1]=max[i+1][1];
}
else{
max[i][0]=arr[i];
max[i][1]=i;
}
}
for(int i=0;i<n-1;i++){
if(arr[i]<max[i][0]){
System.out.print((max[i][0]-arr[i]+1)+" ");
}
else if(max[i][1]==i)
System.out.print(0+" ");
else
System.out.print(1+" ");
}
System.out.println(0);
}
}
| Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | 79331bfcde9040a8049afc8397ba17d1 | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long[] a = new long[n];
long[] b = new long[n];
for(int i = 0; i < n; i++)
{
a[i] = in.nextInt();
}
long max = a[a.length - 1] - 1;
for( int i = n - 1; i >= 0; i--)
{
// for( int k = i + 1; k < n; k++)
// {
// if(a[k] > max) {
// max = a[k];
// }
// }
if (max >= a[i]) {
b[i] = max - a[i] + 1;
} else {
b[i] = 0;
}
if(a[i] > max) {
max = a[i];
}
// if (i < n - 1) {
// System.out.print(b[i] + " ");
// } else {
// System.out.println(b[i]);
// }
}
for( int i = 0; i < n; i++)
{
if (i < n - 1) {
System.out.print(b[i] + " ");
} else {
System.out.println(b[i]);
}
}
}
}
/*
входные данные
5
1 2 3 1 2
выходные данные
3 2 0 2 0
входные данные
4
3 2 1 4
выходные данные
2 3 4 0
5
500 400 300 200 100
*/ | Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | 2a7a680c378b5f0d04bf4d2e0b792216 | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.util.Scanner;
public class B {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[] = new int[n];
for(int i = 0 ; i < n ; i++)
a[i] = in.nextInt();
int b[] = new int[n];int max=a[n-1];
for(int i = n-2 ; i >=0 ; i--)
if(a[i]<=max)
b[i] = max-a[i]+1;
else
max = a[i];
for(int i = 0 ; i < n ; i++)
System.out.print(b[i]+" ");
}
}
| Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | 24a115d0e08823ee333199204c6f09fe | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.io.*;
import java.util.*;
public class B
{
FastScanner in;
PrintWriter out;
int i = 0, j = 0;
void solve() {
/**************START**************/
int n = in.nextInt();
int[] seq = new int[n];
for (i = 0; i < n; i++)
{
seq[i] = in.nextInt();
}
int high = seq[n-1];
seq[n-1] = 0;
for (i = n-2; i >= 0; i--)
{
if (seq[i] > high)
{
high = seq[i];
seq[i] = 0;
}
else
{
seq[i] = high - seq[i] + 1;
}
}
for (i = 0; i < n; i++)
{
out.print(seq[i] + " ");
}
out.print("\n");
/***************END***************/
}
public static void main(String[] args) {
new B().runIO();
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | 6f135f088305b518d5c4ea83bbca541e | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | //package codeforces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;
public class LuxuriousHouses
{
public static void main(String[] args)
{
MyScanner scan = new MyScanner();
int n = scan.nextInt();
int[] h = new int[n];
for (int i = 0; i < n; i++) {
h[i] = scan.nextInt();
}
int maxFloors = 0;
Stack<Integer> stack = new Stack<Integer>();
for (int i = n-1; i >=0; i--)
{
if (h[i]>maxFloors) {
maxFloors = h[i];
stack.push(0);
} else {
stack.push(maxFloors-h[i]+1);
}
}
while (!stack.isEmpty()) {
System.out.print(stack.pop()+" ");
}
System.out.println();
}
//--------------------------------------------------------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
| Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | bfe0deaaf2899e01600468b7c567407c | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | //package TestOnly.Div2B_322.Code1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main
{
FastScanner in;
PrintWriter out;
public void solve() throws IOException
{
int n = in.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < a.length; i++)
{
a[i] = in.nextInt();
}
int max = 0;
for (int i = n - 1; i >= 0; i--)
{
b[i] = Math.max(0, max + 1 - a[i]);
max = Math.max(max, a[i]);
}
for (int i = 0; i < b.length; i++)
{
System.out.print(b[i] + " ");
}
}
public void run()
{
try
{
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
class FastScanner
{
BufferedReader br;
StringTokenizer st;
FastScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreTokens())
{
try
{
st = new StringTokenizer(br.readLine());
} catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
}
public static void main(String[] arg)
{
new Main().run();
}
}
| Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | e94072ad4e1fd203b7d61a4d5170e9ac | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | //package TestOnly.Div2B_322.Code1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main
{
FastScanner in;
PrintWriter out;
/*
* public void solve() throws IOException { int n = in.nextInt(); int a[] = new int[n]; int b[] = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } int max = 0; for (int i = n - 1; i >= 0; i--) { b[i] = Math.max(0, max + 1 - a[i]); max = Math.max(max, a[i]); } for (int i = 0; i < b.length; i++) { System.out.print(b[i] + " "); } }
*/
public void solve() throws IOException
{
int n = in.nextInt();
long a[] = new long[n];
for (int i = 0; i < a.length; i++)
{
a[i] = in.nextInt();
}
long max = a[n - 1];
a[a.length - 1] = 0;
for (int i = n - 2; i >= 0; i--)
{
if (a[i] <= max)
{
a[i] = max + 1 - a[i];
} else
{
max = a[i];
a[i] = 0;
}
}
for (int i = 0; i < a.length; i++)
{
System.out.print(a[i] + " ");
}
}
public void run()
{
try
{
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
class FastScanner
{
BufferedReader br;
StringTokenizer st;
FastScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreTokens())
{
try
{
st = new StringTokenizer(br.readLine());
} catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
}
public static void main(String[] arg)
{
new Main().run();
}
}
| Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | f693a1d69123d3fa20ac282607e91eaf | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class LuxuriousHouses {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(f.readLine());
int[] a = new int[n];
StringTokenizer st = new StringTokenizer(f.readLine());
for (int i = 0; i < n; i++)
a[i] = Integer.parseInt(st.nextToken());
int[] b = new int[n];
int max = a[n-1];
for (int i = n-2; i >= 0; i--) {
b[i] = Math.max(max - a[i] + 1, 0);
max = Math.max(max, a[i]);
}
StringBuffer sb = new StringBuffer();
for (int x : b)
sb.append(" " + x);
System.out.println(sb.toString().substring(1));
}
} | Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | c1fdf09d30b8febceef5f7699f7716c1 | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.Random;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] max = new int[n];
max[n - 1] = a[n - 1];
for (int i = n - 2; i >= 0 ; i--) {
max[i] = Math.max(max[i + 1], a[i]);
}
for (int i = 0; i < n; i++) {
if (i == n - 1) {
out.print(0 + " ");
break;
}
if (a[i] <= max[i + 1]) {
out.print(max[i + 1] - a[i] + 1 + " ");
} else
out.print(0 + " ");
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer st;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | 91cdb1caccd4e919b8e0f0009670776d | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.util.Scanner;
public class Ma {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] ArrIn= new int[N];
int[] ArrOut= new int[N];
int i=0;
for (int k=0; k<N; k++) {
ArrIn[k] = sc.nextInt();
}
int maxtmp=0;
for (int k=N-1; k>=0; k--){
if (ArrIn[k]>maxtmp){ // ��� �����?
maxtmp=ArrIn[k];
ArrIn[k]=0;
ArrOut[k]=0;
}
else {
ArrOut[k]=maxtmp-ArrIn[k]+1;
}
}
for (int k=0; k<N; k++){
System.out.print(ArrOut[k]+ " ");
}
}
} | Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | 366362d58bc433559364d2887e4e6e58 | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.io.*;
import java.util.*;
public class P581B{
static int[] run(int[] ar){
int[] max_ar = new int[ar.length];
for (int i=ar.length-1; i>-1; i--) {
if(i==ar.length-1)
max_ar[i] = 0;
else{
if(max_ar[i+1]>ar[i+1])
max_ar[i] = max_ar[i+1];
else
max_ar[i] = ar[i+1];
}
}
int[] res = new int[ar.length];
for (int i=0; i<ar.length; i++) {
if(ar[i]>max_ar[i])
res[i] = 0;
else
res[i] = max_ar[i] - ar[i] + 1;
}
return res;
}
static void print(int[] ar){
for(int i=0; i<ar.length-1; i++){
System.out.print(ar[i] + ",");
}
System.out.println(ar[ar.length-1]);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String s = sc.nextLine();
String[] s_ar = s.split(" ");
int[] int_ar = new int[s_ar.length];
for (int i=0; i<s_ar.length; i++) {
int_ar[i] = Integer.parseInt(s_ar[i].trim());
}
int[] res_ar = run(int_ar);
for (int i=0; i<res_ar.length-1; i++) {
System.out.print(res_ar[i] + " ");
}
System.out.println(res_ar[res_ar.length-1]);
}
}
| Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | fbc361980452a66da09d06466e1ac246 | train_000.jsonl | 1443430800 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class P581B {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] heights = new int[n];
int[] result = new int[n];
String[] heights_str = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
heights[i] = Integer.parseInt(heights_str[i]);
}
int max_to_right = 0;
result[n - 1] = 0;
for (int i = n - 2; i >= 0; i--) {
if (heights[i + 1] > max_to_right)
max_to_right = heights[i + 1];
if (heights[i] > max_to_right)
continue;
result[i] = max_to_right - heights[i] + 1;
}
for (int i = 0; i < n; i++)
System.out.print(result[i] + " ");
}
}
| Java | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | 1 second | ["3 2 0 2 0", "2 3 4 0"] | null | Java 7 | standard input | [
"implementation",
"math"
] | e544ed0904e2def0c1b2d91f94acbc56 | The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. | 1,100 | Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | standard output | |
PASSED | b6c6f2a1737d0658ef6af8cf46a66071 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | //babes, its gonna take time
import java.util.*;
import java.io.*;
public class codeforces
{
public static void main(String[] args)
{
FastReader s=new FastReader();
int t=s.nextInt();
while(t-->0)
{
int max=0;
int n=s.nextInt();
String str1=s.next();
String str2=s.next();
int memo[][]=new int[21][21];
boolean cout=true;
for(int i=0;i<n;i++)
{
int val1=(str1.charAt(i)-'a');
max=Math.max(max,val1);
int val2=(str2.charAt(i)-'a');
if(val1>val2)
{
cout=false;
break;
}
memo[val1][val2]++;
}
if(!cout)
System.out.println(-1);
else
{
int count=0;
for(int i=0;i<21;i++)
{
cout=false;
int prev=0;
for(int j=0;j<21;j++)
{
if(i==j)
continue;
if(memo[i][j]>0)
{
if(!cout)
{
prev=j;
max=Math.max(prev,max);
count++;
cout=true;
}
else if(i==max)
{
count++;
}
else
{
memo[prev][j]=memo[i][j];
}
}
}
}
System.out.println(count);
}
}
}
//FastReader//////////////////////////////////////////////////////////////////////////////
private 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 | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | f36ad37ce5497e74f84d53292adc6580 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
StringBuilder sb=new StringBuilder();
int t=s.nextInt();
for(int i=0;i<t;i++)
{
int n=s.nextInt();
String str1=s.next();
String str2=s.next();
int p=0;
for(int j=0;j<n;j++)
{
if(str1.charAt(j)>str2.charAt(j))
{
p=1;
break;
}
}
if(p==1)
{
sb.append("-1\n");
}
else
{
int[][] dp=new int[26][26];
for(int j=0;j<n;j++)
{
dp[str1.charAt(j)-'a'][str2.charAt(j)-'a']++;
}
int ans=0;
for(int j=0;j<26;j++)
{
for(int k=j+1;k<26;k++)
{
if(dp[j][k]>0)
{
ans++;
int count=0;
for(int l=k+1;l<26;l++)
{
count=dp[j][l];
dp[j][l]=0;
dp[k][l]=dp[k][l]+count;
}
}
}
}
sb.append(ans);
sb.append("\n");
}
}
System.out.println(sb);
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | c879550a5dd8d94bf1a1a3c45357c95d | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
static ArrayList<Integer> adj[];
//static PrintWriter out = new PrintWriter(System.out);
static int [][]notmemo;
static int k;
static long[] a;
static int b[];
static int m;
static class Pair implements Comparable<Pair> {
int node;
long cost;
public Pair(int b,long l) {
node=b;
cost=l;
}
@Override
public int compareTo(Pair o) {
return Long.compare(this.cost,o.cost);
}
}
static Pair s1[];
static ArrayList<Edge> adjlist[];
//static char c[];
public static long mod= 1000000007;
static int V;
static long INF = (long) 1E16;
static int n;
static int s;
static char c[];
static int d[];
static int z;
static int p[];
static int h[];
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t=sc.nextInt();
label:while(t-->0) {
int n=sc.nextInt();
String a=sc.nextLine();
String b=sc.nextLine();
UnionFind uf=new UnionFind(20);
for (int i = 0; i < a.length(); i++) {
if(a.charAt(i)==b.charAt(i))
continue;
else if(a.charAt(i)>b.charAt(i)) {
System.out.println(-1);
continue label;
}
else {
uf.unionSet(a.charAt(i)-'a', b.charAt(i)-'a');
}
}
System.out.println(20-uf.numSets);
}
out.flush();
}
static ArrayList<Integer> inc=new ArrayList<>();
static Stack<Integer> dec=new Stack<>();
static long total;
static void dfs(int u) {
vis[u]=true;
for(int v:adj[u]) {
if(!vis[v]) {
dfs(v);
}
}
total+=(a[u]*1l);
if(a[u]>0) {
if(h[u]!=-2)
a[h[u]]+=a[u];
inc.add(u);
}
else {
dec.add(u);
}
}
static int zz;
//static int dp(int idx,int left,int state) {
//if(idx>=k-((zz-left)*2)||idx+1==n) {
// return 0;
//}
//if(memo[idx][left][state]!=-1) {
// return memo[idx][left][state];
//}
//int ans=a[idx+1]+dp(idx+1,left,0);
//if(left>0&&state==0&&idx>0) {
// ans=Math.max(ans,a[idx-1]+dp(idx-1,left-1,1));
//}
//return memo[idx][left][state]=ans;
//}
static HashMap<Integer,Integer> map;
static int maxa=0;
static int ff=123123;
static long dist[][];
static int[][][] memo;
static void dijkstra(int S) //O(E log E)
{
dist = new long[n][maxa+1];
for(long x[]:dist)
Arrays.fill(x, (long) 1e17);
PriorityQueue<Edge> pq = new PriorityQueue<>();
dist[0][S] = 0;
pq.add(new Edge(0,S,0)); //may add more in case of MSSP (Mult-Source)
while(!pq.isEmpty())
{
Edge cur=pq.poll();
int mincoins=(int) Math.min(maxa,cur.cost+c[cur.node]);
if(cur.time+d[cur.node]<dist[cur.node][mincoins]) {
pq.add(new Edge(cur.node,mincoins,dist[cur.node][mincoins]=cur.time+d[cur.node]));
}
for(Edge e:adjlist[cur.node]) {
if(cur.cost<e.cost)
continue;
if(cur.time+e.time<dist[(int) e.node][(int) (cur.cost-e.cost)]) {
pq.add(new Edge(e.node,cur.cost-e.cost,dist[e.node][(int) (cur.cost-e.cost)]=cur.time+e.time));
}
}
}
}
static long modmod=998244353;
static int dx[]= {1,-1,0,0};
static int dy[]= {0,0,1,-1};
static class BBOOK implements Comparable<BBOOK>{
int t;
int alice;
int bob;
public BBOOK(int x,int y,int z) {
t=x;
alice=y;
bob=z;
}
@Override
public int compareTo(BBOOK o) {
return this.t-o.t;
}
}
private static long lcm(long a2, long b2) {
return (a2*b2)/gcd(a2,b2);
}
static class Edge implements Comparable<Edge>
{
int node;long cost ; long time;
Edge(int a, long b,long c) { node = a; cost = b; time=c; }
public int compareTo(Edge e){ return Long.compare(time,e.time); }
}
static void sieve(int N) // O(N log log N)
{
isComposite = new int[N+1];
isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number
primes = new ArrayList<Integer>();
for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N))
if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance
{
primes.add(i);
if(1l * i * i <= N)
for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve
isComposite[j] = 1;
}
}
static TreeSet<Integer> factors;
static ArrayList<Integer> primeFactors(int N) // O(sqrt(N) / ln sqrt(N))
{
ArrayList<Integer> factors = new ArrayList<Integer>(); //take abs(N) in case of -ve integers
int idx = 0, p = primes.get(idx);
while(1l*p * p <= N)
{
while(N % p == 0) { factors.add(p); N /= p; }
p = primes.get(++idx);
}
if(N != 1) // last prime factor may be > sqrt(N)
factors.add(N); // for integers whose largest prime factor has a power of 1
return factors;
}
static class SegmentTree { // 1-based DS, OOP
int N; //the number of elements in the array as a power of 2 (i.e. after padding)
int[] array, sTree, lazy;
SegmentTree(int[] in)
{
array = in; N = in.length - 1;
sTree = new int[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero
lazy = new int[N<<1];
Arrays.fill(sTree, (int) 1e9);
build(1,1,N);
}
void build(int node, int b, int e) // O(n)
{
if(b == e)
sTree[node] = array[b];
else
{
int mid = b + e >> 1;
build(node<<1,b,mid);
build(node<<1|1,mid+1,e);
sTree[node] = Math.min(sTree[node<<1],sTree[node<<1|1]);
}
}
void update_point(int index, int val) // O(log n)
{
index += N - 1;
sTree[index] = val;
while(index>1)
{
index >>= 1;
sTree[index] = Math.min(sTree[index<<1],sTree[index<<1|1]);
}
}
void update_range(int i, int j, int val) // O(log n)
{
update_range(1,1,N,i,j,val);
}
void update_range(int node, int b, int e, int i, int j, int val)
{
if(i > e || j < b)
return;
if(b >= i && e <= j)
{
sTree[node] += (e-b+1)*val;
lazy[node] += val;
}
else
{
int mid = b + e >> 1;
propagate(node, b, mid, e);
update_range(node<<1,b,mid,i,j,val);
update_range(node<<1|1,mid+1,e,i,j,val);
sTree[node] = sTree[node<<1] + sTree[node<<1|1];
}
}
void propagate(int node, int b, int mid, int e)
{
lazy[node<<1] += lazy[node];
lazy[node<<1|1] += lazy[node];
sTree[node<<1] += (mid-b+1)*lazy[node];
sTree[node<<1|1] += (e-mid)*lazy[node];
lazy[node] = 0;
}
int query(int i, int j)
{
return query(1,1,N,i,j);
}
int query(int node, int b, int e, int i, int j) // O(log n)
{
if(i>e || j <b)
return 0;
if(b>= i && e <= j)
return sTree[node];
int mid = b + e >> 1;
propagate(node, b, mid, e);
int q1 = query(node<<1,b,mid,i,j);
int q2 = query(node<<1|1,mid+1,e,i,j);
return Math.min(q1,q2);
}
}
static class UnionFind {
int[] p, rank, setSize;
int numSets;
int max[];
public UnionFind(int N) {
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) {
p[i] = i;
setSize[i] = 1;
}
}
public int findSet(int i) {
return p[i] == i ? i : (p[i] = findSet(p[i]));
}
public boolean isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
public int chunion(int i,int j, int x2) {
if (isSameSet(i, j))
return 0;
numSets--;
int x = findSet(i), y = findSet(j);
int z=findSet(x2);
p[x]=z;;
p[y]=z;
return x;
}
public void unionSet(int i, int j) {
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) {
p[y] = x;
setSize[x] += setSize[y];
} else {
p[x] = y;
setSize[y] += setSize[x];
if (rank[x] == rank[y])
rank[y]++;
}
}
public int numDisjointSets() {
return numSets;
}
public int sizeOfSet(int i) {
return setSize[findSet(i)];
}
}
static class Quad implements Comparable<Quad> {
int u;
int v;
char state;
int turns;
public Quad(int i, int j, char c, int k) {
u = i;
v = j;
state = c;
turns = k;
}
public int compareTo(Quad e) {
return (int) (turns - e.turns);
}
}
static long manhatandistance(long x, long x2, long y, long y2) {
return Math.abs(x - x2) + Math.abs(y - y2);
}
static long fib[];
static long fib(int n) {
if (n == 1 || n == 0) {
return 1;
}
if (fib[n] != -1) {
return fib[n];
} else
return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod);
}
static class Point implements Comparable<Point>{
long x, y;
Point(long counth, long counts) {
x = counth;
y = counts;
}
@Override
public int compareTo(Point p )
{
return Long.compare(p.y*1l*x, p.x*1l*y);
}
}
static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N))
{
TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers
int idx = 0, p = primes.get(idx);
while (p * p <= N) {
while (N % p == 0) {
factors.add((long) p);
N /= p;
}
if (primes.size() > idx + 1)
p = primes.get(++idx);
else
break;
}
if (N != 1) // last prime factor may be > sqrt(N)
factors.add(N); // for integers whose largest prime factor has a power of 1
return factors;
}
static boolean visited[];
/**
* static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>();
* q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0;
* while(!q.isEmpty()) {
*
* int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) {
* maxcost=Math.max(maxcost, v.cost);
*
*
*
* if(!visited[v.v]) {
*
* visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost,
* v.cost); } }
*
* } return maxcost; }
**/
static boolean[] vis2;
static boolean f2 = false;
static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x
// r)
{
long[][] C = new long[p][r];
for (int i = 0; i < p; ++i) {
for (int j = 0; j < r; ++j) {
for (int k = 0; k < q; ++k) {
C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod;
C[i][j] %= mod;
}
}
}
return C;
}
public static int[] schuffle(int[] a2) {
for (int i = 0; i < a2.length; i++) {
int x = (int) (Math.random() * a2.length);
int temp = a2[x];
a2[x] = a2[i];
a2[i] = temp;
}
return a2;
}
static boolean vis[];
static TreeSet<Integer> set = new TreeSet<Integer>();
static long modPow(long ways, long count, long mod) // O(log e)
{
ways %= mod;
long res = 1;
while (count > 0) {
if ((count & 1) == 1)
res = (res * ways) % mod;
ways = (ways * ways) % mod;
count >>= 1;
}
return res % mod;
}
static long gcd(long l, long o) {
if (o == 0) {
return l;
}
return gcd(o, l % o);
}
static int[] isComposite;
static int[] valid;
static ArrayList<Integer> primes;
static ArrayList<Integer> l1;
static TreeSet<Integer> primus = new TreeSet<Integer>();
static void sieveLinear(int N)
{
int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i
for(int i = 2; i <= N; ++i)
{
if(lp[i] == 0)
{
primus.add(i);
lp[i] = i;
}
int curLP = lp[i];
for(int p: primus)
if(p > curLP || p * i > N)
break;
else
lp[p * i] = i;
}
}
public static long[] schuffle(long[] a2) {
for (int i = 0; i < a2.length; i++) {
int x = (int) (Math.random() * a2.length);
long temp = a2[x];
a2[x] = a2[i];
a2[i] = temp;
}
return a2;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
public int[] nxtArr(int n) throws IOException {
int[] ans = new int[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
}
public static int[] sortarray(int a[]) {
schuffle(a);
Arrays.sort(a);
return a;
}
public static long[] sortarray(long a[]) {
schuffle(a);
Arrays.sort(a);
return a;
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 295d2d0f0c5b7d84bdd7aeb23c082741 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
public static void main(String[] args) throws Exception {
PrintWriter pw = new PrintWriter(System.out);
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while(t--!=0) {
int n = s.nextInt();
String a = s.next();
String b = s.next();
ArrayList<HashSet<Integer>> arr = new ArrayList<HashSet<Integer>>();
for(int i=0;i<20;i++) {
arr.add(new HashSet<Integer>());
}
int ans = 0;
for(int i=0;i<n;i++) {
char c_a = a.charAt(i);
char c_b = b.charAt(i);
if(c_a != c_b) {
if(c_a > c_b) {
ans = -1;
break;
}else {
arr.get(c_a - 97).add(i);
}
}
}
if(ans != -1) {
for(int i=0;i<20;i++) {
HashSet<Integer> set = arr.get(i);
char c_min = 'u';
Iterator<Integer> it = set.iterator();
while(it.hasNext()) {
int p = it.next();
char cc = b.charAt(p);
if(cc < c_min) {
c_min = cc;
}
}
if(c_min == 'u') {
continue;
}
ans++;
HashSet<Integer> set2 = arr.get(c_min-97);
Iterator<Integer> itt = set.iterator();
while(itt.hasNext()) {
int p = itt.next();
if(b.charAt(p) != c_min) {
set2.add(p);
}
}
}
}
pw.println(ans);
}
pw.flush();
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | ccbc9e4795c9941aa872e89651e8fb13 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
public static void main(String args[]) throws Exception {
BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bu.readLine());
StringBuilder sb = new StringBuilder();
inner:while (t-- > 0) {
int n = Integer.parseInt(bu.readLine());
char[]a = bu.readLine().toCharArray();
char [] b = bu.readLine().toCharArray();
for (int pos = 0; pos < n; pos++) {
if (a[pos] > b[pos]) {
sb.append("-1\n");
continue inner;
}
}
int operations = 0;
for (char ch = 'a'; ch < 'z'+1; ch++) {
char minChar='z'+1;
boolean check = false;
for (int pos = 0; pos < n; pos++) {
if (a[pos]!=b[pos] && a[pos]==ch) {
minChar = (char) Math.min(minChar, b[pos]);
check = true;
}
}
for (int pos = 0; pos < n; pos++) {
if (a[pos]!=b[pos] && a[pos]==ch)
a[pos] = minChar;
}
if (check)
operations++;
}
sb.append(operations+"\n");
}
System.out.print(sb);
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | b09ea1306ae2a7ce86b94bb71d3805ea | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
public class Main7{
static public void main(String args[])throws IOException{
int tt=i();
StringBuilder sb=new StringBuilder();
for(int ttt=1;ttt<=tt;ttt++){
int n=i();
String s=s();
String s1=s();
int flag=0;
for(int i=0;i<n;i++){
if(s.charAt(i)-'a'>s1.charAt(i)-'a'){
flag=1;
}
}
if(flag==1){
sb.append("-1\n");
}else{
ArrayList<ArrayList<Integer>> ar=new ArrayList<>();
for(int i=0;i<26;i++){
ar.add(new ArrayList<>());
}
for(int i=0;i<n;i++){
if(s.charAt(i)!=s1.charAt(i)){
ar.get(s.charAt(i)-'a').add(i);
}
}
long ans=0;
for(int i=0;i<26;i++){
ArrayList<Integer> tmp=ar.get(i);
if(tmp.size()>0){
int min=26;
for(int j=0;j<tmp.size();j++){
min=Math.min(min,s1.charAt(tmp.get(j))-'a');
}
ArrayList<Integer> next=new ArrayList<>();
for(int j=0;j<tmp.size();j++){
if(min!=s1.charAt(tmp.get(j))-'a'){
next.add(tmp.get(j));
}
}
ar.get(min).addAll(next);
ans++;
}
}
sb.append(ans+"\n");
}
}
System.out.print(sb.toString());
}
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
static ArrayList<ArrayList<Integer>> graph;
static int mod=1000000007;
static class Pair{
int x;
int y;
Pair(int x,int y){
this.x=x;
this.y=y;
}
/*@Override
public int hashCode()
{
final int temp = 14;
int ans = 1;
ans =x*31+y*13;
return (int)ans;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (this.getClass() != o.getClass()) {
return false;
}
Pair other = (Pair)o;
if (this.x != other.x || this.y!=other.y) {
return false;
}
return true;
}*/
}
public static long[] sort(long[] a){
int n=a.length;
ArrayList<Long> ar=new ArrayList<>();
for(int i=0;i<a.length;i++){
ar.add(a[i]);
}
Collections.sort(ar);
for(int i=0;i<n;i++){
a[i]=ar.get(i);
}
return a;
}
public static long pow(long a, long b){
long result=1;
while(b>0){
if (b % 2 != 0){
result=(result*a);
b--;
}
a=(a*a);
b /= 2;
}
return result;
}
public static long gcd(long a, long b){
if (a == 0){
return b;
}
return gcd(b%a, a);
}
public static long lcm(long a, long b){
return a*(b/gcd(a,b));
}
public static long l(){
String s=in.String();
return Long.parseLong(s);
}
public static void pln(String value){
System.out.println(value);
}
public static int i(){
return in.Int();
}
public static String s(){
return in.String();
}
}
class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars== -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
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 String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.Int();
return array;
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | b7f7e6357107cd789dbc88fb2d5d7c5e | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.math.*;
public class Main{
public static int solve(String A,String B,int n){
char[] a = A.toCharArray();
char[] b = B.toCharArray();
String s = "abcdefghijklmnopqrst";
for(int i = 0 ; i < n ; i++){
if(a[i] > b[i]){
return -1;
}
}
int ans = 0;
for(int i = 0 ; i < s.length() ; i++){
char min = 'u';
for(int j = 0 ; j < n ; j++){
if(s.charAt(i) == a[j] && b[j] > s.charAt(i)){
min = (b[j] < min)?b[j]:min;
}
}
if(min != 'u'){
ans++;
for(int j = 0 ; j < n ; j++){
if(s.charAt(i) == a[j] && b[j] > s.charAt(i)){
a[j] = min;
}
}
}
}
return ans;
}
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
while(c-- > 0){
int n = sc.nextInt();
String A = sc.next();
String B = sc.next();
System.out.println(solve(A,B,n));
}
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 10ae6207b7c39b6694eb4df5ec74f00b | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.math.*;
public class Main{
public static int solve(String A,String B,int n){
char[] a = A.toCharArray();
char[] b = B.toCharArray();
String s = "abcdefghijklmnopqrst";
for(int i = 0 ; i < n ; i++){
if(a[i] > b[i]){
return -1;
}
}
int ans = 0;
for(char x = 'a' ; x <= 't' ; x++){
char y = 'z';
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0 ; i < n ; i++){
if(a[i] == x && b[i] != x){
y = (b[i] < y)?b[i]:y;
list.add(i);
}
}
if(y != 'z'){
ans++;
for(int i = 0 ; i < n ; i++){
if(a[i] == x && b[i] != x)
a[i] = y;
}
}
}
return ans;
}
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
while(c-- > 0){
int n = sc.nextInt();
String A = sc.next();
String B = sc.next();
System.out.println(solve(A,B,n));
}
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 5b0c636df35b9f9bb12ac08cb7654cf9 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.math.*;
public class Main{
public static int solve(String A,String B,int n){
char[] a = A.toCharArray();
char[] b = B.toCharArray();
String s = "abcdefghijklmnopqrst";
for(int i = 0 ; i < n ; i++){
if(a[i] > b[i]){
return -1;
}
}
int ans = 0;
for(int i = 0 ; i < s.length() ; i++){
char min = 'u';
for(int j = 0 ; j < n ; j++){
if(s.charAt(i) == a[j] && b[j] > s.charAt(i)){
min = (b[j] < min)?b[j]:min;
}
}
if(min != 'u'){
ans++;
for(int j = 0 ; j < n ; j++){
if(s.charAt(i) == a[j] ){
a[j] = min;
}
}
}
}
return ans;
}
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
while(c-- > 0){
int n = sc.nextInt();
String A = sc.next();
String B = sc.next();
System.out.println(solve(A,B,n));
}
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | f9ae29152caa190a03ec2e2b4a406ca1 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.math.*;
public class Main{
public static int solve(String A,String B,int n){
char[] a = A.toCharArray();
char[] b = B.toCharArray();
String s = "abcdefghijklmnopqrst";
for(int i = 0 ; i < n ; i++){
if(a[i] > b[i]){
return -1;
}
}
int ans = 0;
for(char x = 'a' ; x <= 't' ; x++){
char y = 'z';
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0 ; i < n ; i++){
if(a[i] == x && b[i] != x){
y = (b[i] < y)?b[i]:y;
list.add(i);
}
}
if(y != 'z'){
ans++;
for(int p:list)
a[p] = y;
}
}
return ans;
}
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
while(c-- > 0){
int n = sc.nextInt();
String A = sc.next();
String B = sc.next();
System.out.println(solve(A,B,n));
}
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 4dd5463e61a0771e1b0f4a0885cd751c | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.math.*;
public class Main{
public static int solve(String A,String B,int n){
char[] a = A.toCharArray();
char[] b = B.toCharArray();
String s = "abcdefghijklmnopqrst";
for(int i = 0 ; i < n ; i++){
if(a[i] > b[i]){
return -1;
}
}
int ans = 0;
for(char x = 'a' ; x <= 't' ; x++){
char y = 'z';
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0 ; i < n ; i++){
if(a[i] == x && b[i] > x){
y = (b[i] < y)?b[i]:y;
list.add(i);
}
}
if(y != 'z'){
ans++;
for(int p:list)
a[p] = y;
}
}
return ans;
}
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
while(c-- > 0){
int n = sc.nextInt();
String A = sc.next();
String B = sc.next();
System.out.println(solve(A,B,n));
}
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | d7a7df220e5be8271e3eca9aa6fe9242 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static class node{
int a, b;
public node(int x, int y) {
a = x;
b = y;
}
}
static class Pair implements Comparable<Pair>{
int a;
int b;
// int ind;
// public Pair(int x, long y) {a = x;b=y;}
public Pair(int x, int y) {a = x;b=y;}
// public Pair(int x,int y, int z){a=x;b=y;ind = z;}
public int compareTo(Pair p){
return b - p.b;
}
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + a;
// result = prime * result + b;
//
// return result;
// }
// @Override
// public boolean equals(Object obj) {
// Pair cur = (Pair)obj;
// if((a==cur.a && b==cur.b))return true;
// return false;
// }
}
static class cell{
int a, b;
public cell(int x, int y) {
a = x;
b = y;
}
}
static class TrieNode{
TrieNode left, right;
int cnt;
public TrieNode() {
cnt = 0;
}
}
public static long gcd(long a,long b)
{
if(a<b)
return gcd(b,a);
if(b==0)
return a;
return gcd(b,a%b);
}
static long lcm(int a,int b) {
return a*b / gcd(a,b);
}
public static void main(String[] args) throws Exception {
new Thread(null, null, "Anshum Gupta", 99999999) {
public void run() {
try {
solve();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static long pow(long x,long y){
if(y == 0)return 1;
if(y==1)return x;
long a = pow(x,y/2);
a = (a*a)%mod;
if(y%2==0){
return a;
}
return (a*x)%mod;
}
static long[]fact,inv_fact;
static long my_inv(long a) {
return pow(a,mod-2);
}
static long bin(int a,int b) {
if(a < b || a<0 || b<0)return 0;
return ((fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod;
}
static void make_facts() {
fact=new long[mxN];
inv_fact = new long[mxN];
fact[0]=inv_fact[0]=1L;
for(int i=1;i<mxN;i++) {
fact[i] = (i*fact[i-1])%mod;
inv_fact[i] = my_inv(fact[i]);
}
}
static void lazy(int st, int e, int tn) {
if(lazy[tn] != INF) {
tree[tn] = Math.min(tree[tn], lazy[tn]);
if(st != e) {
lazy[2*tn] = Math.min(lazy[2*tn], lazy[tn]);
lazy[2*tn+1] = Math.min(lazy[2*tn+1], lazy[tn]);
}
lazy[tn] = INF;
}
}
static void update(int ind, int val, int st, int e, int tn) {
if(st == e) {
tree[tn] = val;
return;
}
int mid = (st + e) >> 1;
if(ind <= mid)
update(ind, val, st, mid, 2*tn);
else
update(ind, val, mid+1, e, 2*tn+1);
tree[tn] = Math.min(tree[2*tn], tree[2*tn+1]);
}
static int query(int l, int r, int st, int e, int tn) {
if(st > r || e < l)return INF;
if(st >= l && e <= r) {
return tree[tn];
}
int mid = (st + e) >> 1;
int x = query(l, r, st, mid, 2 * tn);
int y = query(l, r, mid+1, e, 2 * tn + 1);
return Math.min(x, y);
}
static final long mxx = (long)(1e18+5);
static final int mxN = (int)(1e5);
static final int mxV = (int)(1e5+5);
static final long mod = 998244353;//(long)(1e9+7); //
static int[]tree, lazy;
static final int INF = (int)1e9+5;
static ArrayList<ArrayList<Integer>> adj;
static boolean[] dp2;
static int n, m, b, c, q, t, k, l;
static int[]d;
static int[][]cnt;
static boolean[]vis;
static void dfs(int sv) {
vis[sv] = true;
for(Integer x : adj.get(sv)) {
if(!vis[x])
dfs(x);
}
}
public static void solve() throws Exception {
// solve the problem here
MyScanner s = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
int tc = s.nextInt();
while(tc-->0){
n = s.nextInt();
String a = s.next();
String b = s.next();
boolean ok = true;
adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=20;i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<n; i++) {
if(a.charAt(i) > b.charAt(i)) {
out.println("-1");
ok = false;
break;
}
adj.get(a.charAt(i) - 'a').add(b.charAt(i) - 'a');
adj.get(b.charAt(i) - 'a').add(a.charAt(i) - 'a');
}
if(!ok)continue;
int ans = 20;
vis = new boolean[20];
for(int i=0 ;i<20; i++) {
if(!vis[i]) {
dfs(i);
ans--;
}
}
out.println(ans);
}
out.flush();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | bc90817123f389583c92af375bab0dc0 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author sofiane
*/
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 {
private void dfs(boolean[] vis, boolean[][] adj, HashSet<Integer> comp, int c) {
vis[c] = true;
comp.add(c);
for (int i = 0; i < 20; i++) {
if (!adj[c][i] || vis[i])
continue;
else {
dfs(vis, adj, comp, i);
}
}
return;
}
public void solve(int testNumber, Scanner in, PrintWriter out) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
String A = in.next();
String B = in.next();
int ans = 0;
for (int i = 0; i < n; i++) {
if (A.charAt(i) > B.charAt(i)) {
ans = -1;
break;
}
}
if (ans == -1) {
out.println(-1);
continue;
}
boolean[] vis = new boolean[20];
boolean[][] adj = new boolean[20][20];
for (int i = 0; i < n; i++) {
if (A.charAt(i) != B.charAt(i)) {
int f = A.charAt(i) - 'a', l = B.charAt(i) - 'a';
adj[f][l] = adj[l][f] = true;
}
}
for (int i = 0; i < n; i++) {
if (A.charAt(i) != B.charAt(i) && !vis[A.charAt(i)-'a']) {
HashSet<Integer> comp = new HashSet<>();
dfs(vis, adj, comp, A.charAt(i) - 'a');
ans += comp.size() - 1;
}
}
out.println(ans);
}
}
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | d90c832eee75166d316f8102c11c753f | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
public class TestClass {
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final int readInt() throws IOException {
return (int) readLong();
}
public final long readLong() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
if (c == -1) throw new IOException();
}
boolean negative = false;
if (c == '-') {
negative = true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return negative ? -res : res;
}
public final int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public final long[] readLongArray(int size) throws IOException {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static long mulmod(long a, long b,
long mod) {
long res = 0; // Initialize result
a = a % mod;
while (b > 0) {
// If b is odd, add 'a' to result
if (b % 2 == 1) {
res = (res + a) % mod;
}
// Multiply 'a' with 2
a = (a * 2) % mod;
// Divide b by 2
b /= 2;
}
// Return result
return res % mod;
}
static long pow(long a, long b, long MOD) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 == 1) {
x = (x * y);
if (x > MOD) x %= MOD;
}
y = (y * y);
if (y > MOD) y %= MOD;
b /= 2;
}
return x;
}
static long[] f = new long[100011];
static long InverseEuler(long n, long MOD) {
return pow(n, MOD - 2, MOD);
}
static long C(int n, int r, long MOD) {
return (f[n] * ((InverseEuler(f[r], MOD) * InverseEuler(f[n - r], MOD)) % MOD)) % MOD;
}
static int[] h = {0, 0, -1, 1};
static int[] v = {1, -1, 0, 0};
static class Pair2 {
public long cost;
int node;
public Pair2(long cos, int node) {
this.cost = cos;
this.node = node;
}
}
static long l[][] = new long[100011][6];
static long compute_hash(String s) {
int p = 31;
int m = 1000000007;
long hash_value = 0;
long p_pow = 1;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;
p_pow = (p_pow * p) % m;
}
return hash_value;
}
public static class SegmentTree {
int[][] tree;
long[] sumtree;
long[] count;
int n;
public SegmentTree(int[] nodes) {
tree = new int[nodes.length * 4][31];
sumtree = new long[nodes.length * 4];
count = new long[nodes.length * 4];
n = nodes.length;
build(0, n - 1, 0, nodes);
}
private void build(int l, int r, int pos, int[] nodes) {
if (l == r) {
sumtree[pos] = nodes[l];
boolean neg = false;
if (nodes[l] < 0) {
neg = true;
}
count[pos] = 1;
if (neg) {
count[pos] = -1;
}
for (int i = 0; i < 31; ++i) {
tree[pos][i] = (neg ? -1 : 1) * (((nodes[l] < 0 ? -1 * nodes[l] : nodes[l]) & (1 << i)) != 0 ? 1 : 0);
}
return;
}
int mid = (l + r) / 2;
build(l, mid, 2 * pos + 1, nodes);
build(mid + 1, r, 2 * pos + 2, nodes);
sumtree[pos] = sumtree[2 * pos + 1] + sumtree[2 * pos + 2];
count[pos] = count[2 * pos + 1] + count[2 * pos + 2];
for (int i = 0; i < 31; ++i) {
tree[pos][i] = tree[2 * pos + 1][i] + tree[2 * pos + 2][i];
}
}
public long getSum(int l, int r) {
return getSumUtil(0, n-1, 0, l, r);
}
private long getSumUtil(int l, int r, int pos, int ql, int qr) {
if (l > qr || r < ql) return 0L;
if (l >= ql && r <= qr) {
return sumtree[pos];
}
int mid = (l + r) >> 1;
return getSumUtil(l, mid, 2 * pos + 1, ql, qr) + getSumUtil(mid + 1, r, 2 * pos + 2, ql , qr);
}
public long getCount(int l, int r) {
return getCountUtil(0, n-1, 0, l, r);
}
private long getCountUtil(int l, int r, int pos, int ql, int qr) {
if (l > qr || r < ql) return 0L;
if (l >= ql && r <= qr) {
return count[pos];
}
int mid = (l + r) >> 1;
return getCountUtil(l, mid, 2 * pos + 1, ql, qr) + getCountUtil(mid + 1, r, 2 * pos + 2, ql , qr);
}
public int[] getBitCount(int l, int r) {
return getBitCountUtil(0, n-1, 0, l, r);
}
private int[] getBitCountUtil(int l, int r, int pos, int ql, int qr) {
if (l > qr || r < ql) return null;
if (l >= ql && r <= qr) {
int[] returs = new int[30];
for (int i = 0; i < 30; ++i) {
returs[i] = tree[pos][i];
}
return returs;
}
int mid = (l + r) >> 1;
int[] left = getBitCountUtil(l, mid, 2 * pos + 1, ql, qr);
int[] right = getBitCountUtil(mid + 1, r, 2 * pos + 2, ql, qr);
if (left == null) return right;
if (right == null) return left;
// int[] returs = new int[30];
for (int i = 0; i < 30; ++i) {
left[i] += right[i];
}
return left;
}
}
static int counter = 0;
static int[] In;
static int[] Out;
private static int[] flatten;
private static int[][] lca;
static long answer = 0;
static int VISITED = 1;
static int VISITING = 2;
public static void main(String[] args) throws Exception {
//https://i...content-available-to-author-only...e.com/ebRGa6
InputReader in = new InputReader(System.in);
// l[0][0] = 1;
// for (int i = 1; i < 100008; i++) {
// // Set every nCr = 1 where r = 0
// l[i][0] = 1;
// for (int j = 1; j < 5; j++) {
//
// // Value for the current cell of Pascal's triangle
// l[i][j] = (l[i - 1][j - 1] + l[i - 1][j]) % 1000000007;
// }
// }
int t = in.readInt();
while (t-- > 0) {
int n = in.readInt();
String a = in.readString();
String b = in.readString();
List<Set<Integer>> occ = new ArrayList<>();
for (int i = 0; i < 20; ++i) {
occ.add(new HashSet<>());
}
boolean hasAns = true;
for (int i = 0; i < a.length(); ++i) {
if (b.charAt(i) < a.charAt(i)) {
hasAns = false;
break;
}
occ.get(a.charAt(i) - 'a').add(b.charAt(i) - 'a');
}
if (hasAns) {
int answer = 0;
for (int i = 0; i < 20; ++i) {
Set<Integer> thisChar = occ.get(i);
int j = i+1;
for (; j < 20; ++j) {
if (thisChar.contains(j)) break;
}
if (j != 20) {
occ.get(j).addAll(thisChar);
++answer;
}
}
System.out.println(answer);
} else {
System.out.println(-1);
}
}
}
private static long solve(int pos, int curK, int k, int[] arr, int m, long[][] dp) {
System.out.println(pos);
if (pos == arr.length) {
if (curK == k) return 0;
return -1000000000000L;
}
if (curK > k) return -1000000000000L;
if (dp[pos][curK] != -1) return dp[pos][curK];
long with = -1000000000000L;
if (curK < k)
with = solve(pos + 1, curK + 1, k, arr, m, dp) + arr[pos] * (((curK + 1) % m));
long without = solve(pos + 1, curK, k, arr, m, dp);
return dp[pos][curK] = Math.max(with, without);
}
static int countFreq(String pattern, String text) {
int m = pattern.length();
int n = text.length();
int res = 0;
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) {
if (text.charAt(i + j) != pattern.charAt(j)) {
break;
}
}
if (j == m) {
res++;
j = 0;
}
}
return res;
}
private static void dfs(List<List<Integer>> g, int node, int last, int[] val, int[] traversal, int depth) {
In[node] = counter;
flatten[counter++] = val[node];
traversal[depth] = node;
for (int i = 0; depth - (1 << i) >= 0; ++i) {
lca[node][i] = traversal[depth - (1 << i)];
}
for (int i = 0; i < g.get(node).size(); ++i) {
int ntb = g.get(node).get(i);
if (ntb != last) {
dfs(g, ntb, node, val, traversal, depth + 1);
}
}
Out[node] = counter;
flatten[counter++] = -1 * val[node];
}
private static void preprocess(int pos, int[][] pre, List<List<Integer>> tree, int[] traverse, int depth, int last, int[] tin, int[] tout) {
tin[pos] = counter++;
traverse[depth] = pos;
for (int i = 0; depth - (1 << i) >= 0; ++i) {
pre[pos][i] = traverse[depth - (1 << i)];
}
for (int i = 0; i < tree.get(pos).size(); ++i) {
if (tree.get(pos).get(i) != last)
preprocess(tree.get(pos).get(i), pre, tree, traverse, depth + 1, pos, tin, tout);
}
tout[pos] = counter++;
}
static int gcd(int a, int b) {
while (b != 0) {
int t = a;
a = b;
b = t % b;
}
return a;
}
static boolean submit = true;
static void debug(String s) {
if (!submit)
System.out.println(s);
}
static void debug(int s) {
if (!submit)
System.out.println(s);
}
class Solution {
public class Pair {
public int start, end, c;
public Pair(int start, int end, int c) {
this.start = start;
this.end = end;
this.c = c;
}
}
public List<String> maxNumOfSubstrings(String s) {
int n = s.length();
List<String> answer = new ArrayList<>();
Map<Integer, Integer> f = new HashMap<>();
Map<Integer, Integer> l = new HashMap<>();
for (int i = 0; i < n; ++i) {
if (!f.containsKey(s.charAt(i) - 'a')) {
f.put(s.charAt(i) - 'a', i);
}
}
for (int i = n - 1; i >= 0; --i) {
if (!l.containsKey(s.charAt(i) - 'a')) {
l.put(s.charAt(i) - 'a', i);
}
}
List<Pair> p = new ArrayList<>();
for (int i = 0; i < 26; ++i) {
int start = f.getOrDefault(i, -1);
int end = l.getOrDefault(i, -1);
if (start != -1) {
for (int j = start; j < end; ++j) {
end = Math.max(end, l.get(s.charAt(j) - 'a'));
if (start > f.get(s.charAt(j) - 'a')) {
start = Math.min(start, f.get(s.charAt(j) - 'a'));
j = start;
}
}
p.add(new Pair(start, end, i));
}
}
p.sort(Comparator.comparingInt(a -> a.end));
int lastEnd = 0;
for (Pair pair : p) {
if (pair.start >= lastEnd) {
answer.add(s.substring(pair.start, pair.end + 1));
lastEnd = pair.end;
}
}
return answer;
}
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 8fd26378f2316708258b0630fad6c31a | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public final class C {
private static final class UnionFind {
private final int[] parent;
private final int[] size;
private int count;
private UnionFind(int n) {
parent = new int[n];
size = new int[n];
count = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int find(int p) {
// path compression
while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
public void union(int p, int q) {
final int rootP = find(p);
final int rootQ = find(q);
if (rootP == rootQ) {
return;
}
// union by size
if (size[rootP] > size[rootQ]) {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
} else {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
count--;
}
public int count() { return count; }
public int[] size() { return size; }
}
public static void main(String[] args) {
final Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
final int t = Integer.parseInt(in.nextLine());
outer:
for (int x = 0; x < t; x++) {
final int n = Integer.parseInt(in.nextLine());
final String s1 = in.nextLine();
final String s2 = in.nextLine();
final UnionFind uf = new UnionFind(20);
int res = 0;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) > s2.charAt(i)) {
System.out.println(-1);
continue outer;
}
if (uf.find(s1.charAt(i) - 'a') != uf.find(s2.charAt(i) - 'a')) {
uf.union(s1.charAt(i) - 'a', s2.charAt(i) - 'a');
res++;
}
}
System.out.println(res);
}
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 80d6fafe86f0b886005b4660743bc1ba | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Set;
public class Main {
private static final String NO = "NO";
private static final String YES = "YES";
InputStream is;
PrintWriter out;
String INPUT = "";
private List<Integer>[] g;
private static final long MOD = 998244353;
private static final int INF = Integer.MAX_VALUE;
void solve() {
int T = ni();
for (int i = 0; i < T; i++)
solve(i);
}
void solve(int T) {
int n = ni();
char a[] = ns().toCharArray();
char b[] = ns().toCharArray();
boolean chk[][] = new boolean[20][20];
for (int i = 0; i < n; i++) {
if (a[i] > b[i]) {
out.println(-1);
return;
}
if (a[i] < b[i])
chk[a[i] - 'a'][b[i] - 'a'] = true;
}
int ans = 0;
for (int i = 0; i < 20; i++) // a->b
for (int j = i + 1; j < 20; j++) //
if (chk[i][j]) {
ans++;
// checking exists b->c && a->c
for (int k = j + 1; k < 20; k++)
if (chk[i][k])
chk[j][k] = true;
break;
}
out.println(ans);
}
// a^b
long power(long a, long b) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 != 0) {
x = (x * y) % MOD;
}
y = (y * y) % MOD;
b /= 2;
}
return x % MOD;
}
private long gcd(long a, long b) {
while (a != 0) {
long tmp = b % a;
b = a;
a = tmp;
}
return b;
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private boolean vis[];
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n) {
if (!(isSpaceChar(b)))
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private List<Integer> na2(int n) {
List<Integer> a = new ArrayList<Integer>();
for (int i = 0; i < n; i++)
a.add(ni());
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private long[][] nl(int n, int m) {
long[][] a = new long[n][];
for (int i = 0; i < n; i++)
a[i] = nl(m);
return a;
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | f46fcaf3c7397bd9e5f00127fa12f922 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
static long mod = (long)(1e9+7);
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static void main(String sp[])throws IOException{
Scanner sc = new Scanner(System.in);
//FastReader sc = new FastReader();
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
String s1 = sc.next();
String s2 = sc.next();
boolean flag=false;
for(int i=0;i<n;i++){
if(s1.charAt(i)>s2.charAt(i)){
System.out.println("-1");
flag=true;
break;
}
}
if(flag==true){
continue;
}
int count = 0;
char arr[] = s1.toCharArray();
for(char ch='a';ch<='z';ch++){
char next = 'z';
for(int i=0;i<n;i++){
if(arr[i]==ch && arr[i]!=s2.charAt(i)){
next = (char)Math.min(next, s2.charAt(i));
}
}
if(next!='z'){
count++;
for(int i=0;i<n;i++){
if(arr[i]==ch && arr[i]!=s2.charAt(i)){
arr[i]=next;
}
}
}
}
System.out.println(count);
}
}
public static ArrayList<Integer> primefactor(int n){
int sqrt = (int)Math.sqrt(n);
ArrayList<Integer> al = new ArrayList<>();
while(n%2==0){
al.add(2);
n/=2;
}
for(int i=3;i<=sqrt;i+=2){
while(n%i==0){
al.add(i);
n/=i;
}
}
if(n>2)
al.add(n);
return al;
}
public static long sum(long val){
long fg =0 ;
while(val!=0){
fg+=val%10;
val/=10;
}
return fg;
}
public static ArrayList<Integer> factor(int n){
int sqrt = (int)Math.sqrt(n);
ArrayList<Integer> al = new ArrayList<>();
for(int i=1;i<=sqrt;i++){
if(n%i!=0)
continue;
int first = i;
int second = n/i;
al.add(i);
if(first==second){
continue;
}
al.add(n/i);
}
return al;
}
public static long power(long x, long y)
{
long temp;
if( y == 0)
return 1l;
temp = power(x, y/2);
if (y%2 == 0)
return (temp*temp)%mod;
else
return ((x*temp)%mod*temp)%mod;
}
public static ArrayList<Integer> comp(){
ArrayList<Integer> al = new ArrayList<>();
int n = (int)2e5;
boolean arr[] = new boolean[n+1];
int sqrt = (int)Math.sqrt(n);
for(int i=2;i<=sqrt;i++){
if(arr[i]==false){
for(int j=i*i;j<=n;j+=i){
arr[j]=true;
}
}
}
for(int i=2;i<=n;i++){
if(arr[i]==false)
al.add(i);
}
return al;
}
public static class pair{
long x;
long y;
long diff;
pair(long x, long y, long d){
this.x=x;
this.y=y;
diff = d;
}
}
public static class comp implements Comparator<pair>{
public int compare(pair o1, pair o2){
return Long.valueOf(o1.diff).compareTo(Long.valueOf(o2.diff));
}
}
static class Node{
int node;
int d;
ArrayList<Integer> al = new ArrayList<>();
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static class FastReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 2153d0d58535fcd64fe1c776549e6610 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static char s[], t[];
static void solve() throws Exception{
int n = sc.nextInt(), ans = 0;
s = sc.nextLine().toCharArray();
t = sc.nextLine().toCharArray();
Queue<Integer> adj[] = new LinkedList[20];
for(int i = 0; i < 20; i++) adj[i] = new LinkedList<>();
for(int i = 0; i < n; i++) {
adj[s[i] - 'a'].add(i);
}
boolean flag = true;
for(int i = 0; i < 20; i++) {
ArrayList<Integer> indices = new ArrayList<>();
for(int j = 0; j < n; j++) {
if(t[j] == (char) ('a' + i)) {
indices.add(j);
}
}
HashSet<Character> st = new HashSet<>();
for(int idx : indices) {
if(s[idx] == t[idx]) continue;
st.add(s[idx]);
flag &= s[idx] < t[idx];
}
ans += st.size();
for(char c : st) {
int u = c - 'a';
while(!adj[u].isEmpty()) {
int v = adj[u].poll();
s[v] = (char) ('a' + i);
adj[i].add(v);
}
}
}
out.println(flag ? ans : -1);
}
public static void main(String[] args) throws Exception {
int t = sc.nextInt();
while(t-- > 0) {
solve();
}
out.close();
}
}
class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | a38e23eec146458b4ce5b0d3cf1497f5 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.*;
/**
* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
*/
public class Main {
public static void main(String[] args) {
// Write your solution here
FastReader in = new FastReader();
int tt = in.nextInt();
while(tt-- > 0){
int n = in.nextInt();
int res = 0;
int f = 0;
String s1 = in.nextLine();
String s2 = in.nextLine();
char[] s = s1.toCharArray();
char[] t = s2.toCharArray();
for(int i = 0; i < n; i++){
if(s[i] > t[i]){
f = 1;
break;
}
}
if(f == 1){
System.out.println(-1);
} else{
for(char i = 'a'; i < 't'; i++){
List<Integer> l = new ArrayList<>();
for(int j = 0; j < n; j++){
if(s[j] == i && i < t[j]){ //all same chars in s which are smaller than chars of t at their position
l.add(j); //store thier indices
}
}
char min = 't';
for(int idx : l){
min = (char)Math.min(min, t[idx]);
}
for(int idx : l){
s[idx] = min;
}
if(!l.isEmpty()) res++;
}
System.out.println(res);
}
}
}
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 | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 84a4ba6d346b8d01c771e949cc38efc5 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
static long mod = (long)(1e9+7);
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static void main(String sp[])throws IOException{
Scanner sc = new Scanner(System.in);
//FastReader sc = new FastReader();
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
String s1 = sc.next();
String s2 = sc.next();
boolean flag=false;
for(int i=0;i<n;i++){
if(s1.charAt(i)>s2.charAt(i)){
System.out.println("-1");
flag=true;
break;
}
}
if(flag==true){
continue;
}
int count = 0;
char arr[] = s1.toCharArray();
for(char ch='a';ch<='z';ch++){
char next = 'z';
for(int i=0;i<n;i++){
if(arr[i]==ch && arr[i]!=s2.charAt(i)){
next = (char)Math.min(next, s2.charAt(i));
}
}
if(next!='z'){
count++;
for(int i=0;i<n;i++){
if(arr[i]==ch && arr[i]!=s2.charAt(i)){
arr[i]=next;
}
}
}
}
System.out.println(count);
}
}
public static ArrayList<Integer> primefactor(int n){
int sqrt = (int)Math.sqrt(n);
ArrayList<Integer> al = new ArrayList<>();
while(n%2==0){
al.add(2);
n/=2;
}
for(int i=3;i<=sqrt;i+=2){
while(n%i==0){
al.add(i);
n/=i;
}
}
if(n>2)
al.add(n);
return al;
}
public static long sum(long val){
long fg =0 ;
while(val!=0){
fg+=val%10;
val/=10;
}
return fg;
}
public static ArrayList<Integer> factor(int n){
int sqrt = (int)Math.sqrt(n);
ArrayList<Integer> al = new ArrayList<>();
for(int i=1;i<=sqrt;i++){
if(n%i!=0)
continue;
int first = i;
int second = n/i;
al.add(i);
if(first==second){
continue;
}
al.add(n/i);
}
return al;
}
public static long power(long x, long y)
{
long temp;
if( y == 0)
return 1l;
temp = power(x, y/2);
if (y%2 == 0)
return (temp*temp)%mod;
else
return ((x*temp)%mod*temp)%mod;
}
public static ArrayList<Integer> comp(){
ArrayList<Integer> al = new ArrayList<>();
int n = (int)2e5;
boolean arr[] = new boolean[n+1];
int sqrt = (int)Math.sqrt(n);
for(int i=2;i<=sqrt;i++){
if(arr[i]==false){
for(int j=i*i;j<=n;j+=i){
arr[j]=true;
}
}
}
for(int i=2;i<=n;i++){
if(arr[i]==false)
al.add(i);
}
return al;
}
public static class pair{
long x;
long y;
long diff;
pair(long x, long y, long d){
this.x=x;
this.y=y;
diff = d;
}
}
public static class comp implements Comparator<pair>{
public int compare(pair o1, pair o2){
return Long.valueOf(o1.diff).compareTo(Long.valueOf(o2.diff));
}
}
static class Node{
int node;
int d;
ArrayList<Integer> al = new ArrayList<>();
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static class FastReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | c57f0e507f39fe6a65a82db7ba021b51 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | // https://codeforces.com/contest/1384/problem/C
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Solution
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader s=new FastReader();
int t = s.nextInt();
outer: while(t > 0){
int n = s.nextInt();
char[] a = s.next().toCharArray();
char[] b = s.next().toCharArray();
boolean[][] letters = new boolean[20][20];
for(int i = 0; i < n; i++) {
if(a[i] > b[i]){
System.out.println(-1);
t--;
continue outer;
}else {
letters[a[i] - 'a'][b[i] - 'a'] = true;
}
}
int count = 0;
for(int i = 0; i < 20; i++) {
int update = -1;
for(int j = 0; j < 20; j++) {
if(i == j) continue;
if(letters[i][j] && update == -1){
count++;
update = j;
}else if(letters[i][j]) {
letters[update][j] = true;
}
}
}
System.out.println(count);
t--;
}
}
} | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 530da957e690daf88acb3aedfe4a429a | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.io.*;
public class Question4 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int t = sc.nextInt();
while(t-->0) {
solve();
}
}
public static void solve() {
int n = sc.nextInt();
char[] a = sc.next().toCharArray();
char[] b = sc.next().toCharArray();
for(int i = 0;i < n;i++) {
if(a[i] > b[i]) {
System.out.println(-1);
return;
}
}
int moves = 0;
outer :
for(int i = 0;i < 26;i++) {
ArrayList<Integer> list = new ArrayList<Integer>();
char ch = (char)('a' + i);
char min = 'u';
for(int j = 0;j < n;j++) {
if(a[j] == ch && a[j] != b[j]) {
list.add(j);
if(b[j] < min)min = b[j];
}
}
if(list.isEmpty())continue outer;
moves++;
for(Integer ix : list) {
a[ix] = min;
}
}
System.out.println(moves);
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | ada9ca0c9c5eaa620c5048da06540535 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
import java.io.*;
public class Question4 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int t = sc.nextInt();
while(t-->0) {
solve();
}
}
public static void solve() {
int n = sc.nextInt();
char[] a = sc.next().toCharArray();
char[] b = sc.next().toCharArray();
char max = b[0];
for(int i = 0;i < n;i++) {
if(b[i] > max)max = b[i];
if(a[i] > b[i]) {
System.out.println(-1);
return;
}
}
int moves = 0;
for(int i = 0;i < 20;i++) {
ArrayList<Integer> list = new ArrayList<Integer>();
char ch = (char)('a' + i);
char min = max;
for(int j = 0;j < n;j++) {
if(a[j] == ch && a[j] != b[j]) {
list.add(j);
if(b[j] < min)min = b[j];
}
}
if(list.isEmpty())continue;
moves++;
for(Integer ix : list) {
a[ix] = min;
}
}
System.out.println(moves);
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 174f8472865d71644af294569d92bea2 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Task4 {
public static void main(String[] args) throws IOException {
new Task4().solve();
}
private void solve() throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(f.readLine());
for (int t1 = 0; t1 < t; t1++) {
int n = Integer.parseInt(f.readLine());
char[] seq1 = f.readLine().toCharArray();
char[] seq2 = f.readLine().toCharArray();
boolean impossible = false;
for (int i = 0; i < n; i++) {
if (seq2[i] - seq1[i] < 0) {
impossible = true;
break;
}
}
if (impossible) {
out.println(-1);
continue;
}
int[][] moves = new int[20][20];
for (int i = 0; i < n; i++) {
if (seq1[i] != seq2[i]) {
moves[seq2[i] - 'a'][seq1[i] - 'a']++;
}
}
int res = 0;
/*
for (int i = 0; i < 20; i++) {
boolean[] alreadySet = new boolean[20];
for (int j = 0; j < n; j++) {
if (seq1[j] == seq2[j]) continue;
if (seq1[j] - 'a' == i) {
boolean found = false;
for (int k = seq2[j] - 'a' - 1; k > i; k--) {
if (moves[seq2[j] - 'a'][k] != 0) {
found = true;
if (!alreadySet[k]) res++;
alreadySet[k] = true;
break;
}
}
if (!found && !alreadySet[seq2[j] - 'a']) {
alreadySet[seq2[j] - 'a'] = true;
res++;
}
}
}
} */
for (int i = 0; i < 20; i++) {
boolean[] alreadySet = new boolean[20];
Character min = null;
boolean areAllSame = true;
for (int j = 0; j < n; j++) {
if (seq1[j] == seq2[j]) continue;
if (seq1[j] - 'a' == i) {
areAllSame = false;
if (min == null || (seq2[j] - 'a') < (min - 'a')) {
min = seq2[j];
}
}
}
if (!areAllSame) {
res++;
for (int j = 0; j< n; j++) {
if (seq1[j] == seq2[j]) continue;
if (seq1[j] - 'a' == i) {
seq1[j] = min;
}
}
}
}
out.println(res);
}
out.close();
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 5f9cf5001924bb0c457d6a4ebc5e4d10 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.Scanner;
// https://codeforces.com/contest/1384/problem/C
public class C {
public static final Scanner INPUT = new Scanner(System.in);
public static void main(String[] args) {
int t = Integer.parseInt(INPUT.nextLine());
while (t > 0) {
t--;
int n = Integer.parseInt(INPUT.nextLine());
String a = INPUT.nextLine().trim();
String b = INPUT.nextLine().trim();
// System.out.println("n = " + n);
// System.out.println("a = " + a);
// System.out.println("b = " + b);
int[][] c = trans2matrix(a, b, n);
while (reduce(c)) {
}
System.out.println(counter(c));
}
}
private static final int N_SIZE = 20;
private static boolean reduce(int[][] c) {
if (c == null) {
return false;
}
boolean canReduce = false;
for (int i = 0; i < N_SIZE; i++) {
int last = -1;
for (int j = i + 1; j < N_SIZE; j++) {
if (c[i][j] > 0) {
if (last == -1) {
last = j;
} else {
c[i][last] += c[i][j];
c[last][j] += c[i][j];
c[i][j] = 0;
canReduce = true;
}
}
}
}
return canReduce;
}
private static int counter(int[][] c) {
if (c == null) {
return -1;
}
int counter = 0;
for (int i = 0; i < N_SIZE; i++) {
for (int j = i + 1; j < N_SIZE; j++) {
if (c[i][j] > 0) {
counter++;
}
}
}
return counter;
}
private static int[][] trans2matrix(String a, String b, int n) {
if (a == null || b == null) {
return null;
}
if ((a.length() != n) || (b.length() != n)) {
return null;
}
int[][] c = new int[N_SIZE][N_SIZE];
for (int id = 0; id < n; id++) {
int cA = a.charAt(id) - 'a';
int cB = b.charAt(id) - 'a';
if (cA > cB) {
return null;
}
if (cA < cB) {
c[cA][cB]++;
}
}
return c;
}
}
/*
* 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda
*/ | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | b43a95d102199b40dfb02e3de34f87aa | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
// https://codeforces.com/contest/1384/problem/C
public class C {
private static final int N_SIZE = 20;
public static final Scanner INPUT = new Scanner(System.in);
public static void main(String[] args) {
int t = Integer.parseInt(INPUT.nextLine());
while (t > 0) {
t--;
int n = Integer.parseInt(INPUT.nextLine());
String a = INPUT.nextLine().trim();
String b = INPUT.nextLine().trim();
// System.out.println("n = " + n);
// System.out.println("a = " + a);
// System.out.println("b = " + b);
int[][] c = trans2matrix(a, b, n);
// while (reduce(c)) {
// }
// System.out.println(counter(c));
System.out.println(countMinEdgeCover(c));
}
}
// trong do tho ton tai nhieu do thi topo, dem so luong do thi topo doc lap voi
// nhau
private static int countMinEdgeCover(int[][] c) {
if (c == null) {
return -1;
}
int[] fas = new int[N_SIZE];
for (int id = 0; id < N_SIZE; id++) {
fas[id] = id;
}
int nComponent = N_SIZE;
int[] degIns = countDegIn(c);
//for (int id = 0; id < N_SIZE; id++) {
// if (degIns[id] > 0) {
// System.out.println("degIns[" + id + "] = " + degIns[id]);
// }
//}
Queue<Integer> queue = new LinkedList<Integer>();
for (int id = 0; id < N_SIZE; id++) {
if (degIns[id] == 0) {
queue.add(id);
}
}
while (queue.size() > 0) {
int u = queue.poll();
for (int v = 0; v < N_SIZE; v++) {
if (c[u][v] > 0) {
//System.out.println("edge(" + u + ", " + v + ")");
degIns[v] -= c[u][v];
if (degIns[v] == 0) {
//System.out.println("add to queue: " + v);
queue.add(v);
}
int faU = findFa(fas, u);
int faV = findFa(fas, v);
if (faU != faV) {
fas[faU] = faV;
nComponent--;
}
}
}
}
for (int id = 0; id < N_SIZE; id++) {
if (degIns[id] > 0) {
return -1;
}
}
return N_SIZE - nComponent;
}
private static int findFa(int[] fas, int u) {
if (fas[u] == u) {
return u;
}
fas[u] = findFa(fas, fas[u]);
return fas[u];
}
private static int[] countDegIn(int[][] c) {
int[] degs = new int[N_SIZE];
for (int i = 0; i < N_SIZE; i++) {
for (int j = 0; j < N_SIZE; j++) {
if (c[i][j] > 0) {
degs[j] += c[i][j];
}
}
}
return degs;
}
private static boolean reduce(int[][] c) {
if (c == null) {
return false;
}
boolean canReduce = false;
for (int i = 0; i < N_SIZE; i++) {
int last = -1;
for (int j = i + 1; j < N_SIZE; j++) {
if (c[i][j] > 0) {
if (last == -1) {
last = j;
} else {
c[i][last] += c[i][j];
c[last][j] += c[i][j];
c[i][j] = 0;
canReduce = true;
}
}
}
}
return canReduce;
}
private static int counter(int[][] c) {
if (c == null) {
return -1;
}
int counter = 0;
for (int i = 0; i < N_SIZE; i++) {
for (int j = i + 1; j < N_SIZE; j++) {
if (c[i][j] > 0) {
counter++;
}
}
}
return counter;
}
private static int[][] trans2matrix(String a, String b, int n) {
if (a == null || b == null) {
return null;
}
if ((a.length() != n) || (b.length() != n)) {
return null;
}
int[][] c = new int[N_SIZE][N_SIZE];
for (int id = 0; id < n; id++) {
int cA = a.charAt(id) - 'a';
int cB = b.charAt(id) - 'a';
if (cA > cB) {
return null;
}
if (cA < cB) {
c[cA][cB]++;
}
}
return c;
}
}
/*
* 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda
*/ | Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | d55cdf2d55a25af6e3708e37f435bd2d | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | // package com.company.codeforces;
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int t=input.nextInt();
while (t-->0) {
int n = input.nextInt();
char a[] = new char[n];
char b[]=new char[n];
// HashMap<Character,HashMap<Character,Integer>> map=new HashMap<>();
int map[][]=new int[20][20];
a=input.next().toCharArray();
b=input.next().toCharArray();
int flag=0;
for (int i = 0; i <n ; i++) {
if (a[i]>b[i]){
flag=1;
break;
}
if (a[i]==b[i]){
continue;
}
map[a[i]-'a'][b[i]-'a']++;
}
if (flag==1){
System.out.println(-1);
continue;
}
int cunt=0;
for (int i = 0; i <20 ; i++) {
int nextmin=0;
for (int j = 0; j <20 ; j++) {
if (map[i][j]>0){
map[i][j]=0;
nextmin=j;
cunt++;
break;
}
}
for (int j = 0; j <20 ; j++) {
map[nextmin][j]+=map[i][j];
}
}
System.out.println(cunt);
}
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 2fc0d95697ee0da8f6640b2341f0b810 | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-- > 0) {
// Input
int n = scanner.nextInt();
char[] a = scanner.next().toCharArray();
char[] b = scanner.next().toCharArray();
boolean flag = true;
for (int i = 0; i < n; ++i) {
if (a[i] > b[i]) {
flag = false;
System.out.println(-1);
break;
}
}
if (flag) {
int ans = 0;
for (int cnt = 0; cnt < 26; ++cnt) {
char ch = (char) ('a' + cnt);
ArrayList<Integer> changes = new ArrayList<>();
char min_ch = 'z';
for (int i = 0; i < n; ++i) {
if (a[i] == ch) {
if (a[i] != b[i]) {
changes.add(i);
if (b[i] < min_ch)
min_ch = b[i];
}
}
}
if (changes.size() > 0) {
ans++;
for (int index : changes) {
a[index] = min_ch;
}
}
}
System.out.println(ans);
}
}
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 709d6398dedbef92c4ddcc46e5c0dece | train_000.jsonl | 1595601300 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CStringTransformation1 solver = new CStringTransformation1();
solver.solve(1, in, out);
out.close();
}
static class CStringTransformation1 {
public void solve(int testNumber, FastReader s, PrintWriter out) {
int t = s.nextInt();
Oter:
while (t-- > 0) {
int n = s.nextInt();
char[] a = s.nextString().toCharArray();
char[] b = s.nextString().toCharArray();
for (int i = 0; i < n; i++) {
if (a[i] > b[i]) {
out.println(-1);
continue Oter;
}
}
int moves = 0;
outer:
for (int i = 0; i < 26; i++) {
ArrayList<Integer> list = new ArrayList<Integer>();
char ch = (char) ('a' + i);
char min = 'u';
for (int j = 0; j < n; j++) {
if (a[j] == ch && a[j] != b[j]) {
list.add(j);
if (b[j] < min) min = b[j];
}
}
if (list.isEmpty()) {
continue outer;
}
moves++;
for (Integer ix : list) {
a[ix] = min;
}
}
out.println(moves);
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | 1 second | ["2\n-1\n3\n2\n-1"] | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Java 11 | standard input | [
"greedy",
"graphs",
"dsu",
"sortings",
"dfs and similar",
"trees"
] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,700 | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | standard output | |
PASSED | 7890391087a9da218f15b5639bf37dc8 | train_000.jsonl | 1354960800 | Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2). | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int a[], n;
static int dist[][];
public static void main(String[] args) throws IOException, InterruptedException {
FastReader in = new FastReader(new File("input.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"));
n = in.nextInt();
a = new int[n];
int max = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
max = Math.max(max, a[i]);
}
dist = new int[n][max + 1];
for (int i = 0; i < n; i++)
Arrays.fill(dist[i], -1);
int x1 = in.nextInt() - 1, y1 = in.nextInt() - 1, x2 = in.nextInt() - 1, y2 = in.nextInt() - 1;
dist[x1][y1] = 0;
LinkedList<Point> q = new LinkedList<Point>();
q.add(new Point(x1, y1));
while (!q.isEmpty()) {
Point v = q.remove();
int x = v.x, y = v.y;
if (x - 1 >= 0) {
if (a[x - 1] < y) {
if (dist[x - 1][a[x - 1]] == -1) {
dist[x - 1][a[x - 1]] = dist[x][y] + 1;
q.add(new Point(x - 1, a[x - 1]));
}
} else if (dist[x - 1][y] == -1) {
dist[x - 1][y] = dist[x][y] + 1;
q.add(new Point(x - 1, y));
}
}
if (x + 1 < n) {
if (a[x + 1] < y) {
if (dist[x + 1][a[x + 1]] == -1) {
dist[x + 1][a[x + 1]] = dist[x][y] + 1;
q.add(new Point(x + 1, a[x + 1]));
}
} else if (dist[x + 1][y] == -1) {
dist[x + 1][y] = dist[x][y] + 1;
q.add(new Point(x + 1, y));
}
}
if (y - 1 >= 0) {
if (dist[x][y - 1] == -1) {
dist[x][y - 1] = dist[x][y] + 1;
q.add(new Point(x, y - 1));
}
}
if (y + 1 <= a[x]) {
if (dist[x][y + 1] == -1) {
dist[x][y + 1] = dist[x][y] + 1;
q.add(new Point(x, y + 1));
}
}
}
out.write(dist[x2][y2] + "\n");
out.close();
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(File f) throws FileNotFoundException {
br = new BufferedReader(new FileReader(f));
}
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
boolean ready() throws IOException {
return br.ready();
}
}
class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
| Java | ["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"] | 1 second | ["3", "6", "3"] | NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left". | Java 8 | input.txt | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | d02e8f3499c4eca03e0ae9c23f80dc95 | The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1). | 1,600 | Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2). | output.txt | |
PASSED | cec7ba74390464ea80b1cbfc9a6e086e | train_000.jsonl | 1354960800 | Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2). | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class cf253c {
static int n, xs, ys, xd, yd;
static int[] arr;
static boolean valid(pair p) {
if (p==null) return false;
int x = p.x; int y=p.y;
if (x>=0 && x<n && y>=0 && y<arr[x]) return true;
return false;
}
public static void main(String[] args) throws Exception {
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
StringTokenizer st;
n = Integer.parseInt(br.readLine());
// int c =0;
arr = new int[n];
st = new StringTokenizer(br.readLine());
boolean[][] vis = new boolean[n][];
for (int i = 0; i < n; i++) {
int k = Integer.parseInt(st.nextToken())+1;
arr[i] = k;
vis[i] = new boolean[k];
}
st = new StringTokenizer(br.readLine());
xs = Integer.parseInt(st.nextToken()) - 1;
ys = Integer.parseInt(st.nextToken()) - 1;
xd = Integer.parseInt(st.nextToken()) - 1;
yd = Integer.parseInt(st.nextToken()) - 1;
br.close();
LinkedList<Integer> qx = new LinkedList<>();
LinkedList<Integer> qy = new LinkedList<>();
int lv = -1;
qx.add(xs);
qy.add(ys);
int [] dx = {0,0,-1,1};
int [] dy = {-1,1,0,0};
while (!qx.isEmpty()) {
int qs = qx.size();
lv++;
while (qs-- > 0) {
int x = qx.poll();
int y = qy.poll();
if (x== xd && y == yd) {
out.println(lv);
out.close();
return;
}
for (int i=0;i<dx.length;i++) {
int xx = x+dx[i];
int yy = y+dy[i];
if (xx<0 || xx>=n || yy<0 ) continue;
yy = Math.min(yy, arr[xx]-1);
if (!vis[xx][yy]) {
vis[xx][yy]=true;
qx.add(xx);
qy.add(yy);
}
}//end for i
}//end while qs
}//end while qx not empty
out.println(-1);
out.close();
}
static pair method(pair p) {
int x = p.x;
int y = p.y;
if (x < 0 || x >= n)
return null;
if (y >= arr[x]) {
y = arr[x]-1;
}
pair k = new pair(x, y);
return k;
}
static class pair {
int x, y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
}
}
| Java | ["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"] | 1 second | ["3", "6", "3"] | NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left". | Java 8 | input.txt | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | d02e8f3499c4eca03e0ae9c23f80dc95 | The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1). | 1,600 | Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2). | output.txt | |
PASSED | 17df4977891bc3f18d02bf5eba573f69 | train_000.jsonl | 1354960800 | Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2). | 256 megabytes | import java.util.*;
import java.io.*;
public class C253 {
static int n;
static int xs, ys, xf, yf;
static boolean vis[][];
static int[][] dist;
static int[] dx = {0, 0, 1, -1};
static int[] dy = {1, -1, 0, 0};
public static int bfs() {
Queue<Pair> qu = new LinkedList<>();
vis[xs][ys] = true;
qu.add(new Pair(xs, ys));
if(xs == xf && ys == yf)
return 0;
while(!qu.isEmpty()) {
Pair p = qu.poll();
int x = p.x, y = p.y, w = dist[x][y];
for(int i = 0; i < 4; i++) {
int xn = x + dx[i], yn = y + dy[i];
if(i == 2) {
if(x != n - 1) {
if(vis[x + 1].length <= yn)
yn = vis[x + 1].length - 1;
}
} else if(i == 3) {
if(x != 0) {
if(vis[x - 1].length <= yn)
yn = vis[x - 1].length - 1;
}
}
if(isValid(xn, yn)) {
vis[xn][yn] = true;
dist[xn][yn] = w + 1;
if(xn == xf && yn == yf)
return w + 1;
qu.add(new Pair(xn, yn));
}
}
}
return -1;
}
public static boolean isValid(int x, int y) {
return x > -1 && x < n && y > -1 && y < vis[x].length && !vis[x][y];
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
PrintWriter pw = new PrintWriter("output.txt");
StringTokenizer st;
n = Integer.parseInt(br.readLine());
vis = new boolean[n][];
dist = new int[n][];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) {
vis[i] = new boolean[Integer.parseInt(st.nextToken()) + 1];
dist[i] = new int[vis[i].length];
}
st = new StringTokenizer(br.readLine());
xs = Integer.parseInt(st.nextToken()) - 1;
ys = Integer.parseInt(st.nextToken()) - 1;
xf = Integer.parseInt(st.nextToken()) - 1;
yf = Integer.parseInt(st.nextToken()) - 1;
pw.println(bfs());
pw.flush();
}
public static class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
}
| Java | ["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"] | 1 second | ["3", "6", "3"] | NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left". | Java 8 | input.txt | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | d02e8f3499c4eca03e0ae9c23f80dc95 | The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1). | 1,600 | Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2). | output.txt | |
PASSED | c4bce8b8f994f9baa26ae1181a57a26c | train_000.jsonl | 1354960800 | Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2). | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Euler {
static int n;
static int[] a;
static int[][] vis = new int[101][100001];
static int[][] dist = new int[101][100001];
static int[][] moves = {{1, 0},{-1, 0},{0, 1},{0, -1}};
static int r1, c1, r2, c2;
static FastReader in =new FastReader();
static PrintWriter out;
static class pair{
int x;
int y;
pair (int x, int y) {
this.x = x;
this.y = y;
}
}
public static void bfs() {
Queue<pair> q = new LinkedList<>();
q.add(new pair(r1, c1));
vis[r1][c1] = 1;
while (!q.isEmpty()) {
pair p = q.poll();
int x = p.x;
int y = p.y;
if (x == r2 && y == c2) {
break;
}
for (int i = 0; i < 4; i++) {
int nx = x + moves[i][0];
int ny = y + moves[i][1];
if (nx < 0) nx = 0;
if (nx >= n) nx = n - 1;
if (ny < 0) ny = 0;
if (ny >= a[nx]) ny = a[nx] - 1;
if (vis[nx][ny] == 1) continue;
q.add(new pair(nx, ny));
vis[nx][ny] = 1;
dist[nx][ny] = 1 + dist[x][y];
}
}
}
public static void main(String[] args){
try{
out=new PrintWriter(new FileWriter("output.txt"));
}
catch(Exception e) {}
n = in.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt() + 1;
r1 = in.nextInt() - 1;
c1 = in.nextInt() - 1;
r2 = in.nextInt() - 1;
c2 = in.nextInt() - 1;
bfs();
out.println(dist[r2][c2]);
out.flush();
out.close();
return;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
if(env) {
try {
br=new BufferedReader(new FileReader("input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else 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 | ["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"] | 1 second | ["3", "6", "3"] | NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left". | Java 8 | input.txt | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | d02e8f3499c4eca03e0ae9c23f80dc95 | The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1). | 1,600 | Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2). | output.txt | |
PASSED | 4719d1794177dbd693ee6e0951c0a57e | train_000.jsonl | 1354960800 | Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2). | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class E {
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
int n = sc.nextInt(), a[] = new int[n];
for(int i = 0; i < n; ++i)
a[i] = sc.nextInt();
int r1 = sc.nextInt() - 1, c1 = sc.nextInt() - 1, r2 = sc.nextInt() - 1, c2 = sc.nextInt() - 1;
int r = r1, c = c1, ans = (int)1e8, d = 0;
while(r < n)
{
c = Math.min(c, a[r]);
ans = Math.min(get(a, r, c, r2, c2) + d, ans);
++r; ++d;
}
r = r1; c = c1; d = 0;
while(r >= 0)
{
c = Math.min(c, a[r]);
ans = Math.min(get(a, r, c, r2, c2) + d, ans);
--r; ++d;
}
out.println(ans);
out.flush();
out.close();
}
static int get(int[] a, int r1, int c1, int r2, int c2)
{
int d = r1 > r2 ? -1 : 1, ans = Math.abs(r1 - r2);
while(r1 != r2)
{
r1 += d;
c1 = Math.min(c1, a[r1]);
}
return ans + Math.abs(c1 - c2);
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader r){ br = new BufferedReader(r);}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"] | 1 second | ["3", "6", "3"] | NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left". | Java 8 | input.txt | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | d02e8f3499c4eca03e0ae9c23f80dc95 | The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1). | 1,600 | Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2). | output.txt | |
PASSED | 76e94daf3d95e330a91a903c3cf59850 | train_000.jsonl | 1354960800 | Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2). | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int MOD = 1000000007;
static int M = 505;
static int oo = (int)1e9;
static int[] di = {-1, 1, 0, 0};
static int[] dj = {0, 0, -1, 1};
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
int n = Integer.parseInt(in.readLine());
StringTokenizer tk = new StringTokenizer(in.readLine());
int[] a = new int[n];
for(int i=0; i < n; i++)
a[i] = Integer.parseInt(tk.nextToken());
tk = new StringTokenizer(in.readLine());
int r1 = Integer.parseInt(tk.nextToken()) - 1;
int c1 = Integer.parseInt(tk.nextToken()) - 1;
int r2 = Integer.parseInt(tk.nextToken()) - 1;
int c2 = Integer.parseInt(tk.nextToken()) - 1;
// int n = in.nextInt();
// int[] a = new int[n];
// for(int i=0; i < n; ++i)
// a[i] = in.nextInt();
// int r1 = in.nextInt() - 1, c1 = in.nextInt() - 1;
// int r2 = in.nextInt() - 1, c2 = in.nextInt() - 1;
boolean[][] visit = new boolean[n][];
for(int i=0; i<n; ++i)
visit[i] = new boolean[a[i] + 1];
Queue<Integer> iq = new ArrayDeque<>();
Queue<Integer> jq = new ArrayDeque<>();
Queue<Integer> kq = new ArrayDeque<>();
iq.add(r1);
jq.add(c1);
kq.add(0);
while(!iq.isEmpty()) {
int i = iq.poll(), j = jq.poll(), k = kq.poll();
visit[i][j] = true;
if(i == r2 && j == c2) {
out.println(k);
break;
}
for(int d=0; d < 4; ++d) {
int ni = i + di[d];
int nj = j + dj[d];
if(!valid(a, n, ni, nj))
continue;
if(a[ni] < nj)
nj = a[ni];
if(!visit[ni][nj]) {
iq.add(ni);
jq.add(nj);
kq.add(k + 1);
visit[ni][nj] = true;
}
}
}
in.close();
out.close();
}
static boolean valid(int[] a, int n, int i, int j) {
return i >= 0 && i < n && j >= 0;
}
static int simpleDist(int[] l, int r1, int c1, int r2, int c2) {
int i = r1, j = c1;
int ret = 0;
while(i != r2) {
int d = r2 > i ? 1 : -1;
i += d;
if(l[i] + 1 < j)
j = l[i] + 1;
ret++;
}
ret += Math.abs(c2 - j);
return ret;
}
static int[] move(int[] l, int i, int j, int r) {
int cnt = 0;
while(i != r) {
int d = r > i ? 1 : -1;
i += d;
if(l[i] + 1 < j)
j = l[i] + 1;
cnt++;
}
int[] ret = {i, j, cnt};
return ret;
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
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 = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
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 {
res *= 10;
res += c - '0';
c = read();
} 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 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 String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | Java | ["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"] | 1 second | ["3", "6", "3"] | NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left". | Java 8 | input.txt | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | d02e8f3499c4eca03e0ae9c23f80dc95 | The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1). | 1,600 | Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2). | output.txt | |
PASSED | 57c877f848290300ae5b8f1f947bc976 | train_000.jsonl | 1354960800 | Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2). | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int MOD = 1000000007;
static int M = 505;
static int oo = (int)1e9;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
int n = Integer.parseInt(in.readLine());
StringTokenizer tk = new StringTokenizer(in.readLine());
int[] l = new int[n+1];
for(int i=1; i <= n; i++)
l[i] = Integer.parseInt(tk.nextToken());
tk = new StringTokenizer(in.readLine());
int r1 = Integer.parseInt(tk.nextToken());
int c1 = Integer.parseInt(tk.nextToken());
int r2 = Integer.parseInt(tk.nextToken());
int c2 = Integer.parseInt(tk.nextToken());
// int n = in.nextInt();
// int[] l = new int[n+1];
// for(int i=1; i <= n; ++i)
// l[i] = in.nextInt();
// int r1 = in.nextInt(), c1 = in.nextInt();
// int r2 = in.nextInt(), c2 = in.nextInt();
int ans = oo;
for(int r = 1; r <= n; ++r) {
int[] m = move(l, r1, c1, r);
int i = m[0], j = m[1], cnt = m[2];
ans = Math.min(ans, cnt + simpleDist(l, i, j, r2, c2) );
}
out.println(ans);
in.close();
out.close();
}
static int simpleDist(int[] l, int r1, int c1, int r2, int c2) {
int i = r1, j = c1;
int ret = 0;
while(i != r2) {
int d = r2 > i ? 1 : -1;
i += d;
if(l[i] + 1 < j)
j = l[i] + 1;
ret++;
}
ret += Math.abs(c2 - j);
return ret;
}
static int[] move(int[] l, int i, int j, int r) {
int cnt = 0;
while(i != r) {
int d = r > i ? 1 : -1;
i += d;
if(l[i] + 1 < j)
j = l[i] + 1;
cnt++;
}
int[] ret = {i, j, cnt};
return ret;
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
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 = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
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 {
res *= 10;
res += c - '0';
c = read();
} 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 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 String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | Java | ["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"] | 1 second | ["3", "6", "3"] | NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left". | Java 8 | input.txt | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | d02e8f3499c4eca03e0ae9c23f80dc95 | The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1). | 1,600 | Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2). | output.txt | |
PASSED | 5964bb86bafdab23838b1abe37ebb584 | train_000.jsonl | 1354960800 | Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2). | 256 megabytes | import java.awt.Point;
import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class TextEditor {
static class Solver {
int n,r1,c1,r2,c2;
int[] arr;
int[][] set = new int[105][(int)1e5 + 5];
public void solve(MyReader in, PrintWriter out) {
n = in.nextInt();
arr = in.nextIntArray(n);
r1 = in.nextInt()-1;
c1 = in.nextInt()-1;
r2 = in.nextInt()-1;
c2 = in.nextInt()-1;
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[]{r1,c1,0});
set[r1][c1] = 1;
while (!q.isEmpty()){
int[] c =q.poll();
if(c[0] == r2 && c[1] == c2){
out.println(c[2]);
return;
}
for(int[] d:dir){
int x = c[0]+d[0];
if(x < 0 || x >= n)continue;
int y = c[1]+d[1];
if(y < 0)continue;
if(y > arr[x])y = arr[x];
int v =c[2] + 1;
if(set[x][y] == 0){
set[x][y] = 1;
q.add(new int[]{x,y,v});
}
}
}
}
// private boolean valid(int x, int y) {
// return x>=1 && y>=0 && x<=n && !set.contains(new int[]{x, y});
// }
}
public static void main(String[] args) throws FileNotFoundException {
MyReader mr = new MyReader();
PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt")));
// PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
new Solver().solve(mr, out);
out.close();
}
static int[][] dir = {{0,1}, {1,0},{-1,0}, {0,-1}};
// static int[][] dir = {{0,1}, {1,0},{-1,0}, {0,-1}, {-1,-1},{-1,1}, {1,1}, {1,-1}};
static class MyReader {
BufferedReader br;
StringTokenizer st;
MyReader() throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
// br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String res = "";
try {
res = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
Integer[] nextIntegerArray(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
Long[] nextLongArray(int n) {
Long[] arr = new Long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
String[] nextStringArray(int n) {
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = next();
}
return arr;
}
}
static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
| Java | ["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"] | 1 second | ["3", "6", "3"] | NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left". | Java 8 | input.txt | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | d02e8f3499c4eca03e0ae9c23f80dc95 | The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1). | 1,600 | Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2). | output.txt | |
PASSED | 80f668feb1fec8a4a5fffc83541806ea | train_000.jsonl | 1354960800 | Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2). | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
public class A_GENERAL {
// for fast output printing : use printwriter or stringbuilder
// remember to close pw using pw.close()
static StringBuilder sb = new StringBuilder();
static long seive_size = (long) 1e6;
static String alpha = "abcdefghijklmnopqrstuvwxyz";
static ArrayList<Integer> primes = new ArrayList<>();
static boolean[] seive_set = new boolean[(int) seive_size+1];
static int n, m, k;
static ArrayList<Integer>[] adj;
static boolean[] vis;
static ArrayDeque<Integer> q = new ArrayDeque<>();
static ArrayDeque<Pair> qq = new ArrayDeque<>();
static final long MOD = 998244353;
static int[] dx = new int[] {1, 0, -1, 0, 1, -1, 1, -1};
static int[] dy = new int[] {0, 1, 0, -1, -1, 1, 1, -1};
static long[][] arr;
static int[] rank;
static int[] parent;
static int[] a;
static int si, sj, ti, tj;
static int[][] dist;
static boolean[][] vis2;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
// MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter("output.txt");
Scanner sc = new Scanner(new File("input.txt"));
n = sc.nextInt();
a = new int[n+1];
dist = new int[n+1][(int)1e5+1];
vis2 = new boolean[n+1][(int)1e5+1];
for(int i = 1; i <= n; i++) {
a[i] = sc.nextInt()+1;
}
si = sc.nextInt();
sj = sc.nextInt();
ti = sc.nextInt();
tj = sc.nextInt();
qq.add(new Pair(si, sj));
dist[si][sj] = 0;
vis2[si][sj] = true;
while(!qq.isEmpty()) {
Pair pp = qq.poll();
int ui = pp.f;
int uj = pp.s;
if(ui == ti && uj == tj) {
break;
}
f(ui-1,uj, ui, uj);
f(ui+1, uj, ui, uj);
f(ui, uj-1, ui, uj);
f(ui, uj+1, ui, uj);
}
out.println(dist[ti][tj]);
out.close();
}
public static void f(int i, int j, int ui, int uj) {
if(i < 1 || i > n || j < 1 || j > a[ui] || vis2[i][j])
return;
j = Math.min(a[i], j);
dist[i][j] = dist[ui][uj] + 1;
vis2[i][j] = true;
qq.add(new Pair(i, j));
}
public static class Triplet implements Comparable<Triplet> {
int x;
int y;
int z;
Triplet(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int compareTo(Triplet o) {
return Integer.compare(this.x, o.x);
}
}
public static class Pair implements Comparable<Pair> {
int f;
int s;
Pair(int f, int s) {
this.f = f;
this.s = s;
}
public int compareTo(Pair o) {
return Integer.compare(this.f, o.f);
}
}
public static class LongPair implements Comparable<LongPair>{
long f;
long s;
LongPair(long f, long s) {
this.f = f;
this.s = s;
}
public int compareTo(LongPair o) {
return Long.compare(this.f, o.f);
}
}
public static void init(int n) {
adj = new ArrayList[n+1];
vis = new boolean[n+1];
parent = new int[n+1];
rank = new int[n+1];
for(int i = 0; i <= n; i++) {
adj[i] = new ArrayList<>();
parent[i] = i;
rank[i] = 0;
}
}
// print string "s" multiple times
// prefer to use this function for multiple printing
public static String mp(String s, int times) {
return String.valueOf(new char[times]).replace("\0", s);
}
// take log with base 2
public static long log2(long k) {
return 63-Long.numberOfLeadingZeros(k);
}
// using lambda function for sorting
public static void lambdaSort() {
Arrays.sort(arr, (a, b) -> Double.compare(a[0], b[0]));
}
// (n choose k) = (n/k) * ((n-1) choose (k-1))
public static long choose(long n, long k) {
return (k == 0) ? 1 : (n*choose(n-1, k-1))/k;
}
// just for keeping gcd function for other personal purposes
public static long gcd(long a, long b) {
return (a == 0) ? b : gcd(b%a, a);
}
public static long max(long... as) {
long max = Long.MIN_VALUE;
for (long a : as) max = Math.max(a, max);
return max;
}
public static long min(int... as) {
long min = Long.MAX_VALUE;
for (long a : as) min = Math.min(a, min);
return min;
}
public static long modpow(long x, long n, long mod) {
if(n == 0) return 1%mod;
long u = modpow(x, n/2, mod);
u = (u*u)%mod;
if(n%2 == 1) u = (u*x)%mod;
return u;
}
// ======================= binary search (lower and upper bound) =======================
public static int lowerBound(long[] a, int x) {
int lo = 0;
int hi = a.length-1;
int ans = -1;
while(lo <= hi) {
int mid = (lo+hi)/2;
if(x < a[mid]) {
hi = mid-1;
} else if(x > a[mid]) {
lo = mid+1;
} else if(lo != hi) {
hi = mid-1; // for first occurrence
ans = mid;
} else {
return mid;
}
}
return ans;
}
public static int upperBound(long[] a, long x) {
int lo = 0;
int hi = a.length-1;
int ans = -1;
while(lo <= hi) {
int mid = (lo+hi)/2;
if(x < a[mid]) {
hi = mid-1;
} else if(x > a[mid]) {
lo = mid+1;
} else if(lo != hi) {
lo = mid+1; // for last occurrence
ans = mid;
} else {
return mid;
}
}
return ans;
}
// ================================================================
// ================== SEIVE OF ERATOSTHENES =======================
// Complexity : O(N * log(log(N))) ( almost O(N) )
public static void generatePrimes() {
// set.add(0);
// set.add(1);
Arrays.fill(seive_set, true);
seive_set[0] = false;
seive_set[1] = false;
for(int i = 2; i <= seive_size; i++) {
if(seive_set[i]) {
for(long j = (long) i*i; j <= seive_size; j+=i)
seive_set[(int)j] = false;
primes.add(i);
}
}
}
public static boolean isPrime(long N) {
if(N <= seive_size) return seive_set[(int)N];
for (int i = 0; i < (int)primes.size(); i++)
if (N % primes.get(i) == 0) return false;
return true;
}
// ===========================================================
// ================ Permutation of String ====================
public static void permute(String str) {
permute(str, 0, str.length()-1);
}
public static void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}
public static String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
// Union-find
// static int[] parent, rank;
// public static void makeSet(int n) {
//
// parent = new int[n+1];
// rank = new int[n+1];
// for(int i = 1; i <= n; i++) {
// parent[i] = i;
// rank[i] = 0;
// }
// }
public static int find(int u) {
if(parent[u] == u) return u;
int v = find(parent[u]);
parent[u] = v;
return v;
}
public static boolean connected(int u, int v) {
return find(u) == find(v);
}
public static void Union(int u, int v) {
int x = find(u); //root of u
int y = find(v); //root of v
if(x == y) return;
if(rank[x] == rank[y]) {
parent[y] = x;
rank[x]++;
}
else if(rank[x] > rank[y]) {
parent[y] = x;
}
else {
parent[x] = y;
}
}
// public static int dijkstra(int x, int y) {
// int[] dist = new int[n+1];
// Arrays.fill(dist, Integer.MAX_VALUE);
// PriorityQueue<Node> q = new PriorityQueue<>();
// q.add(new Node(x, 0));
// dist[x] = 0;
// while(!q.isEmpty()) {
// Node node = q.poll();
// int u = node.key;
// if(u == y) {
// break;
// }
// for(int v : res[u]) {
// if(dist[v] > dist[u]+count[u]) {
// dist[v] = dist[u] + count[u];
// q.add(new Node(v, dist[v]));
// }
// }
// }
// if(dist[y] == Integer.MAX_VALUE) {
// return -1;
// }
// return dist[y];
// }
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}}
return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
String nextLine(){String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[] nextIntArray(int n, int delta) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt() + delta;
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
} | Java | ["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"] | 1 second | ["3", "6", "3"] | NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left". | Java 8 | input.txt | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | d02e8f3499c4eca03e0ae9c23f80dc95 | The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1). | 1,600 | Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2). | output.txt | |
PASSED | b645f237db14a32585458f9ccfc00a4d | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String []name=new String[(int)n];
String []pos=new String[(int)n];
String []order=new String[(int)n];
for (int i=0;i<n ;i++ )
{
String s[]=br.readLine().split(" ");
name[i]=s[0];
pos[i]=s[1];
}
String p="rat";
String q="a";
int c=0;
int j=0;
for(int i=0;i<n;i++)
{
if(pos[i].equals("rat"))
{
System.out.println(name[i]);
}
}
for(int i=0;i<n;i++)
{
if(pos[i].equals("woman") || pos[i].equals("child") )
{
System.out.println(name[i]);
}
}
for(int i=0;i<n;i++)
{
if(pos[i].equals("man"))
{
System.out.println(name[i]);
}
}
for(int i=0;i<n;i++)
{
if(pos[i].equals("captain"))
{
System.out.println(name[i]);
break;
}
}
} catch(Exception e) {
return;}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | e4d83de2039db0b4d5a8c5cb7bd57ba1 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.awt.Point;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Xtend {
public static void main(String[] args)throws IOException{
BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
int m=Integer.parseInt(x.readLine());
String []array=new String[m];
String result="";
for(int i=1;i<=m;i++){
array[i-1]=x.readLine();
}
for(int j=0;j<m;j++){
if(array[j].contains("rat") && array[j].substring(array[j].length()-3).equals("rat")){
result+=array[j].replace(array[j].substring(array[j].length()-3), "")+"\n";
}
}
for(int l=0;l<m;l++){
if(array[l].contains("woman")){
result+=array[l].replace(array[l].substring(array[l].length()-5), "")+"\n";
}
if(array[l].contains("child")){
result+=array[l].replace(array[l].substring(array[l].length()-5), "")+"\n";
}
}
for(int n=0;n<m;n++){
if(array[n].contains("man") && !array[n].contains("woman") && array[n].substring(array[n].length()-3).equals("man")){
result+=array[n].replace(array[n].substring(array[n].length()-3), "")+"\n";
}
}for(int p=0;p<m;p++){
if(array[p].contains("captain")){
result+=array[p].replace(array[p].substring(array[p].length()-7), "")+"\n";
}
}
System.out.println(result);
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 9986d3da3c22604f2d39b8e779fa21b4 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class SinkingShip {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
List<Person> persons = new ArrayList<Person>();
int count = in.nextInt();
for (int i = 0; i < count; i++) {
persons.add(new Person(in.next(), in.next()));
}
Collections.sort(persons);
for (Person person : persons) {
out.println(person);
}
out.close();
}
private static class Person implements Comparable<Person> {
private int type;
private String name;
public Person(String name, String type) {
this.name = name;
this.type = getType(type);
}
private int getType(String type) {
if ("rat".equals(type)) return 0;
if ("child".equals(type)) return 1;
if ("woman".equals(type)) return 1;
if ("man".equals(type)) return 2;
return 3;
}
public String toString() {
return this.name;
}
@Override
public int compareTo(Person o) {
if (this.type == o.type) return 0;
return (this.type > o.type) ? 1 : -1;
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 5902a278fc40aaaea5688a0f66ba63e4 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
ArrayList<String> rats = new ArrayList<String>();
ArrayList<String> womenOrChildren = new ArrayList<String>();
ArrayList<String> men = new ArrayList<String>();
ArrayList<String> captain = new ArrayList<String>();
int N = in.nextInt();
for (int i = 0; i < N; ++i) {
String name = in.next();
String type = in.next();
if (type.equals("rat"))
rats.add(name);
else if (type.equals("woman") || type.equals("child"))
womenOrChildren.add(name);
else if (type.equals("captain"))
captain.add(name);
else
men.add(name);
}
for (String r : rats)
System.out.println(r);
for (String r : womenOrChildren)
System.out.println(r);
for (String r : men)
System.out.println(r);
for (String r : captain)
System.out.println(r);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
public String nextLine() {
String line = null;
try {
tokenizer = null;
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | a660462452132cdfa4c74c813b971637 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
ob[] a = new ob[n];
for (int i = 0; i < a.length; i++) {
a[i] = new ob(in.next(), in.next());
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (!a[i].v && a[i].t.equals("rat")) {
a[i].v = true;
System.out.println(a[i].name);
}
}
}
for(int i = 0 ; i < n;i++){
for(int j = 0 ; j < n;j++){
if(!a[i].v && (a[i].t.equals("woman")||a[i].t.equals("child"))){
a[i].v=true;
System.out.println(a[i].name);
}
}
}
for(int i = 0 ; i < n;i++){
for(int j = 0 ; j < n;j++){
if(!a[i].v && (a[i].t.equals("man"))){
a[i].v=true;
System.out.println(a[i].name);
}
}
}
for(int i = 0 ; i < n;i++){
for(int j = 0 ; j < n;j++){
if(!a[i].v && (a[i].t.equals("captain"))){
a[i].v=true;
System.out.println(a[i].name);
}
}
}
}
public static class ob {
String name;
String t;
boolean v;
public ob(String n, String tt) {
name = n;
t = tt;
v = false;
}
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | f088b8b58ce7124053b90c2b56426341 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
public class Main {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int number = Integer.parseInt(reader.readLine());
Vector<String> rat = new Vector<String>();
Vector<String> women = new Vector<String>();
Vector<String> man = new Vector<String>();
Vector<String> captin = new Vector<String>();
for (int i = 0; i < number; i++) {
String ar[] = reader.readLine().split(" ");
if (ar[1].contains("rat"))
rat.add(ar[0]);
else if (ar[1].contains("wom") || ar[1].contains("chi"))
women.add(ar[0]);
else if (ar[1].contains("man"))
man.add(ar[0]);
else
captin.add(ar[0]);
}
for (int i = 0; i < rat.size(); i++) {
System.out.println(rat.get(i));
}
for (int i = 0; i < women.size(); i++) {
System.out.println(women.get(i));
}
for (int i = 0; i < man.size(); i++) {
System.out.println(man.get(i));
}
for (int i = 0; i < captin.size(); i++) {
System.out.println(captin.get(i));
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 1f5a5707334609a2d8fc578e474531f4 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
/**
* Sinking Ship
*
* The ship crashed into a reef and is sinking. Now the entire crew must be
* evacuated. All n crew members have already lined up in a row (for convenience
* let's label them all from left to right with positive integers from 1 to n)
* and await further instructions. However, one should evacuate the crew
* properly, in a strict order. Specifically:
*
* The first crew members to leave the ship are rats. Then women and children
* (both groups have the same priority) leave the ship. After that all men are
* evacuated from the ship. The captain leaves the sinking ship last.
*
* If we cannot determine exactly who should leave the ship first for any two
* members of the crew by the rules from the previous paragraph, then the one
* who stands to the left in the line leaves the ship first (or in other words,
* the one whose number in the line is less).
*
* For each crew member we know his status as a crew member, and also his name.
* All crew members have different names. Determine the order in which to
* evacuate the crew.
*
* Input
* The first line contains an integer n, which is the number of people in the
* crew (1 <= n <= 100). Then follow n lines. The i-th of those lines contains
* two words — the name of the crew member who is i-th in line, and his status
* on the ship. The words are separated by exactly one space. There are no other
* spaces in the line. The names consist of Latin letters, the first letter is
* uppercase, the rest are lowercase. The length of any name is from 1 to 10
* characters. The status can have the following values: rat for a rat, woman
* for a woman, child for a child, man for a man, captain for the captain. The
* crew contains exactly one captain.
*
* Output
* Print n lines. The i-th of them should contain the name of the crew member
* who must be the i-th one to leave the ship.
*
* Sample test(s)
* Input
* 6
* Jack captain
* Alice woman
* Charlie man
* Teddy rat
* Bob child
* Julia woman
* Output
* Teddy
* Alice
* Bob
* Julia
* Charlie
* Jack
*
* @author Europa
*/
public class SinkingShip {
private static final String RAT = "rat";
private static final String WOMAN = "woman";
private static final String CHILD = "child";
private static final String MAN = "man";
private static final String CAPTAIN = "captain";
private static final int PRIORITY_RAT = 0;
private static final int PRIORITY_WOMAN = 1;
private static final int PRIORITY_CHILD = 1;
private static final int PRIORITY_MAN = 2;
private static final int PRIORITY_CAPTAIN = 3;
private static final int PRIORITY_INVALID = -1;
private static final int NAME = 0;
private static final int STATUS = 1;
private static final String[] arrange(String[][] crew) {
Arrays.sort(crew, new Comparator<String[]>() {
@Override
public int compare(String[] member1, String[] member2) {
return priority(member1) - priority(member2);
}
});
String[] arrangement = new String[crew.length];
for (int i = 0; i < crew.length; i++) {
arrangement[i] = crew[i][NAME];
}
return arrangement;
}
private static int priority(String[] member) {
String status = member[STATUS];
if (RAT.equals(status)) return PRIORITY_RAT;
if (WOMAN.equals(status)) return PRIORITY_WOMAN;
if (CHILD.equals(status)) return PRIORITY_CHILD;
if (MAN.equals(status)) return PRIORITY_MAN;
if (CAPTAIN.equals(status)) return PRIORITY_CAPTAIN;
return PRIORITY_INVALID;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt(); scanner.nextLine();
String[][] crew = new String[N][2];
for (int i = 0; i < N; i++) {
crew[i] = scanner.nextLine().split(" ");
}
String[] results = SinkingShip.arrange(crew);
for (int i = 0; i < N; i++) {
System.out.println(results[i]);
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | f7884f19aaf80200da1339e5ba34033a | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.Scanner;
public class SinkingShip {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int n = in.nextInt();
String [][] ppl = new String [n][2];
String cap = "";
for (int i =0; i < n; i++) {
ppl[i][0] = in.next();
ppl[i][1] = in.next();
//in.nextLine();
if (ppl[i][1].equals("rat"))
System.out.println(ppl[i][0]);
if (ppl[i][1].equals("captain"))
cap = ppl[i][0];
}
for (int i =0; i < n; i++)
if (ppl[i][1].equals("woman") || ppl[i][1].equals("child"))
System.out.println(ppl[i][0]);
for (int i =0; i < n; i++)
if (ppl[i][1].equals("man"))
System.out.println(ppl[i][0]);
System.out.println(cap);
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 1f60b56cb61b1a2f3ba998aa7fe3289d | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.Scanner;
public class untitled {
public static void main (String [] ugh) {
Scanner in = new Scanner (System.in);
int x = in.nextInt();
String [] cok = new String [x+10];
String [] cuk = new String [x+10];
for (int i=0;i<x;++i) {
cok[i] = in.next();
cuk[i] = in.next();
}
for (int i=0;i<x;++i)
if (cuk[i].equals("rat")) System.out.println (cok[i]);
for (int i=0;i<x;++i)
if (cuk[i].equals("child")||cuk[i].equals("woman")) System.out.println (cok[i]);
for (int i=0;i<x;++i)
if (cuk[i].equals("man")) System.out.println (cok[i]);
for (int i=0;i<x;++i)
if (cuk[i].equals("captain")) System.out.println (cok[i]);
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 41ae01233416572e7fe12a0ae6e8cfca | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Point[] arr = new Point[n];
for(int i=0; i<n; ++i) {
arr[i] = new Point(sc.next(), sc.next());
}
Arrays.sort(arr);
// debug(arr);
for(Point p : arr) {
System.out.println(p.name);
}
}
public static void debug(Object...objects ) {
System.out.println(Arrays.deepToString(objects));
}
}
class Point implements Comparable<Point> {
String name, title;
public Point(String name, String title) {
this.name = name;
this.title = title;
}
public int compareTo(Point p) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("rat", 3);
map.put("child", 2);
map.put("woman", 2);
map.put("man", 1);
map.put("captain", 0);
return -map.get(title) + map.get(p.title);
}
public String toString() {
return name + " " + title;
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | dda9ff310a3a379d4fea43328377e035 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String name, status;
List<String> varios = new ArrayList<String>();
List<String> hombres = new ArrayList<String>();
String cap="";
for(int i=1;i<=n;i++) {
name = in.next();
status = in.next();
if(status.equals("rat")) {
System.out.println(name);
}
if(status.equals("woman") || status.equals("child"))
varios.add(name);
if(status.equals("man"))
hombres.add(name);
if(status.equals("captain"))
cap = name;
}
for(String x : varios)
System.out.println(x);
for(String x : hombres)
System.out.println(x);
System.out.println(cap);
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | f09fa82671a6c5eae5825aa59bb974e9 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class SinkingShip {
public static void main(String[] args) {
ArrayList<String> rats = new ArrayList<String>();
ArrayList<String> wcs = new ArrayList<String>();
ArrayList<String> men = new ArrayList<String>();
ArrayList<String> captin = new ArrayList<String>();
Scanner scanner = new Scanner(System.in);
// while (scanner.hasNext()) {
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
String str = scanner.next();
String type = scanner.next();
if(type.equals("rat")) {
rats.add(str);
}
if(type.equals("child")) {
wcs.add(str);
}
if(type.equals("woman")) {
wcs.add(str);
}
if(type.equals("man")) {
men.add(str);
}
if(type.equals("captain")) {
captin.add(str);
}
}
for (Iterator iterator = rats.iterator(); iterator.hasNext();) {
String string = (String) iterator.next();
System.out.println(string);
}
for (Iterator iterator = wcs.iterator(); iterator.hasNext();) {
String string = (String) iterator.next();
System.out.println(string);
}
for (Iterator iterator = men.iterator(); iterator.hasNext();) {
String string = (String) iterator.next();
System.out.println(string);
}
for (Iterator iterator = captin.iterator(); iterator.hasNext();) {
String string = (String) iterator.next();
System.out.println(string);
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | d4678cc309489cb3e9fabc1035b5f40a | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
public class first {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(new InputStreamReader(System.in));
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
int testC = Integer.parseInt(r.readLine());
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> store = new ArrayList<String>();
for (int i = 0; i < testC; i++)
{
String input = r.readLine();
store.add(input);
}
for(int ll = 0 ; ll < store.size(); ll++)
{
String array [] = store.get(ll).split(" ");
if(array[1].equals("rat"))
result.add(array[0]);
}
for(int ll = 0 ; ll < store.size(); ll++)
{
String array [] = store.get(ll).split(" ");
if(array[1].equals("child") || array[1].equals("woman"))
result.add(array[0]);
}
for(int ll = 0 ; ll < store.size(); ll++)
{
String array [] = store.get(ll).split(" ");
if(array[1].equals("man"))
result.add(array[0]);
}
for(int ll = 0 ; ll < store.size(); ll++)
{
String array [] = store.get(ll).split(" ");
if(array[1].equals("captain"))
result.add(array[0]);
}
for(int o = 0 ; o < result.size(); o++)
System.out.println(result.get(o));
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | e69d5a76c702357a1674ad7e025a8d4a | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes |
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SinkingShip {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
if (s.hasNext()) {
int count = Integer.parseInt(s.nextLine());
List<String> rats = new ArrayList<String>();
List<String> womanAndChild = new ArrayList<String>();
List<String> man = new ArrayList<String>();
String captin = "";
while (count-- > 0) {
String[] input = s.nextLine().split(" ");
if ("rat".equals(input[1])) {
rats.add(input[0]);
} else if ("woman".equals(input[1])) {
womanAndChild.add(input[0]);
} else if ("child".equals(input[1])) {
womanAndChild.add(input[0]);
} else if ("man".equals(input[1])) {
man.add(input[0]);
} else if ("captain".equals(input[1])) {
captin = input[0];
}
}
for (String item : rats) {
System.out.println(item);
}
for (String item : womanAndChild) {
System.out.println(item);
}
for (String item : man) {
System.out.println(item);
}
System.out.println(captin);
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 1b00a0a17d88fabe0884087503277cbe | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.*;
import java.util.*;
public class Problem
{
BufferedReader in;
StringTokenizer st;
PrintWriter out;
static String INPUTFILE = "input.txt";
static String OUTPUTFILE = "output.txt";
class TeamMember {
public String Name;
public int W;
public TeamMember(String name, int weight)
{
Name = name;
W = weight;
}
}
void run() throws IOException
{
//in = new BufferedReader(new FileReader(INPUTFILE));
in = new BufferedReader(new InputStreamReader(System.in));
//out = new PrintWriter(OUTPUTFILE);
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
void solve() throws IOException
{
//
int n = nextInt();
TeamMember[] team = new TeamMember[n];
for (int i = 0; i < n; i++)
{
String name = nextToken();
String rank = nextToken();
int weight = -1;
if (rank.contains("rat"))
weight = 0;
else if (rank.contains("woman") || rank.contains("child"))
weight = 1;
else if (rank.contains("man"))
weight = 2;
else if (rank.contains("captain"))
weight = 3;
team[i] = new TeamMember(name, weight);
}
for (int w = 0; w < 4; w++)
{
for (int i = 0; i < n; i++)
if (team[i].W == w)
out.println(team[i].Name);
}
}
public static void main(String[] args) throws IOException
{
new Problem().run();
}
String nextToken() throws IOException
{
if (st == null || ! st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt(nextToken());
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 12c1f97c2097137a9d71e843dd1818c6 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class SinkingShip {
void run(){
try{
BufferedReader bfd = new BufferedReader(new InputStreamReader(System.in));
int n = new Integer(bfd.readLine());
ArrayList<String>[] arr = new ArrayList[4];
for(int k=0; k<arr.length; ++k)
arr[k] = new ArrayList<String>();
String[] sp;
for(int k=0; k<n; ++k){
sp = bfd.readLine().split(" ");
if(sp[1].equals("rat"))
arr[0].add(sp[0]);
else if(sp[1].equals("woman") || sp[1].equals("child"))
arr[1].add(sp[0]);
else if(sp[1].equals("man"))
arr[2].add(sp[0]);
else
arr[3].add(sp[0]);
}
for(int i=0; i<arr.length; ++i)
for(String str:arr[i])
System.out.println(str);
} catch(Exception e){}
}
public static void main(String[] args) {
new SinkingShip().run();
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 7a5849451556e466f94e8b79b52d30ba | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
public class A {
public static void main(String[] args) throws IOException {
A pro = new A();
pro.solve();
}
public void solve() throws NumberFormatException, IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(bf.readLine());
ArrayList<Person> people = new ArrayList<Person>(N);
int count=0;
while(N-- !=0){
Person p = new Person(bf.readLine().split(" "),count++);
people.add(p);
}
Collections.sort(people);
for(Person s : people){
System.out.println(s.name);
}
}
class Person implements Comparable<Person> {
String name;
int key;
int id;
public Person(String[] split, int i) {
name = split[0];
key = getKey(split[1]);
id = i;
}
public int getKey(String s) {
if(s.equalsIgnoreCase("rat")) return 1;
if(s.equalsIgnoreCase("woman") ||s.equalsIgnoreCase("child")) return 2;
if(s.equalsIgnoreCase("man")) return 3;
if(s.equalsIgnoreCase("captain")) return 4;
return -1;
}
@Override
public int compareTo(Person o) {
int dif = this.key - o.key;
return ( dif == 0) ? this.id- o.id : dif;
}
public String toString(){
return id+ " - " + name + " - " + key ;
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 7be283aa34de79c26c9e5b64cc0a6e60 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.IOException;
import java.util.Scanner;
/**
*
* @author s3ood
*/
public class Main {
public static void main(String[] args)throws IOException
{
Scanner sc = new Scanner(System.in);
int nOm = sc.nextInt();
member [] crew = new member[nOm];
for(int i=0; i<nOm; i++){
String name = sc.next();
String rankByString = sc.next();
int rank;
if(rankByString.equals("rat")){
rank = 1;
} else if(rankByString.equals("woman")){
rank = 2;
} else if(rankByString.equals("child")){
rank = 2;
} else if(rankByString.equals("man")){
rank = 3;
} else {
rank = 4;
}
crew[i] = new member(rank, i, name);
}
java.util.Arrays.sort(crew);
for(int i=0; i<nOm; i++)
System.out.println(crew[i].name);
}
}
class member implements Comparable<member>
{
int Rank;
int number;
String name;
public member(int Rank, int number, String name) {
this.Rank = Rank;
this.number = number;
this.name = name;
}
public int compareTo(member o) {
if(this.Rank < o.Rank){
return -1;
} else if(this.Rank == o.Rank && this.number < o.number){
return -1;
} else {
return 1;
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | d4e5e0edc7d83c7f6c75697752675a04 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;
/**
*
* @author Hanif
*/
public class CodeForces
{
public static void main(String args[])throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int input = Integer.parseInt(reader.readLine());
LinkedList<String> rat = new LinkedList<String>();
LinkedList<String> wochild = new LinkedList<String>();
LinkedList<String> man = new LinkedList<String>();
LinkedList<String> captain = new LinkedList<String>();
for(int i = 0; i < input; i++){
StringTokenizer token = new StringTokenizer(reader.readLine());
String temp = token.nextToken();
String stat = token.nextToken();
if(stat.equalsIgnoreCase("rat")){
rat.add(temp);
}else if(stat.equalsIgnoreCase("captain")){
captain.add(temp);
}else if(stat.equalsIgnoreCase("man")){
man.add(temp);
}else{
wochild.add(temp);
}
}
print(rat);
print(wochild);
print(man);
print(captain);
}
public static void print(LinkedList<String> l){
for(String a: l){
System.out.println(a);
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 3346b09102ce781f4a63bc54c2215cc6 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner (System.in);
int n=scn.nextInt();
crew[] cr = new crew[n];
for(int i=0;i<n;++i){
cr[i]=new crew();
cr[i].name=scn.next();
cr[i].type=scn.next();
}
for(int i=0;i<n;++i){
if(cr[i].type.equals("rat")){
System.out.println(cr[i].name);
}
}
for(int i=0;i<n;++i){
if(cr[i].type.equals("woman") || cr[i].type.equals("child")){
System.out.println(cr[i].name);
}
}
for(int i=0;i<n;++i){
if(cr[i].type.equals("man")){
System.out.println(cr[i].name);
}
}
for(int i=0;i<n;++i){
if(cr[i].type.equals("captain")){
System.out.println(cr[i].name);
}
}
scn.close();
}
}
class crew{
String name,type;
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | fe035995bff68b943608101bf8da0e5b | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class SinkingShip {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
String s=r.readLine();
String[] sp=s.split(" ");
int n=Integer.parseInt(sp[0]);
X[] x=new X[n];
for(int i=0;i<n;i++){
sp=r.readLine().split(" ");
x[i]=new X(sp[0],sp[1],i);
}
Arrays.sort(x);
for(X y:x)System.out.println(y);
}
}
class X implements Comparable<X>{
String type;
String name;
int num;
public X(String n,String t,int nm){
name=n;
type=t;
num=nm;
}
public int compareTo(X o2) {
if(this.type.equals("rat")&&o2.type.equals("rat")){
return new Integer(num).compareTo(new Integer(o2.num));
}
if(this.type.equals("rat"))return -1;
if(o2.type.equals("rat"))return 1;
if((this.type.equals("woman")||this.type.equals("child"))&&(o2.type.equals("woman")||o2.type.equals("child"))){
return new Integer(num).compareTo(new Integer(o2.num));
}
if(this.type.equals("woman")||this.type.equals("child"))return -1;
if(o2.type.equals("woman")||o2.type.equals("child"))return 1;
if(this.type.equals("man")&&o2.type.equals("man"))
return new Integer(num).compareTo(new Integer(o2.num));
if(this.type.equals("man"))return -1;
return 1;
}
public String toString(){
return name;
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | ceba747c1c1800afda8b7fbd3100ba68 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes |
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author vasudha
*/
public class NewClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> p = new ArrayList();
int n = sc.nextInt();
int i,j;
String s[] = {"rat","woman","child","man","captain"};
sc.nextLine();
for(i=0;i<n;i++) {
String k = sc.nextLine();
p.add(k);
}
//System.out.println(p);
for(j=0;j<5;j++) {
for(i=0;i<p.size();i++) {
String[] tmp = p.get(i).split(" ");
if(j==1) {
if(tmp[1].equals(s[j])||tmp[1].equals(s[j+1])) {
System.out.println(tmp[0]);
}
}
else if(tmp[1].equals(s[j])) {
System.out.println(tmp[0]);
}
}
if(j==1) j++;
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 8b12b2280bb5f61a38c3877cf3be84ca | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
ArrayList<String> rat = new ArrayList<String>();
ArrayList<String> woman = new ArrayList<String>();
ArrayList<String> man = new ArrayList<String>();
ArrayList<String> capi = new ArrayList<String>();
for(int i=0;i<n;++i){
StringTokenizer st = new StringTokenizer(in.readLine());
String nombre = st.nextToken();
String cargo = st.nextToken();
if(cargo.equals("rat"))
rat.add(nombre);
else if(cargo.equals("woman") || cargo.equals("child"))
woman.add(nombre);
else if(cargo.equals("man"))
man.add(nombre);
else
capi.add(nombre);
}
imp(rat);
imp(woman);
imp(man);
imp(capi);
}
static void imp(ArrayList<String> x){
for (int i = 0; i < x.size(); i++) {
System.out.println(x.get(i));
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 700fa5d967dde82984d39f3d2ab5e901 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes |
import java.util.Scanner;
public class prog {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int s = scan.nextInt();
String a[]= new String[s];
String b[]=new String[s];
int check[]=new int[s];
for (int i = 0; i < 2*s ; i++) {
if(i%2==0){
a[i/2]=scan.next();
check[i/2]=0;
}
else{
b[i/2]=scan.next();
}
}
for (int i = 0; i < s; i++) {
if(b[i].contains("rat")){
System.out.println(a[i]);
check[i]=1;
}
}
for (int i = 0; i < s; i++) {
if(b[i].contains("woman") || b[i].contains("child") ){
System.out.println(a[i]);
check[i]=1;
}
}
for (int i = 0; i < s; i++) {
if(b[i].contains("man") && check[i]!=1){
System.out.println(a[i]);
}
check[i]=1;
}
for (int i = 0; i < s; i++) {
if(b[i].contains("captain")){
System.out.println(a[i]);
}
}
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 25f06af7c1ec909115708b7fbf22c975 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
FastScanner kb = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
//
HashMap<String,Integer> mp = new HashMap<String, Integer>();
mp.put("captain", 3);
mp.put("man", 2);
mp.put("woman", 1);
mp.put("child", 1);
mp.put("rat", 0);
int n = kb.nextInt();
LinkedList<Person> p = new LinkedList<Person>();
for(int i=0;i<n;i++)
p.add(new Person(kb.nextString(),i,mp.get(kb.nextString())));
Collections.sort(p, new MyCompare());
for(int i=0;i<n;i++)
out.println(p.get(i).name);
//
out.close();
}
}
class MyCompare implements Comparator<Person> {
public int compare(Person o1, Person o2) {
if (o1.priority == o2.priority)
return o1.order - o2.order;
else
return o1.priority - o2.priority;
}
}
class Person {
public String name;
public int order;
public int priority;
public Person(String n, int o, int p) {
name = n;
order = o;
priority = p;
}
public String toString() {
return name + " " + order + " " + priority;
}
}
class FastScanner {
final private int BUFFER_SIZE = 1 << 19;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastScanner(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 | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | a8999dbcc927c9b5c84bc36a01befb14 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<String>[]g = new ArrayList[4];
for (int i = 0; i < 4; i++) {
g[i] = new ArrayList<String>();
}
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("rat", 0);
map.put("woman", 1);
map.put("child", 1);
map.put("man", 2);
map.put("captain", 3);
for (int i = 1; i <= n; i++) {
String name = sc.next();
int ind = map.get(sc.next());
g[ind].add(name);
}
for (int i = 0; i < 4; i++) {
for (String s : g[i]) {
System.out.println(s);
}
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 44a6db30105a440cc2a4e544cb0558c6 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes |
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class SinkingShip {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Scanner r=new Scanner(System.in);
int x=r.nextInt();
String c[][]=new String[x][2];
for(int i=0;i<x;i++){
for(int j=0;j<2;j++){
c[i][j]=r.next();
if(c[i][j].equals("rat")){
System.out.println(c[i][j-1]);
}
}
}
for(int i=0;i<x;i++){
for(int j=0;j<2;j++){
if(c[i][j].equals("woman") || c[i][j].equals("child"))
System.out.println(c[i][j-1]);
}
}
for(int i=0;i<x;i++){
for(int j=0;j<2;j++){
if(c[i][j].equals("man"))
System.out.println(c[i][j-1]);
}
}
for(int i=0;i<x;i++){
for(int j=0;j<2;j++){
if(c[i][j].equals("captain"))
System.out.println(c[i][j-1]);
}
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 591d069d30ea434eace926e3f6997277 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes |
import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.LinkedList;
public class C063A {
public void solve() throws Exception {
int n = nextInt();
String[] s = new String[n];
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
s[i] = nextWord();
String c = nextWord();
if (c.equals("woman")) {
arr[i] = 1;
}
if (c.equals("child")) {
arr[i] = 1;
}
if (c.equals("man")) {
arr[i] = 2;
}
if (c.equals("captain")) {
arr[i] = 3;
}
}
for (int i = 0; i <= 3; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[j] == i) {
println(s[j]);
}
}
}
}
// ------------------------------------------------------
void debug(Object... os) {
System.err.println(Arrays.deepToString(os));
}
void print(Object... os) {
if (os != null && os.length > 0)
System.out.print(os[0].toString());
for (int i = 1; i < os.length; ++i)
System.out.print(" " + os[i].toString());
}
void println(Object... os) {
print(os);
System.out.println();
}
BufferedInputStream bis = new BufferedInputStream(System.in);
String nextWord() throws Exception {
char c = (char) bis.read();
while (c <= ' ')
c = (char) bis.read();
StringBuilder sb = new StringBuilder();
while (c > ' ') {
sb.append(c);
c = (char) bis.read();
}
return new String(sb);
}
String nextLine() throws Exception {
char c = (char) bis.read();
while (c <= ' ')
c = (char) bis.read();
StringBuilder sb = new StringBuilder();
while (c != '\n' && c != '\r') {
sb.append(c);
c = (char) bis.read();
}
return new String(sb);
}
int nextInt() throws Exception {
return Integer.parseInt(nextWord());
}
long nextLong() throws Exception {
return Long.parseLong(nextWord());
}
public static void main(String[] args) throws Exception {
new C063A().solve();
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | a59664c216a5046c39a283cbff8ca180 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static java.lang.Integer.parseInt;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class NewClass {
static class escaner
{
BufferedReader in;
StringTokenizer st;
public escaner() {
in=new BufferedReader(new InputStreamReader(System.in));
st=new StringTokenizer("");
}
public int nextInt() throws IOException
{
if(st.hasMoreTokens())return Integer.parseInt(st.nextToken());
else
{ st=new StringTokenizer(in.readLine());
return nextInt();
}
}
public String next() throws IOException
{
if(st.hasMoreTokens())return st.nextToken();
else
{ st=new StringTokenizer(in.readLine());
return next();
}
}
}
public static void main(String[] args) throws Throwable {
escaner sc=new escaner();
int n=sc.nextInt();
String a,b;
ArrayList<String>cap=new ArrayList<String>();
ArrayList<String>womchi=new ArrayList<String>();
ArrayList<String>rat=new ArrayList<String>();
ArrayList<String>man=new ArrayList<String>();
for (int i = 0; i < n; i++) {
a=sc.next();
b=sc.next();
if(b.equals("man"))
man.add(a);
else
if(b.equals("captain"))
cap.add(a);
else
if(b.equals("rat"))
rat.add(a);
else
womchi.add(a);
}
for (int i = 0; i < rat.size(); i++) {
System.out.println(rat.get(i));
}
for (int i = 0; i < womchi.size(); i++) {
System.out.println(womchi.get(i));
}
for (int i = 0; i < man.size(); i++) {
System.out.println(man.get(i));
}
for (int i = 0; i < cap.size(); i++) {
System.out.println(cap.get(i));
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 27d5928ed40b3fb1c1802f48d7e2f8f7 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Collection;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class CF59A implements Runnable{
public static void main(String args[]){
new CF59A().run();
}
@Override
public void run(){
try{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = null;
solve();
in.close();
out.close();
}
catch(IOException e){
e.printStackTrace();
System.exit(0);
}
}
int nextInt()throws IOException{
return Integer.parseInt(nextToken());
}
double nextDouble()throws IOException{
return Double.parseDouble(nextToken());
}
long nextLong() throws IOException{
return Long.parseLong(nextToken());
}
String nextToken()throws IOException{
while(tok == null || !tok.hasMoreTokens()){
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
private void solve()throws IOException{
int N = nextInt();
String[] name = new String[N];
String[] type = new String[N];
for(int i = 0; i < N; i++){
name[i] = nextToken();
type[i] = nextToken();
}
ArrayList<String> l = new ArrayList<String>();
for(int i = 0; i < N; i++){
if(type[i].equals("rat"))l.add(name[i]);
}
for(int i = 0; i< N; i++){
if(type[i].equals("woman") || type[i].equals("child"))l.add(name[i]);
}
for(int i = 0; i < N; i++){
if(type[i].equals("man"))l.add(name[i]);
}
for(int i = 0; i < N; i++){
if(type[i].equals("captain"))l.add(name[i]);
}
for(int i = 0; i < l.size(); i++){
out.println(l.get(i));
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 49b281863f8764da9fe9c8d42ad6c59c | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Scanner;
//Mx
public class Main {
public static void main(String[] args)throws IOException {
Scanner scanner = new Scanner(new BufferedInputStream(System.in));
int crewMembers = scanner.nextInt();
Member [] crew = new Member[crewMembers];
for(int i=0; i<crewMembers; i++){
crew[i] = new Member(i, scanner.next(), scanner.next());
}
java.util.Arrays.sort(crew);
for(int i=0; i<crewMembers; i++){
System.out.println(crew[i].name);
}
}
}
class Member implements Comparable<Member>{
int number;
String name;
int status;
public Member(int number, String name, String status) {
this.number = number;
this.name = name;
if(status.equals("rat")){
this.status = 0;
} else if(status.equals("woman")){
this.status = 1;
} else if(status.equals("child")){
this.status = 1;
} else if(status.equals("man")){
this.status = 2;
} else {
this.status = 3;
}
}
@Override
public int compareTo(Member o) {
if(this.status < o.status){
return -1;
} else if(this.status == o.status && this.number < o.number) {
return -1;
} else {
return 1;
}
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 9517541534841641478d86d393af159b | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes |
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args)throws IOException {
Scanner scanner = new Scanner(new BufferedInputStream(System.in));
int crewMembers = scanner.nextInt();
Member [] crew = new Member[crewMembers];
for(int i=0; i<crewMembers; i++){
crew[i] = new Member(i, scanner.next(), scanner.next());
}
java.util.Arrays.sort(crew);
for(int i=0; i<crewMembers; i++){
System.out.println(crew[i].name);
}
}
}
class Member implements Comparable<Member>{
int number;
String name;
int status;
public Member(int number, String name, String status) {
this.number = number;
this.name = name;
if(status.equals("rat")){
this.status = 0;
} else if(status.equals("woman")){
this.status = 1;
} else if(status.equals("child")){
this.status = 1;
} else if(status.equals("man")){
this.status = 2;
} else {
this.status = 3;
}
}
@Override
public int compareTo(Member o) {
if(this.status < o.status){
return -1;
} else if(this.status == o.status && this.number < o.number) {
return -1;
} else {
return 1;
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | cfe699791c337301713274230f30fd8d | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.*;
public class SinkingShip {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
int n=input.nextInt();
String []s=new String[n];
String []s1=new String[n];
int []a=new int[n];
for(int i=0;i<n;i++){
s[i]=input.next();
s1[i]=input.next();
if(s1[i].equals("rat"))
a[i]=4;
else if(s1[i].equals("woman")||s1[i].equals("child"))
a[i]=3;
else if(s1[i].equals("man"))
a[i]=2;
else if(s1[i].equals("captain"))
a[i]=1;
}
for(int i=0;i<a.length;i++){
if(a[i]==4)
System.out.println(s[i]);
}
for(int i=0;i<a.length;i++){
if(a[i]==3)
System.out.println(s[i]);
}
for(int i=0;i<a.length;i++){
if(a[i]==2)
System.out.println(s[i]);
}
for(int i=0;i<a.length;i++){
if(a[i]==1)
System.out.println(s[i]);
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | ad9ad72b0702b025204ab9d8b8dd9d8a | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.Hashtable;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String cad[] = new String[n];
String tipo[]=new String[n];
Hashtable<String, Integer>lista=new Hashtable<String,Integer>();
for (int i = 0; i < cad.length; i++) {
cad[i]=scan.next();
tipo[i]=scan.next();
if(tipo[i].equals("rat") && !lista.contains(cad[i])){
System.out.println(cad[i]);
lista.put(cad[i],i);
}
}
for (int i = 0; i < tipo.length; i++) {
if(tipo[i].equals("woman") || tipo[i].equals("child") && !lista.contains(cad[i])){
System.out.println(cad[i]);
lista.put(cad[i],i);
}
}
for (int i = 0; i < tipo.length; i++) {
if(tipo[i].equals("man") && !lista.contains(cad[i])){
System.out.println(cad[i]);
lista.put(cad[i],i);
}
}
for (int i = 0; i < tipo.length; i++) {
if(tipo[i].equals("captain") && !lista.contains(cad[i])){
System.out.println(cad[i]);
lista.put(cad[i],i);
}
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 6d3649ab9d81d03dcb0253ea18c0b011 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.*;
public class Main {
public static void main (String [] arg) {
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();
if (s[i][1].equals("rat")) System.out.println(s[i][0]);
}
for (int i = 0; i<N; ++i) if (s[i][1].equals("woman") || s[i][1].equals("child")) System.out.println(s[i][0]);
for (int i = 0; i<N; ++i) if (s[i][1].equals("man")) System.out.println(s[i][0]);
for (int i = 0; i<N; ++i) if (s[i][1].equals("captain")) System.out.println(s[i][0]);
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | bcf6c15462b6a9f7900ab631f5b74879 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class LOL {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
String[] names = new String[N];
String[] type = new String[N];
for (int i=0; i<N; i++) {
names[i] = in.next();
type[i] = in.next();
}
for (int i=0; i<N; i++)
if (type[i].equals("rat"))
System.out.println(names[i]);
for (int i=0; i<N; i++)
if (type[i].equals("woman") || type[i].equals("child"))
System.out.println(names[i]);
for (int i=0; i<N; i++)
if (type[i].equals("man"))
System.out.println(names[i]);
for (int i=0; i<N; i++)
if (type[i].equals("captain"))
System.out.println(names[i]);
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | cb8e6003559ab57bead09691844642ce | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 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 [n+1];
String [] ss= new String [n+1];
for (int i = 1; i <=n; i++) {
s[i]=sc.next();
ss[i]=sc.next();
}
for (int i = 1; i <=n; i++) {
if(ss[i].equals("rat")){
System.out.println(s[i]);
}
}
for (int i = 1; i <=n; i++) {
if(ss[i].equals("child")||ss[i].equals("woman")){
System.out.println(s[i]);
}
}
for (int i = 1; i <=n; i++) {
if(ss[i].equals("man")){
System.out.println(s[i]);
}
}
for (int i = 1; i <=n; i++) {
if(ss[i].equals("captain")){
System.out.println(s[i]);
}
}
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 49fa666db227c125507512cd1f6a9fde | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.Scanner;
public class problem63A {
private static class Person {
public String name;
public int order;
public int type;
public Person(String name, int order, String type) {
this.name = name;
this.order = order;
if ("rat".equals(type)) {
this.type = 0;
return;
}
if ("child".equals(type)) {
this.type = 1;
return;
}
if ("woman".equals(type)) {
this.type = 1;
return;
}
if ("man".equals(type)) {
this.type = 2;
return;
}
this.type = 3;
}
public Person(String name, int order, int type) {
this.name = name;
this.order = order;
this.type = type;
return;
}
public boolean isGreater(Person person) {
if (this.type > person.type)
return true;
else
if ((this.type == person.type) && (this.order > person.order))
return true;
return false;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int i;
int j;
in.nextLine();
Person [] ship = new Person [n];
for (i = 0; i < n; i++) {
String str = in.nextLine();
String [] strs = str.split(" ");
ship[i] = new Person(strs[0], i, strs[1]);
}
in.close();
for (i = 0; i < n - 1; i++)
for (j = i + 1; j < n; j++)
if (ship[i].isGreater(ship[j])) {
Person tmp = new Person(ship[i].name, ship[i].order, ship[i].type);
ship[i] = ship[j];
ship[j] = tmp;
}
for (i = 0; i < n; i++)
System.out.println(ship[i].name);
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | df782578be82d0e49383157317b27163 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.Scanner;
public class SinkingShip {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
int n = scan.nextInt();
Member[] array = new Member[n];
for (int i = 0; i < array.length; i++) {
array[i] = new Member(scan.next(), scan.next());
}
for (int i = 0; i < array.length; i++) {
if (array[i].type.equals("rat"))
System.out.println(array[i].name);
}
for (int i = 0; i < array.length; i++) {
if (array[i].type.equals("woman") || array[i].type.equals("child"))
System.out.println(array[i].name);
}
for (int i = 0; i < array.length; i++) {
if (array[i].type.equals("man"))
System.out.println(array[i].name);
}
for (int i = 0; i < array.length; i++) {
if (array[i].type.equals("captain"))
System.out.println(array[i].name);
}
}
}
}
class Member {
String name;
String type;
public Member(String name, String type) {
this.name = name;
this.type = type;
}
public String toString() {
return name;
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 0620cc1d9a02403680f58bbe7410d687 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.*;
import java.util.*;
public class sinkingship
{ static int n;
static String cap;
public static void main(String args[]) throws IOException
{
BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(cin.readLine());
int f=n;
String[] ar=new String[n];
int r=0;
String[] woman=new String[n];
String[] man=new String[n];
int wo=0;
int ma=0;
while(n-->0)
{
String s=cin.readLine();
ar[r]=s;
r++;
}
int u=0;
for(int m=0;m<f;m++)
{
String[] name=ar[m].split(" ");
int real_prior=priority(ar[m]);
if(real_prior==1)
{
System.out.println(name[0]);
}
else if(real_prior==2)
{
woman[wo]=name[0];
wo++;
}
else if(real_prior==3)
{
man[ma]=name[0];
ma++;
}
else
{
cap=name[0];
}
}
for(int m=0;m<wo;m++)
System.out.println(woman[m]);
for(int m=0;m<ma;m++)
System.out.println(man[m]);
System.out.println(cap);
}
static int priority(String s)
{
String s1=s;
String[] tok=s1.split(" ");
String sta=tok[1];
int prior=0;
if(sta.equalsIgnoreCase("captain"))
{
prior=4;
}
else if(sta.equalsIgnoreCase("rat"))
{
prior=1;
}
else if(sta.equalsIgnoreCase("woman") || sta.equalsIgnoreCase("child"))
{
prior=2;
}
else
{
prior=3;
}
return prior;
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | b319ae7d0d0ed3acee070dcae4c4e291 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Scanner;
import java.util.Comparator;
public class A59 {
public void solve() {
Scanner sc = new Scanner(System.in);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int i = 0, j = 0, k = 0;
int n = sc.nextInt();
Hashtable<String,Integer> hst = new Hashtable<String, Integer>();
hst.put("captain", 4);
hst.put("rat", 1);
hst.put("child", 2);
hst.put("woman", 2);
hst.put("man", 3);
int count=0;
String s[][] = new String[n][2];
for(i=0;i<n;++i){
s[i][0]=sc.next();
s[i][1]=hst.get(sc.next())+"";
}
int a[][] = new int[n][2];
Arrays.sort(s,new Comparator<String []>() {
@Override
public int compare(String[] o1, String[] o2) {
int a1= Integer.valueOf(o1[1]);
int a2= Integer.valueOf(o2[1]);
if(a1>a2){
return 1;
}else{
return -1;
}
}
});
for(i=0;i<n;++i){
System.out.println(s[i][0]);
//s[i][1]=hst.get(sc.next())+"";
}
}
public static void main(String[] args) {
new A59().solve();
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | c83f10e57b15004efb774412cc0a0918 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes |
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Formatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
public static class Pers
{
String name, type;
public Pers (String n, String t)
{
name=n;
type=t;
}
}
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(bf.readLine());
ArrayList<Pers> ps=new ArrayList<Pers>();
for(int i=0; i<n; i++)
{
StringTokenizer stk=new StringTokenizer(bf.readLine());
ps.add(new Pers(stk.nextToken(),stk.nextToken()));
}
for(int i=0; i<n; i++)
{
if(ps.get(i).type.equals("rat"))
pw.println(ps.get(i).name);
}
for(int i=0; i<n; i++)
{
if(ps.get(i).type.equals("woman")||ps.get(i).type.equals("child"))
pw.println(ps.get(i).name);
}
for(int i=0; i<n; i++)
{
if(ps.get(i).type.equals("man"))
pw.println(ps.get(i).name);
}
for(int i=0; i<n; i++)
{
if(ps.get(i).type.equals("captain"))
pw.println(ps.get(i).name);
}
pw.flush();
}
}
/*
3
4 3 20
100 200 10 305
0 1 0.25
1 2 0.1
2 0 0.75
*
*/ | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 0199f8313893ae9bdceed80881053998 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.*;
import java.util.*;
public class Round59Div2_A_ {
private void solve() throws IOException {
int n = Integer.parseInt(stdin.readLine());
ArrayList <String> rats = new ArrayList <String>();
ArrayList<String> women = new ArrayList<String>();
ArrayList<String> men = new ArrayList<String>();
ArrayList<String> captains = new ArrayList<String>();
for(int i = 0 ; i<n ; i++) {
String s = stdin.readLine();
String [] f = s.split(" ");
if (f[1].equals("rat"))rats.add(f[0]);
else if (f[1].equals("man"))men.add(f[0]);
else if (f[1].equals("woman"))women.add(f[0]);
else if (f[1].equals("child"))women.add(f[0]);
else if (f[1].equals("captain"))captains.add(f[0]);
}
for (int i = 0; i < rats.size(); i++) {
out.println(rats.get(i));
out.flush();
}
for (int i = 0; i < women.size(); i++) {
out.println(women.get(i));
out.flush();
}
for (int i = 0; i < men.size(); i++) {
out.println(men.get(i));
out.flush();
}
for (int i = 0; i < captains.size(); i++) {
out.println(captains.get(i));
out.flush();
}
}
BufferedReader stdin;
PrintWriter out;
public void run1() throws IOException {
stdin = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
stdin.close();
}
public void run2() throws IOException {
stdin = new BufferedReader(new FileReader(".in"));
out = new PrintWriter(new BufferedWriter(new FileWriter(".out")));
solve();
out.close();
stdin.close();
}
public static void main(String[] args) throws IOException {
new Round59Div2_A_().run1();
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 6e97d98f8737fa014b8178b9c1c22c0d | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class A063 {
static class guy implements Comparable<guy> {
String name, rank;
int pos;
public guy(String a, String b, int aa) {
name = a;
rank = b;
pos = aa;
}
public int compareTo(guy o) {
int p = priority(), po = o.priority();
if (p == po) {
return pos - o.pos;
}
return p - po;
}
public int priority() {
String s = rank;
if (s.equals("rat"))
return 0;
if (s.equals("man"))
return 2;
if (s.equals("captain"))
return 3;
return 1;
}
}
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
guy[] g = new guy[n];
for(int x = 0;x<n;x++) {
g[x] = new guy(in.next(),in.next(),x);
}
Arrays.sort(g);
for(guy gg:g) System.out.println(gg.name);
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 95807a1a0f72677cc958659f6ba79cd5 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
public class SinkingShip {
public static void main( final String[] args ) throws IOException {
final BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
final int n = Integer.parseInt( br.readLine() );
final ArrayList<CrewMember> list = new ArrayList<CrewMember>();
for ( int i = 0; i < n; ++i ) {
list.add( new CrewMember( br.readLine(), i ) );
}
Collections.sort( list );
for ( final CrewMember crewMember : list ) {
System.out.println( crewMember.name );
}
}
private static final class CrewMember implements Comparable<CrewMember> {
private final String name;
private final int category;
private final int n;
private CrewMember( final String s, final int n ) {
final String[] parts = s.split( " " );
this.name = parts[ 0 ];
this.category = decode( parts[ 1 ] );
this.n = n;
}
@Override
public int compareTo( final CrewMember cm ) {
if ( this.category == cm.category )
return Integer.valueOf( this.n ).compareTo( cm.n );
return Integer.valueOf( this.category ).compareTo( cm.category );
}
}
public static int decode( final String s ) {
if ( "rat".equals( s ) )
return 1;
else if ( "woman".equals( s ) || "child".equals( s ) )
return 2;
else if ( "man".equals( s ) )
return 3;
else if ( "captain".equals( s ) )
return 4;
else
throw new IllegalArgumentException( "category='" + s + '\'' );
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | 9cb7395ad0ae5740ea8b55a32c7a5e42 | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class B {
static class Scanner{
BufferedReader br=null;
StringTokenizer tk=null;
public Scanner(){
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException{
while(tk==null || !tk.hasMoreTokens())
tk=new StringTokenizer(br.readLine());
return tk.nextToken();
}
public int nextInt() throws NumberFormatException, IOException{
return Integer.valueOf(next());
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.valueOf(next());
}
}
public static void main(String args[]) throws NumberFormatException, IOException{
Scanner sc = new Scanner();
int N = sc.nextInt();
LinkedList<String> rats = new LinkedList<String>();
LinkedList<String> woman = new LinkedList<String>();
LinkedList<String> captain = new LinkedList<String>();
LinkedList<String> man = new LinkedList<String>();
for(int i = 0; i < N; i++){
String name = sc.next();
String prf = sc.next();
if (prf.equals("captain"))
captain.add(name);
else if (prf.equals("woman") || prf.equals("child"))
woman.add(name);
else if (prf.equals("man"))
man.add(name);
else
rats.add(name);
}
for(String e: rats)
System.out.println(e);
for(String e: woman)
System.out.println(e);
for(String e: man)
System.out.println(e);
for(String e: captain)
System.out.println(e);
}
}
| Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output | |
PASSED | f3dd6daeeefc904b3047c8426a699cde | train_000.jsonl | 1298908800 | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class JavaApplication11 {
public static void main(String[] args) throws IOException {
BufferedReader I = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(I.readLine());
ArrayList<String> w = new ArrayList<String>();
ArrayList<String> m = new ArrayList<String>();
String c="";
while (n > 0) {
n--;
String[] a = I.readLine().split(" ");
if (a[1].equals("rat")) {
System.out.println(a[0]);
}
if (a[1].equals("woman") || a[1].equals("child")) {
w.add(a[0]);
}
if (a[1].equals("man")) {
m.add(a[0]);
}
if(a[1].equals("captain")){
c=a[0];
}
}
while(!w.isEmpty()){
System.out.println(w.remove(0));
}
while(!m.isEmpty()){
System.out.println(m.remove(0));
}
System.out.println(c);
}
} | Java | ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"] | 2 seconds | ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"] | null | Java 6 | standard input | [
"implementation",
"sortings",
"strings"
] | 753113fa5130a67423f2e205c97f8017 | The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. | 900 | Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.