exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
βŒ€
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
βŒ€
difficulty
int64
-1
3.5k
βŒ€
prob_desc_output_spec
stringlengths
17
1.47k
βŒ€
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
5056adca2d25519d97e726e9836af8b6
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Magnets { public static void main(String[] args) { Scanner in = new Scanner(System.in); int magnets = Integer.parseInt(in.nextLine()), groups = 1; String[] magnetArray = new String[magnets]; for(int i = 0; i < magnetArray.length; i++) { magnetArray[i] = in.nextLine(); if(i > 0) { if(!magnetArray[i].equals(magnetArray[i - 1])) groups++; } } System.out.println(groups); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
85667c29c44a1b29b8335b132cce4de6
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Magnets { public static void main(String args[]) throws IOException { Scanner in = new Scanner(System.in); int n = in.nextInt(); int magnets[] = new int[n]; for (int i = 0; i < n; i++) { magnets[i] = in.nextInt(); } int groups = 1; for (int i = 0; i < n - 1; i++) { if (magnets[i] != magnets[i + 1]) { groups++; } } System.out.println(groups); in.close(); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
0bd30ac00849ca7d4a33878e380b33b4
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.io.*; import java.util.*; public class GFG { public static void main (String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String[] arr = new String[n]; int s = 0; scan.nextLine(); if(n==1){ System.out.println("1"); } else{ for(int i=0;i<n;i++){ arr[i] = scan.nextLine(); } for(int i=0;i<n-1;i++){ String a= arr[i]; String b = arr[i+1]; if( a.equals(b) ){ continue; } else{ s+=1; } } System.out.println(s+1); } } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
94ea5b696a6da0d85ed39ec61a754e77
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Codeforces344A_Mock { public static void main(String args[]) { Scanner input = new Scanner(System.in); int n = input.nextInt(); input.nextLine(); int count = 0; int i; char orient2 = input.nextLine().charAt(0); char orient; for (i = 1; i < n; i++) { orient = orient2; orient2 = input.nextLine().charAt(0); if (orient != orient2) count++; } System.out.println(count + 1); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
8dbd0d267e9bcc9b4b275135287e5449
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class intInput { 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 y = 1; for(int i = 1; i < n; i++) { if(a[i - 1] != a[i]) y++; } System.out.println(y); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
9c4583d5bc91f0a016a3790d3dcb2157
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //http://codeforces.com/problemset/problem/344/A public class Problem344A { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int numOfMagnets = Integer.parseInt(reader.readLine()); if(numOfMagnets <= 0) { System.out.println(0); return; } if(numOfMagnets == 1) { reader.readLine(); System.out.println(1); return; } int countGroup = 1; String previousMagnet = reader.readLine(); String currentMagnet = reader.readLine(); if(!currentMagnet.equals(previousMagnet)) countGroup++; for (int i = 0; i < numOfMagnets - 2; i++) { previousMagnet = currentMagnet; currentMagnet = reader.readLine(); if(!currentMagnet.equals(previousMagnet)) countGroup++; } System.out.println(countGroup); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
e73941f0c64434798844699775cf6588
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Main { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); String a[] = new String[m]; for (int i = 0; i < m; i++) { a[i] = sc.next(); } int count =1; for (int i = 1; i < m; i++) { if (a[i].equals(a[i - 1])) continue; else count++; } System.out.print(count); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
62205513cb181289504a29b1095fc1b2
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.*; public class A { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int res = 1; int cur = scanner.nextInt(); for(int i =0;i<n-1;i++){ int curtemp = scanner.nextInt(); if(cur != curtemp){ res++; cur = curtemp; } } System.out.println(res); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
1610fc78e07e88a57a975ea422c5d129
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; /** * * @author GTS */ public class GirlsAndBoys { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner in=new Scanner(System.in); int num=in.nextInt(); int m=0; int count=0; for (int i = 0; i < num; i++) { int h=in.nextInt(); if(!(h==m)) count++; m=h; } System.out.println(count); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
c5041ebf83b0835f605f0ec3a6bf0694
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; /** * * @author Hoang IT */ public class Main { public static void main(String args[]){ // System.out.println("Nhap chieu dai cua khan dai:"); Scanner sc = new Scanner(System.in); int w = sc.nextInt(); String rac = sc.nextLine(); String arr[] = new String[w]; for(int i = 0; i<w; i++){ arr[i] = sc.nextLine(); } int soKhoiNamCham = 1; for(int i=0; i<w-1;i++){ if(arr[i].charAt(0) != arr[i+1].charAt(0)){ soKhoiNamCham++; } } System.out.println(soKhoiNamCham); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
7c14753763ae3b87ed331c9f8bf8263a
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.*; import java.lang.*; public class Main { public static void main (String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int count = 1; int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); if (i > 0 && ((a[i - 1] == 10 && a[i] == 01) || (a[i - 1] == 01 && a[i] == 10))) count++; } System.out.print(count); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
465f030fa9090c5dfd12c6bc59959721
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
//package com.company; import java.util.ArrayList; import java.util.LinkedList; import com.sun.security.jgss.GSSUtil; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); // LinkedList<Integer> linkedList = new LinkedList<>(); // StringBuilder stringBuilder = new StringBuilder(); // BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); Scanner scanner = new Scanner(System.in); int x = scanner.nextInt(); int[] array = new int[x]; for(int i = 0 ; i< array.length;i++){ array[i] = scanner.nextInt(); list.add(array[i]); } int k = 0 ; if(x==1){ k = 1; System.out.println(k); }else { for (int i = 1; i < array.length; i++) { if (!list.get(i - 1).equals(list.get(i))) { k++; } } System.out.println(k+1); } } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
5528acfee54633cdb23a3875ae2e3698
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); String[] a=new String[t]; for(int i=0;i<t;i++) { a[i]=sc.next(); } int c=1; for(int i=0;i<t-1;i++) { if(!(a[i].equals(a[i+1]))) { c++; } } System.out.println(c); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
e7c2c9463c17ccd8a5963c9305cf9fcd
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] shy){ Scanner s = new Scanner(System.in); int n = s.nextInt(); int arr[] = new int[n]; for(int i = 0; i < n; i++) arr[i] = s.nextInt(); int res = 0; for(int i = 0;i < n - 1;i++){ if(arr[i] != arr[i + 1]) res++; } res++; System.out.println(res); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
d18bb628d372fd4c8e694d2f8c6366e4
train_002.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.util.*; import java.io.InputStreamReader; public class magnets { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; for(int i=0;i<n;i++){ a[i] = sc.nextInt(); } int count=1; for(int i=0;i<n-1;i++){ if(a[i]!=a[i+1]) count++; } System.out.println(count); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
1d9330c59e6b536db57f4580da011ff9
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
import java.util.ArrayList; import java.util.Scanner; public class A_Winner { public static void main(String[] args) { Scanner in = new Scanner(System.in); //players names ArrayList <String> names=new ArrayList<String>(); // Accumulated scores of players names in names array //note that the score at index 0 in scores array is the score of player at index 0 //at names array ArrayList <Integer> scores=new ArrayList<Integer>(); //there is a one to one correspondence between indices of roundNames and //roundScores arrays ArrayList <String> roundNames=new ArrayList<String>(); //rounds names ArrayList <Integer> roundScores=new ArrayList<Integer>(); // rounds scores // names that has a score equal to the max score at the end ArrayList <String> maxNames=new ArrayList<String>(); int n = in.nextInt(); for(int i = 0; i < n; i++) { String name = in.next(); int score = in.nextInt(); roundNames.add(name); roundScores.add(score); if(names.contains(name)) { int index = names.indexOf(name); int newScore = scores.get(index) + score; scores.set(index, newScore); } else { names.add(name); scores.add(score); } } //max value of scores int max = getMaxValue(scores); //names that have max value at the end of the game for(int i = 0; i < scores.size(); i++) { if(max == scores.get(i)) maxNames.add(names.get(i)); } names.clear(); scores.clear(); for(int i = 0; i < n; i++) { String roundName = roundNames.get(i); int roundScore = roundScores.get(i); if(names.contains(roundName)) { int index = names.indexOf(roundName); int newScore = scores.get(index) + roundScore; if(newScore >= max && maxNames.contains(roundName)) { System.out.println(roundName); break; } scores.set(index, newScore); } else { names.add(roundName); scores.add(roundScore); if(roundScore >= max && maxNames.contains(roundName)) { System.out.println(roundName); break; } } } } private static int getMaxValue(ArrayList<Integer> scores) { int max = Integer.MIN_VALUE; for(int element : scores) { if(element > max) max = element; } return max; } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
6589cbe09c55520bc4104b15e6be7176
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
import java.util.*; import java.util.Map.Entry; public class P2A { public static void main(String [] args) { String[]strs = new String[1001]; int[] scores = new int[1001]; Map<String , Integer> mp = new TreeMap<String , Integer>(); Map<String , Integer> mp2 = new TreeMap<String , Integer>(); Set<String> set = new TreeSet<String>(); int max = Integer.MIN_VALUE; Scanner input = new Scanner(System.in); int n = input.nextInt(); for(int i = 0 ; i<n ; i++) { String str = input.next(); int score = input.nextInt(); strs[i] = str; scores[i] = score; addM(str , mp , score); } String test = ""; Iterator<Entry<String , Integer>> it = mp.entrySet().iterator(); while(it.hasNext()) { Entry<String , Integer> entry = it.next(); int som = entry.getValue(); if(max<som) { max = som; test = entry.getKey(); } } int c = 0; int i1; while(true){ addM(strs[c] , mp2 , scores[c]); if(mp.get(strs[c])==max) { if(mp2.get(strs[c])>=max){ i1 = n; break; } } c++; } System.out.println(strs[c]); return; } public static void addM(String str , Map<String , Integer> mp , int val) { if(mp.containsKey(str)) mp.put(str, mp.get(str)+val); else mp.put(str , val); } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
2de36aa28d462dbfa4cf1009bda0661c
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
import java.util.*; import java.util.Map.Entry; public class P2A { public static void main(String [] args) { String[]strs = new String[1001]; int[] scores = new int[1001]; Map<String , Integer> mp = new TreeMap<String , Integer>(); Map<String , Integer> mp2 = new TreeMap<String , Integer>(); Set<String> set = new TreeSet<String>(); int max = Integer.MIN_VALUE; Scanner input = new Scanner(System.in); int n = input.nextInt(); for(int i = 0 ; i<n ; i++) { String str = input.next(); int score = input.nextInt(); strs[i] = str; scores[i] = score; addM(str , mp , score); } String test = ""; Iterator<Entry<String , Integer>> it = mp.entrySet().iterator(); while(it.hasNext()) { Entry<String , Integer> entry = it.next(); int som = entry.getValue(); if(max<som) { max = som; test = entry.getKey(); } } int c = 0; int i1; while(true){ addM(strs[c] , mp2 , scores[c]); if(mp.get(strs[c])>=max) { if(mp2.get(strs[c])>=max){ i1 = n; break; } } c++; } System.out.println(strs[c]); return; } public static void addM(String str , Map<String , Integer> mp , int val) { if(mp.containsKey(str)) mp.put(str, mp.get(str)+val); else mp.put(str , val); } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
02e5d23ed313690ca077f6355cbe4574
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
import java.util.*; import java.util.Map.Entry; public class P2A { public static void main(String[] args) { String[] strs = new String[1001]; int[] scores = new int[1001]; Map<String, Integer> mp = new TreeMap<String, Integer>(); Map<String, Integer> mp2 = new TreeMap<String, Integer>(); Set<String> set = new TreeSet<String>(); int max = Integer.MIN_VALUE; Scanner input = new Scanner(System.in); int n = input.nextInt(); for (int i = 0; i < n; i++) { String str = input.next(); int score = input.nextInt(); strs[i] = str; scores[i] = score; addM(str, mp, score); } String test = ""; Iterator<Entry<String, Integer>> it = mp.entrySet().iterator(); while (it.hasNext()) { Entry<String, Integer> entry = it.next(); int som = entry.getValue(); if (max < som) { max = som; test = entry.getKey(); } } int c = 0; int i1; while (true) { addM(strs[c], mp2, scores[c]); if (mp.get(strs[c]) == max && mp2.get(strs[c]) >= max) { break; } c++; } System.out.println(strs[c]); } public static void addM(String str, Map<String, Integer> mp, int val) { if (mp.containsKey(str)) { mp.put(str, mp.get(str) + val); } else { mp.put(str, val); } } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
666528c6937679d9acd106fe518952d3
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.Scanner; /** * * @author edwardhui */ public class Test { static int n; public static void main(String[] args) { Scanner keybroad = new Scanner(System.in); n = Integer.parseInt(keybroad.nextLine()); String[] name = new String[n]; int[] mark = new int[n]; for (int i = 0; i < n; i++) { String lines = keybroad.nextLine(); String[] strs = lines.trim().split("\\s+"); name[i] = strs[0]; mark[i] = Integer.parseInt(strs[1]); } String[] finalName = new String[n]; int[] finalMark = new int[n]; int[][][] late = new int[n][2][n]; int[] count = new int[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < n; k++) { late[i][j][k] = -1; } } } for (int j = 0; j < n; j++) { boolean saved = false; for (int k = 0; k < n; k++) { if (name[j].equals(finalName[k])) { saved = true; finalMark[k] += mark[j]; for (int x = 0; x < n; x++) { if (late[k][0][x] == -1) { late[k][0][x] = finalMark[k]; late[k][1][x] = j; break; } } } } if (!saved) { for (int k = 0; k < n; k++) { if (finalName[k] == null) { finalName[k] = name[j]; finalMark[k] += mark[j]; for (int x = 0; x < n; x++) { if (late[k][0][x] == -1) { late[k][0][x] = finalMark[k]; late[k][1][x] = j; break; } } break; } } } } findMax(finalMark, finalName, late); } static void findMax(int[] a, String[] b, int[][][] c) { int currentMax = 0, currentIndex = 0; for (int i = 0; i < b.length; i++) { if (currentMax < a[i]) { currentIndex = i; } if (currentMax == a[i]) { boolean flag = false; for (int k = 0; k < n; k++) { if (c[i][0][k] >= currentMax) { for (int m = 0; m < n; m++) { if (c[currentIndex][0][m] >= currentMax) { if (c[i][1][k] < c[currentIndex][1][m] && c[i][1][k] != -1) { flag = true; break; } if (c[i][1][k] == c[currentIndex][1][m] && c[i][0][k] > c[currentIndex][0][m]) { flag = true; break; } break; } } if (flag) { break; } } } if (flag) { currentIndex = i; } } currentMax = Math.max(currentMax, a[i]); } System.out.println(b[currentIndex]); } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
f41147a747afac165faee379f1061338
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
import java.util.*; public class MA { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=0; n=input.nextInt(); ArrayList<String>names=new ArrayList<>(); ArrayList<Integer>scores=new ArrayList<>(); for(int i=0;i<n;i++) { names.add(input.next()); scores.add(input.nextInt()); } HashMap<String, Integer> map=new HashMap<>(); ArrayList<String> equal_player=new ArrayList<>(); for(int i=0;i<n;i++) { String name=names.get(i); if(map.containsKey(name)) { int value= map.get(name); map.put(name,scores.get(i)+value); } else { map.put(name,scores.get(i)); } } boolean flage=false; Set keys=map.keySet(); Iterator<String> iterator=keys.iterator(); iterator.hasNext(); String v=iterator.next(); String index=v; int score=map.get(v); String value=""; //System.out.println(v+" val "+score); equal_player.add(index); while (iterator.hasNext()) { value=iterator.next(); int s=map.get(value); //System.out.println(value+" val "+s); if(s>score) { index=value; score=s; flage=true; } else if(s==score) { flage=false; equal_player.add(value); } } if(flage) { System.out.println(index); } else { HashMap<String, Integer> hashMap=new HashMap<>(); for(int i=0;i<equal_player.size();i++) { int maxx =0; String s=equal_player.get(i); for(int j=0;j<names.size();j++) { if(s.equals(names.get(j))) { maxx+=scores.get(j); if(maxx<=score){ hashMap.put(s,j); } else { hashMap.put(s,j); break; } } } } Set s=hashMap.keySet(); Iterator it=s.iterator(); it.hasNext(); String val=(String) it.next(); int m=hashMap.get(val); while (it.hasNext()) { String vv=(String) it.next(); int mm=hashMap.get(vv); if(mm<m) { m=mm; } } System.out.println(names.get(m)); } input.close(); } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
886c0cc69188270eb6ab7ad5da63bee4
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
import java.io.BufferedReader; import java.io.IOError; import java.io.IOException; import java.io.InputStreamReader; import java.lang.Comparable; import java.util.*; public class Main { static BufferedReader reader; public static String readString(){ try { return reader.readLine().trim(); } catch (IOException exception){ throw new IOError(exception); } } public static int readInt(){ return Integer.parseInt(readString()); } public static int[] readInts(){ String[] parts = readString().split(" "); int[] integers = new int[parts.length]; for (int i = 0; i<integers.length; i++){ integers[i] = Integer.parseInt(parts[i]); } return integers; } public static double readDouble(){ return Double.parseDouble(readString()); } public static double[] readDoubles(){ String[] parts = readString().split(" "); double[] integers = new double[parts.length]; for (int i = 0; i<integers.length; i++){ integers[i] = Double.parseDouble(parts[i]); } return integers; } public static void main(String[] args) { reader = new BufferedReader(new InputStreamReader(System.in)); StringBuilder builder = new StringBuilder(); int numCases = readInt(); List<String> names = new ArrayList<String>(); List<Integer> rounds = new ArrayList<Integer>(); for (int i = 0; i < numCases; i++){ String[] parts = readString().split(" "); String name = parts[0]; Integer score = Integer.parseInt(parts[1]); names.add(name); rounds.add(score); } HashMap<String, Integer> totalScores = new HashMap<String, Integer>(); for (int i = 0; i < numCases; i++){ int startScore = 0; if (totalScores.containsKey(names.get(i))){ startScore = totalScores.get(names.get(i)); } totalScores.put(names.get(i), startScore+rounds.get(i)); } int maxScore = 0; Map<String, Integer> winners = new HashMap<String, Integer>(); for (String name: totalScores.keySet()){ int score = totalScores.get(name); if (score > maxScore){ maxScore = score; winners.clear(); winners.put(name, 0); } else if (score == maxScore){ winners.put(name, 0); } } if (winners.size() == 1){ System.out.println(winners.keySet().iterator().next()); return; } for (int i = 0; i < numCases; i++){ String name = names.get(i); if (!winners.containsKey(name)) { continue; } int newScore = winners.get(name) + rounds.get(i); if (newScore >= maxScore){ System.out.println(name); return; } winners.put(name, newScore); } } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
19ae88d2e025bfeaaee6e6afe20a8b82
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; public class Winner { public static void main(String[] args) { FastReader input = new FastReader(); Map<String,Integer> map = new HashMap<String,Integer>(); int n = input.nextInt(); String[] names = new String[n]; int[] points = new int[n]; for(int i = 0;i < n;i++){ names[i] = input.next(); points[i] = input.nextInt(); if(!map.containsKey(names[i])){ map.put(names[i],points[i]); } else{ map.put(names[i],map.get(names[i]) + points[i]); } } int max = 0; for(int i : map.values()){ max = Math.max(max,i); } Set<String> possibles = new HashSet<String>(); for(Map.Entry<String,Integer> m : map.entrySet()){ if(m.getValue() >= max){ possibles.add(m.getKey()); } } map.clear(); String winner = ""; for(int i = 0;i < n;i++){ if(!map.containsKey(names[i])){ map.put(names[i],points[i]); } else{ map.put(names[i],map.get(names[i]) + points[i]); } if(map.get(names[i]) >= max && possibles.contains(names[i])){ winner = names[i]; break; } } System.out.println(winner); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
363e0bc737261e2b06de8fb533d28622
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class Winner_2A { private static class Player { String name; int points; List<RoundPoints> roundPoints; Player(String name, int points, int round) { this.name = name; this.points = points; roundPoints = new LinkedList<>(); roundPoints.add(new RoundPoints(round, points)); } } private static class RoundPoints { int round; int points; RoundPoints(int round, int points) { this.round = round; this.points = points; } } private static class Hash { private Player[] players = new Player[1001]; private int hash(String name) { return (name.hashCode() & 0x7fffffff) % 1001; } private void put(String name, int points, int round) { int i = hash(name); while (players[i] != null) { if (players[i].name.equals(name)) { players[i].points += points; players[i].roundPoints.add(new RoundPoints(round, players[i].points)); return; } i = (i+1) % 1001; } players[i] = new Player(name, points, round); } } private static boolean aReachedFirst(Player a, Player b) { int finalPoints = a.points; int aRound = 0, bRound = 0; for (RoundPoints rp : a.roundPoints) { if (rp.points >= finalPoints) { aRound = rp.round; break; } } for (RoundPoints rp : b.roundPoints) { if (rp.points >= finalPoints) { bRound = rp.round; break; } } return aRound < bRound; } public static void main(String[] args) { Hash hash = new Hash(); Scanner s = new Scanner(System.in); int n = s.nextInt(); String name; int points; for (int i = 0; i < n; i++) { name = s.next(); points = s.nextInt(); hash.put(name, points, i+1); } s.close(); Player maxPlayer = new Player("", 0, 0); for (Player player : hash.players) { if (player == null) continue; if ((player.points > maxPlayer.points) || ((player.points == maxPlayer.points) && (aReachedFirst(player, maxPlayer)))) maxPlayer = player; } System.out.println(maxPlayer.name); } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
256158628b52f2ccc1454f58cecc3d0d
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int line = in.nextInt(); Map <String, Integer> table = new HashMap<String, Integer>(); ArrayList<String> winners = new ArrayList<String>(); String name [] = new String [line]; int score [] = new int [line]; for (int i=0; i<line; i++){ name[i] = in.next(); score[i]=in.nextInt(); if (table.get(name[i])==null){ table.put(name[i], score[i]); } else { table.put(name[i],score[i]+table.get(name[i])); } } boolean winner = false; int record = 0; String record_w = ""; for (Map.Entry<String, Integer> entry : table.entrySet()) { if (entry.getValue()>record) { record=entry.getValue(); record_w=entry.getKey(); winners.clear(); winner=true; } else if (entry.getValue()==record){ winners.add(record_w); winners.add(entry.getKey()); winner=false; } } if (winner) { System.out.println(record_w); } else { record_w=""; int record_line = 2000; for (int i=0; i<winners.size(); i++) { int time_score=0; for (int j=0; j<name.length; j++){ if (name[j].equals(winners.get(i))){ time_score+=score[j]; if (time_score>=record && record_line>j){ record_line=j; record_w=name[j]; } } } } System.out.println(record_w); } } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
f51d9e44f4b81c0a6517a984e3da8359
train_002.jsonl
1267117200
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
64 megabytes
import java.io.PrintWriter; import java.util.*; import java.util.Scanner; /** * Created by abdujabbor on 3/11/17. */ public class Winner { public static void main(String args[]) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Map<String, Integer> m = new HashMap<String, Integer>(); int n; n = in.nextInt(); String inp[] = new String[n]; int max_value = 0; int scores[] = new int[n]; String names[] = new String[n]; for(int i = 0; i < n; i++) { String s; int v; s = in.next(); v = in.nextInt(); inp[i] = s + " " + v; if(m.get(s) == null) { m.put(s, v); } else { m.put(s, m.get(s) + v); } names[i] = s; scores[i] = m.get(s); } for (Map.Entry<String, Integer> entry : m.entrySet()) { if(entry.getValue() > max_value) max_value = entry.getValue(); } for(int i = 0; i < n; i++) { if(m.get(names[i]) == max_value && scores[i] >= max_value) { out.println(names[i]); break; } } out.flush(); } }
Java
["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"]
1 second
["andrew", "andrew"]
null
Java 8
standard input
[ "implementation", "hashing" ]
c9e9b82185481951911db3af72fd04e7
The first line contains an integer number n (1  ≀  n  ≀  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
1,500
Print the name of the winner.
standard output
PASSED
e381d1e3e375b29cfafda7510f1639ee
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.Scanner; public class ss_948A { public static void main(String[] args) { Scanner s = new Scanner(System.in); int R = s.nextInt(), C = s.nextInt(); char[][] pasture = new char[R][C]; for (int i = 0; i < R; i++) { String tmp = s.next(); for (int j = 0; j < C; j++) { pasture[i][j] = tmp.charAt(j); } } boolean canProtect = false; if (countAnimal('W',pasture)==0) { canProtect=true; // no change needed // no wolves found // } else if (!AssessAndProtect(pasture)) { canProtect = true; } // output // if (canProtect) { System.out.println("Yes"); for (char[] line:pasture) { for (char letter : line) System.out.print(letter); System.out.println(); } } else { System.out.println("No"); } } static boolean AssessAndProtect(char[][] pasture) { int R = pasture.length; int C = pasture[0].length; // check borders // upper , i=0 & lower i=R-1 for (int j = 0; j < C; j++) { if(pasture[0][j]=='S') // upper { // check below if(R>1 && pasture[1][j]=='W') return true; else addDog(pasture,1,j); // check to the right if(j<C-1 && pasture[0][j+1]=='W') return true; else addDog(pasture,0,j+1); // check to the left if(j>0 && pasture[0][j-1]=='W') return true; else addDog(pasture,0,j-1); } if(pasture[R-1][j]=='S') // lower { // check above if(R>1 && pasture[R-2][j]=='W') return true; else addDog(pasture,R-2,j); // check to the right if(j<C-1 && pasture[R-1][j+1]=='W') return true; else addDog(pasture,R-1,j+1); // check to the left if(j>0 && pasture[R-1][j-1]=='W') return true; else addDog(pasture,R-1,j-1); } } // leftmost , j=0 & rightmost j=C-1 for (int i = 0; i < R; i++) { if(pasture[i][0]=='S') // leftmost { // check to the right if(C>1 && pasture[i][1]=='W') return true; else addDog(pasture,i,1); // check below if(i<R-1 && pasture[i+1][0]=='W') return true; else addDog(pasture,i+1,0); // check above if(i>0 && pasture[i-1][0]=='W') return true; else addDog(pasture,i-1,0); } if(pasture[i][C-1]=='S') // rightmost { // check to the left if(C>1 && pasture[i][C-2]=='W') return true; else addDog(pasture,i,C-2); // check below if(i<R-1 && pasture[i+1][C-1]=='W') return true; else addDog(pasture,i+1,C-1); // check above if(i>0 && pasture[i-1][C-1]=='W') return true; else addDog(pasture,i-1,C-1); } } // check ''inner'' pasture for (int i = 1; i < R-1; i++) { for (int j = 1; j < C-1; j++) { if(pasture[i][j]=='S') { if (pasture[i - 1][j] == 'W') return true; else addDog(pasture,i-1,j); if (pasture[i + 1][j] == 'W') return true; else addDog(pasture,i+1,j); if (pasture[i][j - 1] == 'W') return true; else addDog(pasture,i,j-1); if (pasture[i][j + 1] == 'W') return true; else addDog(pasture,i,j+1); } } } // otherwise return false; } static void addDog(char[][] pasture, int i,int j) { try { if(pasture[i][j]=='.') pasture[i][j] = 'D'; } catch (ArrayIndexOutOfBoundsException err) { } } static int countAnimal(char symbol,char[][] field) { int c = 0; for (char[] chars : field) { for (char aChar : chars) { if (aChar == symbol) c++; } } return c; } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
6eea10ace3fb8038a6fe1a74662a2bfb
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.Scanner; public class ss_948A { public static void main(String[] args) { Scanner s = new Scanner(System.in); int R = s.nextInt(), C = s.nextInt(); char[][] pasture = new char[R][C]; for (int i = 0; i < R; i++) { String tmp = s.next(); for (int j = 0; j < C; j++) { pasture[i][j] = tmp.charAt(j); } } boolean canProtect = false; if (countAnimal('W',pasture)==0) { canProtect=true; // no change needed // no wolves found // } else if (!foundSW(pasture)) { canProtect = true; addMaximalProtection(pasture); } // output // if (canProtect) { System.out.println("Yes"); for (char[] line:pasture) { for (char letter : line) System.out.print(letter); System.out.println(); } } else { System.out.println("No"); } } static void addMaximalProtection(char[][] pasture) { for (int i = 0; i < pasture.length; i++) { for (int j = 0; j < pasture[i].length; j++) { if(pasture[i][j]=='.') pasture[i][j] = 'D'; } } } static boolean foundSW(char[][] pasture) { int R = pasture.length; int C = pasture[0].length; // check borders // upper , i=0 & lower i=R-1 for (int j = 0; j < C; j++) { if(pasture[0][j]=='S') // upper { // check below if(R>1 && pasture[1][j]=='W') return true; // check to the right if(j<C-1 && pasture[0][j+1]=='W') return true; // check to the left if(j>0 && pasture[0][j-1]=='W') return true; } if(pasture[R-1][j]=='S') // lower { // check above if(R>1 && pasture[R-2][j]=='W') return true; // check to the right if(j<C-1 && pasture[R-1][j+1]=='W') return true; // check to the left if(j>0 && pasture[R-1][j-1]=='W') return true; } } // leftmost , j=0 & rightmost j=C-1 for (int i = 0; i < R; i++) { if(pasture[i][0]=='S') // leftmost { // check to the right if(C>1 && pasture[i][1]=='W') return true; // check below if(i<R-1 && pasture[i+1][0]=='W') return true; // check above if(i>0 && pasture[i-1][0]=='W') return true; } if(pasture[i][C-1]=='S') // rightmost { // check to the left if(C>1 && pasture[i][C-2]=='W') return true; // check below if(i<R-1 && pasture[i+1][C-1]=='W') return true; // check above if(i>0 && pasture[i-1][C-1]=='W') return true; } } // check ''inner'' pasture for (int i = 1; i < R-1; i++) { for (int j = 1; j < C-1; j++) { if(pasture[i][j]=='S') { if (pasture[i - 1][j] == 'W') return true; if (pasture[i + 1][j] == 'W') return true; if (pasture[i][j - 1] == 'W') return true; if (pasture[i][j + 1] == 'W') return true; } } } // otherwise return false; } static int countAnimal(char symbol,char[][] field) { int c = 0; for (char[] chars : field) { for (char aChar : chars) { if (aChar == symbol) c++; } } return c; } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
d3b66c855b9728132bb86124da83fa1c
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Main { private static String line; private static int indexLine; public static void readLine(BufferedReader reader) throws IOException { line = reader.readLine(); indexLine = 0; } public static int readInt() { int x = 0; while (indexLine < line.length() && line.charAt(indexLine) >= '0' && line.charAt(indexLine) <= '9') { x = x * 10 + line.charAt(indexLine) - 48; indexLine++; } indexLine++; return x; } public static long readLong() { long x = 0; while (indexLine < line.length() && line.charAt(indexLine) >= '0' && line.charAt(indexLine) <= '9') { x = x * 10 + line.charAt(indexLine) - 48; indexLine++; } return x; } private static final int mod = (int)(1e6 + 3); public static void main(String[] args) { new Main(); } public Main() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); in.nextLine(); String line = new String(); char[][] matrix = new char[n][k]; for (int i = 0; i < n; i++) { line = in.nextLine(); for (int j = 0; j < k; j++) matrix[i][j] = line.charAt(j) == '.' ? 'D': line.charAt(j); } boolean valid = true; for (int i = 0; i < n; i++) for (int j = 0; j < k; j++) if (matrix[i][j] == 'W') { if (i + 1 < n && matrix[i + 1][j] == 'S') valid = false; if (j + 1 < k && matrix[i][j + 1] == 'S') valid = false; if (i - 1 >= 0 && matrix[i - 1][j] == 'S') valid = false; if (j - 1 >= 0 && matrix[i][j - 1] == 'S') valid = false; } if (valid) { System.out.println("Yes"); for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) System.out.print(matrix[i][j]); System.out.println(); } } else System.out.println("No"); } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
8668e60dcfbd12782d610843e2825168
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.io.*; public class Task948A { public static void main(String... args) throws NumberFormatException, IOException { Solution.main(System.in, System.out); } static class Scanner { private final BufferedReader br; private String[] cache; private int cacheIndex; Scanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); cache = new String[0]; cacheIndex = 0; } int nextInt() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return Integer.parseInt(cache[cacheIndex++]); } long nextLong() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return Long.parseLong(cache[cacheIndex++]); } String next() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return cache[cacheIndex++]; } void close() throws IOException { br.close(); } } static class Solution { public static void main(InputStream is, OutputStream os) throws NumberFormatException, IOException { PrintWriter pw = new PrintWriter(os); Scanner sc = new Scanner(is); int r = sc.nextInt(); int c = sc.nextInt(); boolean retVal = true; char[][] board = new char[r][]; for (int i = 0; i < r; i++) { board[i] = sc.next().toCharArray(); } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (board[i][j] == '.') { board[i][j] = 'D'; } } } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (board[i][j] == 'S') { if (i > 0) { if (board[i - 1][j] == 'W') { retVal = false; } } if (j > 0) { if (board[i][j - 1] == 'W') { retVal = false; } } if (i + 1 < r) { if (board[i + 1][j] == 'W') { retVal = false; } } if (j + 1 < c) { if (board[i][j + 1] == 'W') { retVal = false; } } } } } if (retVal) { pw.println("Yes"); for (char[] row : board) { pw.println(row); } } else { pw.println("No"); } pw.flush(); sc.close(); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
4f8508663bd767cd8def99f7efbe65bd
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.Scanner; // https://codeforces.com/problemset/problem/948/A public class A948 { static Scanner sc; public static void solve() { } public static void main(String[] args) { sc = new Scanner(System.in); int r = sc.nextInt(); int c = sc.nextInt(); char[][] map = new char[r][c]; boolean hasDots = false; for(int i = 0; i < r; i++) { char[] line = sc.next().toCharArray(); for(int j = 0; j < c; j++) { map[i][j] = line[j]; if(line[j] == '.') hasDots = true; } } // if any wolf can reach a cheap then it's NOOOO boolean stop = false; for(int i = 0; i < r; i++) { if(stop == true) break; for (int j = 0; j < c; j++) { if(map[i][j] != 'W') continue; if(i > 0 && map[i-1][j] == 'S') { stop = true; break; } if(j > 0 && map[i][j-1] == 'S') { stop = true; break; } if(i + 1 < r && map[i+1][j] == 'S') { stop = true; break; } if(j + 1 < c && map[i][j+1] == 'S') { stop = true; break; } } } if(stop) { System.out.println("NO"); return; } System.out.println("YES"); for(int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if(map[i][j] == '.') map[i][j] = 'D'; System.out.print(map[i][j]); } System.out.println(); } sc.close(); } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
d3f878a6bd54990c465473891be69f69
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args) { // Use the Scanner class Scanner sc = new Scanner(System.in); /* int n = sc.nextInt(); // read input as integer long k = sc.nextLong(); // read input as long double d = sc.nextDouble(); // read input as double String str = sc.next(); // read input as String String s = sc.nextLine(); // read whole line as String */ int R = sc.nextInt(); int C = sc.nextInt(); sc.nextLine(); char[][] matrix=new char[R][C]; for(int r=0; r<R; r++){ String row = sc.nextLine(); for(int c=0; c<C; c++){ matrix[r][c]=row.charAt(c); } } boolean no=false; for(int r=0; r<R && !no; r++){ for(int c=0; c<C; c++){ if(matrix[r][c]=='W'){ if(canEat(matrix, r, c)){ no=true; break; } } } } if(no){ System.out.println("No"); }else{ System.out.println("Yes"); for(int r=0; r<R && !no; r++){ for(int c=0; c<C; c++){ if(matrix[r][c]=='S'){ putDogs(matrix, r, c); } } } StringBuffer sb = new StringBuffer(); for(int r=0; r<R; r++){ for(int c=0; c<C; c++){ sb.append(matrix[r][c]); } System.out.println(sb.toString()); sb.setLength(0); } } } private static void putDogs(char[][] matrix, int r, int c){ for(int rd=-1; rd<=1; rd++){ for(int cd=-1; cd<=1; cd++){ if((rd!=0)^(cd!=0)){ if(r+rd>=0 && r+rd<matrix.length && c+cd>=0 && c+cd<matrix[0].length){ if(matrix[r+rd][c+cd]=='.'){ matrix[r+rd][c+cd]='D'; } } } } } } private static boolean canEat(char[][] matrix, int r, int c){ boolean can=false; for(int rd=-1; rd<=1 && !can; rd++){ for(int cd=-1; cd<=1; cd++){ if((rd!=0)^(cd!=0)){ if(r+rd>=0 && r+rd<matrix.length && c+cd>=0 && c+cd<matrix[0].length){ if(matrix[r+rd][c+cd]=='S'){ can=true; break; } } } } } return can; } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
87e02b44b9fa57b73dc7d5b23b73f75d
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner r = new Scanner(System.in); int t=1; //t = r.nextInt(); while(t-->0){ int row = r.nextInt(); int col = r.nextInt(); char[][] ar = new char[row][col]; boolean a = true; for(int i=0;i<row;i++){ String xx = r.next(); for(int j=0;j<col;j++){ ar[i][j] = xx.charAt(j); } } outer:for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ if(ar[i][j]=='S'){ if(j!=0) if(ar[i][j-1] != 'W'){ if(ar[i][j-1] != 'S') ar[i][j-1] = 'D'; } else{ a = false; System.out.print("No"); break outer; } if(j!=col-1) if(ar[i][j+1] != 'W'){ if(ar[i][j+1] != 'S') ar[i][j+1] = 'D'; } else{ a = false; System.out.print("No"); break outer; } if(i!=0) if(ar[i-1][j] != 'W'){ if(ar[i-1][j] != 'S') ar[i-1][j] = 'D'; } else{ a = false; System.out.print("No"); break outer; } if(i!=row-1) if(ar[i+1][j] != 'W'){ if(ar[i+1][j] != 'S') ar[i+1][j] = 'D'; } else{ a = false; System.out.print("No"); break outer; } } } } if(a){ System.out.println("Yes"); for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ System.out.print(ar[i][j]); } System.out.println(); } } } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { 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
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
2003b88e60d23d79ca5b776fa18e4110
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int r = scanner.nextInt(); int c = scanner.nextInt(); int[][] field = new int[r][c]; for (int i = 0; i < r; i++) { String row = scanner.next(); for (int j = 0; j < c; j++) { field[i][j] = convert(row.charAt(j)); } } if (!isSafe(field)) { System.out.println("No"); return; } System.out.println("Yes"); moveDogs(field); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { System.out.print(conert(field[i][j])); } System.out.println(); } } private static int convert(char s) { if (s == '.') return 0; if (s == 'S') return 1; return 2; } private static String conert(int i) { if (i == 0) return "."; if (i == 1) return "S"; if (i == 2) return "W"; return "D"; } private static boolean isSafe(int[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == 1) { if (i - 1 >= 0 && matrix[i-1][j] == 2) return false; if (j + 1 < matrix[0].length && matrix[i][j+1] == 2) return false; if (i + 1 < matrix.length && matrix[i+1][j] == 2) return false; if (j - 1 >= 0 && matrix[i][j-1] == 2) return false; } } } return true; } private static void moveDogs(int[][] matrix) { for(int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == 0) matrix[i][j] = 3; } } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
7df0e8488a30f743bd78fa9f2b47dcf3
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
//package CodeForces; import java.util.Scanner; public class ProtectSheep { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int R = sc.nextInt(), C = sc.nextInt(); String [] row = new String[R]; char [][] Tr = new char [R][C]; for(int i = 0; i<R; i++) { Tr[i] = sc.next().toCharArray(); } sc.close(); for(int i = 0; i<R; i++) { for(int j=0; j<C; j++) { if(Tr[i][j] == 'S') { if(Tr[i][j != 0 ? j-1 : 0] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i][j != 0 ? j-1 : 0] == '.') { Tr[i][j != 0 ? j-1 : 0] = 'D'; } if(Tr[i][j != C-1 ? j+1 : C-1] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i][j != C-1 ? j+1 : C-1] == '.') { Tr[i][j != C-1 ? j+1 : C-1] = 'D'; } if(Tr[i != 0 ? i-1 : 0][j] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i != 0 ? i-1 : 0][j] == '.') { Tr[i != 0 ? i-1 : 0][j] = 'D'; } if(Tr[i != R-1 ? i+1 : R-1][j] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i != R-1 ? i+1 : R-1][j] == '.') { Tr[i != R-1 ? i+1 : R-1][j] = 'D'; } } } } System.out.println("Yes"); for(int i = 0; i<R; i++) { for(int j = 0; j<C; j++) { System.out.print(Tr[i][j]); } System.out.println(); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
12710cc0fef4104f29fb6486ed7d0669
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
//package CodeForces; import java.util.Scanner; public class ProtectSheep { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int R = sc.nextInt(), C = sc.nextInt(); String [] row = new String[R]; for(int i = 0; i<R; i++) { row [i] = sc.next(); } sc.close(); char [][] Tr = new char [R][C]; for(int i = 0; i<R; i++) { for(int j = 0; j<C; j++) { Tr[i][j] = row[i].charAt(j); } } for(int i = 0; i<R; i++) { for(int j=0; j<C; j++) { if(Tr[i][j] == 'S') { if(Tr[i][j != 0 ? j-1 : 0] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i][j != 0 ? j-1 : 0] == '.') { Tr[i][j != 0 ? j-1 : 0] = 'D'; } if(Tr[i][j != C-1 ? j+1 : C-1] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i][j != C-1 ? j+1 : C-1] == '.') { Tr[i][j != C-1 ? j+1 : C-1] = 'D'; } if(Tr[i != 0 ? i-1 : 0][j] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i != 0 ? i-1 : 0][j] == '.') { Tr[i != 0 ? i-1 : 0][j] = 'D'; } if(Tr[i != R-1 ? i+1 : R-1][j] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i != R-1 ? i+1 : R-1][j] == '.') { Tr[i != R-1 ? i+1 : R-1][j] = 'D'; } } } } System.out.println("Yes"); for(int i = 0; i<R; i++) { for(int j = 0; j<C; j++) { System.out.print(Tr[i][j]); } System.out.println(); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
57dcc702812f812e79489af59faf24be
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
//package CodeForces; import java.util.Scanner; public class ProtectSheep { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int R = sc.nextInt(), C = sc.nextInt(); String [] row = new String[R]; char [][] Tr = new char [R][C]; for(int i = 0; i<R; i++) { Tr[i] = sc.next().toCharArray(); } sc.close(); for(int i = 0; i<R; i++) { for(int j=0; j<C; j++) { if(Tr[i][j] == 'S') { if(Tr[i][j != 0 ? j-1 : 0] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i][j != 0 ? j-1 : 0] == '.') { Tr[i][j != 0 ? j-1 : 0] = 'D'; } if(Tr[i][j != C-1 ? j+1 : C-1] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i][j != C-1 ? j+1 : C-1] == '.') { Tr[i][j != C-1 ? j+1 : C-1] = 'D'; } if(Tr[i != 0 ? i-1 : 0][j] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i != 0 ? i-1 : 0][j] == '.') { Tr[i != 0 ? i-1 : 0][j] = 'D'; } if(Tr[i != R-1 ? i+1 : R-1][j] == 'W') { System.out.println("No"); System.exit(0); }else if(Tr[i != R-1 ? i+1 : R-1][j] == '.') { Tr[i != R-1 ? i+1 : R-1][j] = 'D'; } } } } System.out.println("Yes"); for(int i = 0; i<R; i++) { String s = ""; for(int j = 0; j<C; j++) { s += Tr[i][j]; } System.out.println(s); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
5b4c0ef69af2f7397c21eac217b95492
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.Scanner; public class ProtectSheep { static char[][] pasture; static int r, c; public static void main(String[] args) { Scanner in = new Scanner(System.in); r=in.nextInt(); c=in.nextInt(); pasture = new char[r][c]; for(int i=0; i<r; i++) pasture[i]=in.next().toCharArray(); int consecutive=0; for(int i=0; i<r; i++) { for(int j=0; j<c; j++) { if(hasAdjacent(i, j)) { consecutive++; } } } if(consecutive!=0) { System.out.println("No"); return; } System.out.println("Yes"); for(int i=0; i<r; i++) { for(int j=0; j<c; j++) { if(pasture[i][j]=='.') System.out.print('D'); else System.out.print(pasture[i][j]); } System.out.println(); } } static boolean hasAdjacent(int i, int j) { if(i==r-1&&j==c-1) { return false; } if(i==r-1) { if ((pasture[i][j] == 'W' && pasture[i][j + 1] == 'S') || (pasture[i][j] == 'S' && pasture[i][j + 1] == 'W')) return true; return false; } if(j==c-1) { if ((pasture[i][j] == 'W' && pasture[i + 1][j] == 'S') || (pasture[i][j] == 'S' && pasture[i + 1][j] == 'W')) return true; return false; } if ((pasture[i][j + 1] == 'W' && pasture[i][j] == 'S') || (pasture[i][j + 1] == 'S' && pasture[i][j] == 'W') || (pasture[i][j] == 'W' && pasture[i + 1][j] == 'S') || (pasture[i][j] == 'S' && pasture[i + 1][j] == 'W')) { return true; } return false; } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
61aceb61d1fb2899bf62dd5de289c9e0
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
//package javaapplication3; import java.util.ArrayList; import java.util.Scanner; import java.util.Collection; import java.util.Arrays; import java.util.Collections; public class JavaApplication3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int R = sc.nextInt(), C = sc.nextInt(); String [] row = new String[R]; char [][] Tr = new char [R][C]; for(int i = 0; i<R; i++) { Tr[i] = sc.next().toCharArray(); } sc.close(); int []dx = new int[]{0,0,-1,1}; int []dy = new int[]{1,-1,0,0}; for(int i = 0; i<R; i++) { for(int j=0; j<C; j++) { if(Tr[i][j] == 'S') { // inja ro kollan avaz kardim ! for (int ptr = 0 ; ptr < 4 ; ptr ++){ int i2 = i + dx[ptr]; int j2 = j + dy[ptr]; if (j2 >= 0 && j2 < C && i2 >= 0 && i2 < R){ // yani tooye jadvalim hanooz ! if (Tr[i2][j2] == 'W'){ System.out.println("No"); System.exit(0); } if (Tr[i2][j2] != 'S') Tr[i2][j2] = 'D'; } } } } } System.out.println("Yes"); for(int i = 0; i<R; i++) { String tot = ""; for(int j = 0; j<C; j++) { // System.out.print(Tr[i][j]); tot += Tr[i][j]; } System.out.println(tot); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
7f7bfe4047953e241e7a0e80acca8430
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
//package javaapplication3; import java.util.ArrayList; import java.util.Scanner; import java.util.Collection; import java.util.Arrays; import java.util.Collections; public class JavaApplication3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int R = sc.nextInt(), C = sc.nextInt(); String [] row = new String[R]; char [][] Tr = new char [R][C]; for(int i = 0; i<R; i++) { Tr[i] = sc.next().toCharArray(); } sc.close(); int []dx = new int[]{0,0,-1,1}; int []dy = new int[]{1,-1,0,0}; for(int i = 0; i<R; i++) { for(int j=0; j<C; j++) { if(Tr[i][j] == 'S') { // inja ro kollan avaz kardim ! for (int ptr = 0 ; ptr < 4 ; ptr ++){ int i2 = i + dx[ptr]; int j2 = j + dy[ptr]; if (j2 >= 0 && j2 < C && i2 >= 0 && i2 < R){ // yani tooye jadvalim hanooz ! if (Tr[i2][j2] == 'W'){ System.out.println("No"); System.exit(0); } if (Tr[i2][j2] != 'S') Tr[i2][j2] = 'D'; } } } } } System.out.println("Yes"); for(int i = 0; i<R; i++) { // String tot = ""; for(int j = 0; j<C; j++) { System.out.print(Tr[i][j]); // tot += Tr[i][j]; } System.out.println(); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
464415f55c7b67b46035ce22e906ba7c
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.*; /** * _948A */ public class _948A { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int r=sc.nextInt(); int c=sc.nextInt(); char a[][]=new char[r][c]; sc.nextLine(); for(int i=0;i<r;i++){ String s=sc.nextLine(); for(int j=0;j<s.length();j++){ a[i][j]=s.charAt(j); } } for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ if(a[i][j]=='S'){ if(i<r-1&&a[i+1][j]=='W'){ System.out.println("NO"); return; } if(i>0&&a[i-1][j]=='W'){ System.out.println("NO"); return; } if(j<c-1&&a[i][j+1]=='W'){ System.out.println("NO"); return; } if(j>0&&a[i][j-1]=='W'){ System.out.println("NO"); return; } if(i==r-1||i==0){ if(j-1>0&&a[i][j-1]=='W'){ System.out.println("NO"); return; } if(j+1<c&&a[i][j+1]=='W'){ System.out.println("NO"); return; } } if(j==0||j==c-1){ if(i-1>0&&a[i-1][j]=='W'){ System.out.println("NO"); return; } if(i+1<r&&a[i+1][j]=='W'){ System.out.println("NO"); return; } } } } } for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ if(a[i][j]=='.'){ a[i][j]='D'; } } } System.out.println("YES"); for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ System.out.print(a[i][j]); } System.out.println(); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
2fa5e19963cb65933b1763ea4932cc10
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.awt.Point; import java.util.ArrayList; import java.util.Scanner; public class ProtectSheep { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int r = sc.nextInt(); int c = sc.nextInt(); char[][] adj = new char[r][c]; for (int i = 0; i < r; i++) { adj[i] = sc.next().toCharArray(); } ArrayList<Point> wolf = new ArrayList<Point>(); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (adj[i][j] == '.') adj[i][j] = 'D'; if (adj[i][j] == 'W') wolf.add(new Point(i, j)); } } boolean pos = true; for (Point w : wolf) { if (w.x > 0 && adj[w.x - 1][w.y] == 'S') pos = false; if (w.y > 0 && adj[w.x][w.y - 1] == 'S') pos = false; if (w.x < r - 1 && adj[w.x + 1][w.y] == 'S') pos = false; if (w.y < c - 1 && adj[w.x][w.y + 1] == 'S') pos = false; } System.out.println(pos ? "Yes" : "No"); if (pos) { for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { System.out.print(adj[i][j]); } System.out.println(); } } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
8721f51dbd29cb25253e51e255cfd800
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.Scanner; public class CF_948_Problem1 { public static void main(String[] args) { char[][] matrix = readInput(); boolean possible = process(matrix); System.out.println(possible ? "Yes" : "No"); if(possible) { print(matrix); } // print(matrix); } public static char[][] readInput() { Scanner sc = new Scanner(System.in); int row = sc.nextInt(); int col = sc.nextInt(); char[][] matrix = new char[row][col]; for(int i = 0; i < row; ++i) { String line = sc.next(); for(int j = 0; j < col; ++j) { matrix[i][j] = line.charAt(j); } } sc.close(); return matrix; } public static boolean process(char[][] matrix) { for(int i = 0; i < matrix.length; ++i) { for(int j = 0; j < matrix[i].length; ++j) { if(matrix[i][j] == '.') { matrix[i][j] = 'D'; } else if(matrix[i][j] == 'W') { if(i > 0) { if(matrix[i-1][j] == 'S') { return false; } } if(i < matrix.length - 1) { if(matrix[i+1][j] == 'S') { return false; } } if(j > 0) { if(matrix[i][j-1] == 'S') { return false; } } if(j < matrix[i].length - 1) { if(matrix[i][j+1] == 'S') { return false; } } } } } return true; } public static void print(char[][] matrix) { for(int i = 0; i < matrix.length; ++i) { for(int j = 0; j < matrix[i].length; ++j) { System.out.print(matrix[i][j]); } System.out.println(); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
87fc546cc32acc70cf031d1c0cdc9eb3
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int R = scanner.nextInt(); int C = scanner.nextInt(); char[][] chars = new char[R][C]; boolean check = true; for (int i = 0; i < R; i++) { String string = scanner.next(); for (int j = 0; j < C; j++) { chars[i][j] = string.charAt(j); // System.out.print(chars[i][j]); } } for (int i = 0; i < R && check; i++) { for (int j = 0; j < C && check; j++) { if (chars[i][j] == 'W') { if (i > 0 && chars[i - 1][j] == 'S' || j < C - 1 && chars[i][j + 1] == 'S' || j > 0 && chars[i][j - 1] == 'S' || i < R - 1 && chars[i + 1][j] == 'S') check = false; else { if (i > 0&&chars[i - 1][j]=='.') { chars[i - 1][j] = 'D'; } if (i < R - 1&&chars[i + 1][j]=='.') { chars[i + 1][j] = 'D'; } if (j > 0&&chars[i][j - 1]=='.') { chars[i][j - 1] = 'D'; } if (j < C - 1&&chars[i][j + 1]=='.') { chars[i][j + 1] = 'D'; } } } } } if (check) { System.out.println("Yes"); for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { System.out.print(chars[i][j]); } System.out.println(); } } else { System.out.print("No"); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
33c77ec3c51f573921a42393c84e28da
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException{ //FastScanner in = new FastScanner(new FileInputStream(new File("phi.in"))); //PrintWriter out = new PrintWriter(new File("output.txt")); PrintWriter out = new PrintWriter(System.out); FastScanner in = new FastScanner(System.in); new Main().solveA(in, out); out.close(); System.exit(0); } /* begin() */ void solveA(FastScanner in, PrintWriter out){ int n = in.nextInt(); int m = in.nextInt(); char[][] grid = new char[n][m]; for(int i=0; i<n; i++) grid[i] = in.next().toCharArray(); for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(grid[i][j] == 'S'){ int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; for(int k=0; k<4; k++){ int x = j + dx[k]; int y = i + dy[k]; // System.out.println(i+ " "+x+" "+y); if(x >= 0 && x <m && y >= 0 && y<n){ if(grid[y][x] == 'W'){ out.println("No"); return; } if(grid[y][x] != 'S'){ //out.println(y+" "+x); grid[y][x] = 'D'; } } } } } } out.println("Yes"); for(int i=0; i<n; i++){ for(int j=0; j<m; j++) out.print(grid[i][j]); out.println(); } } void solveB(FastScanner in, PrintWriter out){ } void solveC(FastScanner in, PrintWriter out){ } void solveD(FastScanner in, PrintWriter out){ } /* end() */ private static class FastScanner { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
1798378d0d7834f97ccaa1ac8511124d
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.*; import org.omg.PortableInterceptor.INACTIVE; import java.awt.List; import java.io.*; import java.lang.*; public class code2 { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); //Code starts.. int n = in.nextInt(); int m = in.nextInt(); String[] s = new String[n]; for(int i=0; i<n; i++) s[i] = in.nextLine(); boolean flag = true; for(int i=0; i<n; i++) for(int j=0; j<m; j++) { if(s[i].charAt(j)=='S') { if(i>0) if(s[i-1].charAt(j)=='W') flag = false; if(i<n-1) if(s[i+1].charAt(j)=='W') flag = false; if(j>0) if(s[i].charAt(j-1)=='W') flag = false; if(j<m-1) if(s[i].charAt(j+1)=='W') flag = false; } } if(flag) { pw.println("Yes"); for(int i=0; i<n; i++) { for(int j=0; j<m; j++) if(s[i].charAt(j)=='.') pw.print("D"); else pw.print(s[i].charAt(j)); pw.println(); } } else pw.print("No"); //Code ends.... pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long c = 0; public static long mod = 1000000007; public static int d; public static int p; public static int q; public static boolean flag; public static int gcd(int p2, int p22) { if (p2 == 0) return (int) p22; return gcd(p22%p2, p2); } public static int findGCD(int arr[], int n) { int result = arr[0]; for (int i=1; i<n; i++) result = gcd(arr[i], result); return result; } public static void nextGreater(long[] a, int[] ans) { Stack<Integer> stk = new Stack<>(); stk.push(0); for(int i=1; i<a.length; i++) { if(!stk.isEmpty()) { int s = stk.pop(); while(a[s]<a[i]) { ans[s] = i; if(!stk.isEmpty()) s = stk.pop(); else break; } if(a[s]>=a[i]) stk.push(s); } stk.push(i); } return; } public static void nextGreaterRev(long[] a, int[] ans) { int n = a.length; int[] pans = new int[n]; Arrays.fill(pans, -1); long[] arev = new long[n]; for(int i=0; i<n; i++) arev[i] = a[n-1-i]; Stack<Integer> stk = new Stack<>(); stk.push(0); for(int i=1; i<n; i++) { if(!stk.isEmpty()) { int s = stk.pop(); while(arev[s]<arev[i]) { pans[s] = n - i-1; if(!stk.isEmpty()) s = stk.pop(); else break; } if(arev[s]>=arev[i]) stk.push(s); } stk.push(i); } //for(int i=0; i<n; i++) //System.out.print(pans[i]+" "); for(int i=0; i<n; i++) ans[i] = pans[n-i-1]; return; } public static void nextSmaller(long[] a, int[] ans) { Stack<Integer> stk = new Stack<>(); stk.push(0); for(int i=1; i<a.length; i++) { if(!stk.isEmpty()) { int s = stk.pop(); while(a[s]>a[i]) { ans[s] = i; if(!stk.isEmpty()) s = stk.pop(); else break; } if(a[s]<=a[i]) stk.push(s); } stk.push(i); } return; } public static long lcm(int[] numbers) { long lcm = 1; int divisor = 2; while (true) { int cnt = 0; boolean divisible = false; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == 0) { return 0; } else if (numbers[i] < 0) { numbers[i] = numbers[i] * (-1); } if (numbers[i] == 1) { cnt++; } if (numbers[i] % divisor == 0) { divisible = true; numbers[i] = numbers[i] / divisor; } } if (divisible) { lcm = lcm * divisor; } else { divisor++; } if (cnt == numbers.length) { return lcm; } } } public static long fact(long n) { long factorial = 1; for(int i = 1; i <= n; i++) { factorial *= i; } return factorial; } public static int lowerLimit(int[] a, int n) { int ans = 0; int ll = 0; int rl = a.length-1; // System.out.println(a[rl]+" "+n); if(a[0]>n) return 0; if(a[0]==n) return 1; else if(a[rl]<=n) return rl+1; while(ll<=rl) { int mid = (ll+rl)/2; if(a[mid]==n) { ans = mid + 1; break; } else if(a[mid]>n) { rl = mid-1; } else { ans = mid+1; ll = mid+1; } } return ans; } public static long choose(long total, long choose){ if(total < choose) return 0; if(choose == 0 || choose == total) return 1; return (choose(total-1,choose-1)+choose(total-1,choose))%mod; } public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static int floorSearch(int arr[], int low, int high, int x) { if (low > high) return -1; if (x > arr[high]) return high; int mid = (low+high)/2; if (mid > 0 && arr[mid-1] < x && x < arr[mid]) return mid-1; if (x < arr[mid]) return floorSearch(arr, low, mid-1, x); return floorSearch(arr, mid+1, high, x); } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static ArrayList<Integer> primeFactorization(int n) { ArrayList<Integer> a =new ArrayList<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int lowerbound(ArrayList<Long> net, long c2) { int i=Collections.binarySearch(net, c2); if(i<0) i = -(i+2); return i; } public static int uperbound(ArrayList<Long> net, long c2) { int i=Collections.binarySearch(net, c2); if(i<0) i = -(i+1); return i; } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int[] countDer(int n) { int der[] = new int[n + 1]; der[0] = 1; der[1] = 0; der[2] = 1; for (int i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der; } static long binomialCoeff(int n, int k) { long C[][] = new long[n+1][k+1]; int i, j; // Calculate value of Binomial Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previosly stored values else C[i][j] = C[i-1][j-1] + C[i-1][j]; } } return C[n][k]; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=(x%mod * x%mod)%mod; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean checkYear(int year) { if (year % 400 == 0) return true; if (year % 100 == 0) return false; if (year % 4 == 0) return true; return false; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } static class triplet implements Comparable<triplet> { Integer x,y,z; triplet(int x,int y,int z) { this.x = x; this.y = y; this.z = z; } public int compareTo(triplet o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); if(result==0) result = z.compareTo(o.z); return result; } public boolean equlas(Object o) { if(o instanceof triplet) { triplet p = (triplet)o; return x==p.x && y==p.y && z==p.z; } return false; } public String toString() { return x+" "+y+" "+z; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode() + new Long(z).hashCode(); } } static class node implements Comparable<node> { Integer x, y, z; node(int x,int y, int z) { this.x=x; this.y=y; this.z=z; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); if(result==0) result = z.compareTo(z); return result; } @Override public int compareTo(node o) { // TODO Auto-generated method stub return 0; } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
17acfb79fbdf3cde142df84150becc07
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import javax.sound.midi.MidiChannel; public class Main { public static void main(String[] args) { // Scanner reader = new Scanner(System.in); InputReader reader = new InputReader(); int n = reader.nextInt(); int m = reader.nextInt(); char[][] field = new char[n + 1][m + 1]; for (int i = 0; i < n; i++) { String inPut = reader.next(); for (int j = 0; j < m; j++) { char get = inPut.charAt(j); if (get == '.') { get = 'D'; } // System.out.println("~"); field[i][j] = get; } } // System.out.println("~"); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { boolean cantProtect = (field[i][j] == 'S' && field[i][j + 1] == 'W') || (field[i][j] == 'W' && field[i][j + 1] == 'S') || (field[i][j] == 'S' && field[i + 1][j] == 'W') || (field[i][j] == 'W' && field[i + 1][j] == 'S'); // System.out.println("~"); if (cantProtect) { System.out.println("No"); return; } } } System.out.println("Yes"); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(field[i][j]); } System.out.println(); } } } class InputReader { BufferedReader buf; StringTokenizer tok; InputReader() { buf = new BufferedReader(new InputStreamReader(System.in)); } boolean hasNext() { while (tok == null || !tok.hasMoreElements()) { try { tok = new StringTokenizer(buf.readLine()); } catch (Exception e) { return false; } } return true; } String next() { if (hasNext()) return tok.nextToken(); return null; } char nextChar() { return next().charAt(0); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } /* * BigInteger nextBigInteger() { return new BigInteger(next()); } * * BigDecimal nextBigDecimal() { return new BigDecimal(next()); } */ } // wow, thanks for your code review!
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
844a6b421643d78b2b8810ce60e524cb
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.*; public class Prob948A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int r = sc.nextInt(); int c = sc.nextInt(); boolean canProtect = true; //use stringbuffer will avoid string immutable in java StringBuffer[] matrixLine = new StringBuffer[r]; //move to next line sc.nextLine(); matrixLine[0] = new StringBuffer(sc.nextLine()); for(int i = 0; i < r; ++i) { if (i != r - 1) matrixLine[i + 1] = new StringBuffer(sc.nextLine()); for (int j = 0; j < c; ++j) { //we just process if we encounter the sheep if (matrixLine[i].charAt(j) == 'S') { //sequentially check four sides of each sheep if (j > 0) { if(!checkNeighbor(matrixLine, i, j - 1)) canProtect = false; } if (c - j > 1) { if(!checkNeighbor(matrixLine, i, j + 1)) canProtect = false; } if (i > 0) { if(!checkNeighbor(matrixLine, i - 1, j)) canProtect = false; } if (r - i > 1) { if(!checkNeighbor(matrixLine, i + 1, j)) canProtect = false; } if (canProtect == false) { System.out.println("No"); return; } } } } System.out.println("Yes"); for (StringBuffer line : matrixLine) { System.out.println(line); } } public static boolean checkNeighbor(StringBuffer[] matrixLine, int i, int j) { switch(matrixLine[i].charAt(j)) { case '.': { matrixLine[i].setCharAt(j, 'D'); return true; } case 'D': { return true; } case 'W': { return false; } case 'S': { return true; } default: { return true; } } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
555a0f9d51ed1499c37e2b3a1ce5263c
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.*; import java.io.*; public class Main{ /* . . . . . . . some constants . */ static int i=0,j=0,k=0,l=0; /* . . . if any . . */ public static void main(String[] args) throws IOException{ /* . . . . . . */ int r=ni(); int c=ni(); char arr[][]=new char[r][c]; for(i=0;i<r;i++) arr[i]=ns().toCharArray(); outer: for(i=0;i<r;i++){ for(j=0;j<c;j++){ if(arr[i][j]=='W'){ if(i>0 && arr[i-1][j]=='.') arr[i-1][j]='D'; if(i<(r-1) && arr[i+1][j]=='.') arr[i+1][j]='D'; if(j>0 && arr[i][j-1]=='.') arr[i][j-1]='D'; if(j<(c-1) && arr[i][j+1]=='.') arr[i][j+1]='D'; if(i>0 && arr[i-1][j]=='S') break outer; if(i<(r-1) && arr[i+1][j]=='S') break outer; if(j>0 && arr[i][j-1]=='S') break outer; if(j<(c-1) && arr[i][j+1]=='S') break outer; } } } if(i!=r || j!=c) sop("NO"); else{ sop("YES"); for(i=0;i<r;i++) System.out.println(arr[i]); } /* . . . . . . . */ } /* temporary functions . . */ /* fuctions . . . . . . . . . . . . . . . . . abcdefghijklmnopqrstuvwxyz . . . . . . */ static int modulo(int j,int m){ if(j<0) return m+j; if(j>=m) return j-m; return j; } static final int mod=1000000007; static final double eps=1e-8; static final long inf=100000000000000000L; static final boolean debug=true; static Reader in=new Reader(); static StringBuilder ans=new StringBuilder(); static long powm(long a,long b,long m){ long an=1; long c=a; while(b>0){ if(b%2==1) an=(an*c)%m; c=(c*c)%m; b>>=1; } return an; } static Random rn=new Random(); static void sop(Object a){System.out.println(a);} static int ni(){return in.nextInt();} static int[] nia(int n){int a[]=new int[n];for(int i=0;i<n;i++)a[i]=ni();return a;} static long nl(){return in.nextLong();} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String ns(){return in.next();} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double nd(){return in.nextDouble();} static double[] nda(int n){double a[]=new double[n];for(int i=0;i<n;i++)a[i]=nd();return a;} static class Reader{ public BufferedReader reader; public StringTokenizer tokenizer; public Reader(){ reader=new BufferedReader(new InputStreamReader(System.in),32768); tokenizer=null; } public String next(){ while(tokenizer==null || !tokenizer.hasMoreTokens()){ try{ tokenizer=new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
3e24e4904b50a2d433c0ea5d1ca93290
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { static boolean visited[] ; static boolean found = false; static int steps = 0 ; static int n ; static int[][] memo ; public void solve(int testNumber, InputReader in, PrintWriter out) { int r = in.nextInt() ; int c = in.nextInt() ; char [][] matrix = new char[r][c] ; for (int i = 0; i < r; i++) { String x = in.next() ; for (int j = 0; j < c; j++) { matrix[i][j] = x.charAt(j) ; } } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if(matrix[i][j] == '.') matrix[i][j] = 'D' ; } } boolean res = true ; for (int i = 0; i <r; i++) { for (int j = 0; j <c; j++) { if(matrix[i][j]=='S' && i>0 && matrix[i-1][j]=='W') { res= false ; System.out.println("NO"); return ; } if(matrix[i][j]=='S' && j>0 && matrix[i][j-1]=='W') { res= false ; System.out.println("NO"); return ; } if(matrix[i][j]=='S' && i<r-1 && matrix[i+1][j]=='W') { res= false ; System.out.println("NO"); return ; } if(matrix[i][j]=='S' && j<c-1 && matrix[i][j+1]=='W') { res= false ; System.out.println("NO"); return ; } } } System.out.println("YES"); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { System.out.print(matrix[i][j]+""); } System.out.println(""); } } public static String solve(String x){ int n = x.length() ; String y = "" ; for (int i = 0; i < n-2; i+=2) { if(ifPalindrome(x.substring(i, i+2))) y+= x.substring(i, i+2) ; else break ; } return y+ solve1(x.substring(y.length(),x.length())) ; } public static String solve1(String x){ String y = x.substring(0 , x.length()/2) ; return "" ; } public static String reverse(String x){ String y ="" ; for (int i = 0; i < x.length(); i++) { y = x.charAt(i) + y ; } return y ; } public static boolean ifPalindrome(String x){ int numbers[] = new int[10] ; for (int i = 0; i < x.length(); i++) { int z = Integer.parseInt(x.charAt(i)+"") ; numbers[z] ++ ; } for (int i = 0; i < numbers.length; i++) { if(numbers[i]%2!=0) return false; } return true ; } public static int get(int n){ return n*(n+1)/2 ; } public static long getSmallestDivisor( long y){ if(isPrime(y)) return -1; for (long i = 2; i*i <= y; i++) { if(y%i ==0) { return i; } } return -1; } // public static void lis(pair []a , int n){ // int lis[] = new int[n] ; // Arrays.fill(lis,1) ; // // for(int i=1;i<n;i++) // for(int j=0 ; j<i; j++) // if (a[i].y>a[j].y && lis[i] < lis[j]+1) // lis[i] = lis[j] + 1; // // int max = lis[0]; // // for(int i=1; i<n ; i++) // if (max < lis[i]) // max = lis[i] ; // System.out.println(max); // // ArrayList<Integer> s = new ArrayList<Integer>() ; // for (int i = n-1; i >=0; i--) // { // if(lis[i]==max) // { // s.add(a[i].z); // max --; // } // } // // for (int i = s.size()-1 ; i>=0 ; i--) // { // System.out.print(s.get(i)+" "); // } // // return ; // } public static int calcDepth(Vertix node){ if(node.depth>0) return node.depth; // meaning it has been updated before; if(node.parent != null) return 1+ calcDepth(node.parent); else return -1; } public static int helper(int a[] , int i , int j , int d , int n){ if(j==i || i==n-1 || j==0) return 0; if(a[j] - a[i] <= d) return 0; if(memo[i][j]!= -1) return memo[i][j] ; if( a[j-1]-a[i]< a[j]-a[i+1]) return memo[i][j]=1 + helper(a, i, j-1, d , n) ; if( a[j-1]-a[i]> a[j]-a[i+1]) return memo[i][j]=1+ helper(a , i+1 , j , d ,n ) ; return memo[i][j]=1+ Math.min(helper(a, i, j-1, d , n) , helper(a , i+1 , j , d ,n )) ; } public static boolean isPrime (long num){ if (num < 2) return false; if (num == 2) return true; if (num % 2 == 0) return false; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true; } public static boolean dfs(Vertix v , int target){ try{ visited[v.i]= true ; } catch (NullPointerException e) { System.out.println(v.i); } if(v.i == target) return true ; for (int i =0 ; i< v.neighbours.size() ; i++) { Vertix child = v.neighbours.get(i) ; if(child.i == target){ found = true ; } if(visited[child.i]==false){ found |= dfs(child, target) ; } } return found; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } public static class Vertix{ int i ; int depth ; ArrayList<Vertix> neighbours ; Vertix parent ; public Vertix(int i){ this.i = i ; this.neighbours = new ArrayList<Vertix> () ; this.parent = null ; depth =-1; } } public static class pair implements Comparable<pair>{ int x ; // neededLessonsToSkip //k int y ; // value public pair(int x, int y){ this.x=x ; this.y=y ; } @Override public int compareTo(pair p) { if(this.x > p.x) return 1 ; else if(this.x== p.x) { if(this.y >= p.y) return 1 ; else return -1 ; } else return -1 ; } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
d2c19773d99fa1c91c798f3e8b149b79
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.Scanner; public class Solution { private static void printAns(char [][] chs,int r, int c) { for(int i =0;i<r;i++) { for(int k=0;k<c;k++) { if(chs[i][k]=='S') { if(i-1>-1) { if(chs[i-1][k]=='W') { System.out.println("No"); return; } } if(i+1<r) { if(chs[i+1][k]=='W') { System.out.println("No"); return; } } if(k-1>-1) { if(chs[i][k-1]=='W') { System.out.println("No"); return; } } if(k+1<c) { if(chs[i][k+1]=='W') { System.out.println("No"); return; } } } } } System.out.println("Yes"); for(int i =0;i<r;i++) { for(int k=0;k<c;k++) { System.out.print(chs[i][k]); } System.out.println(); } } public static void main(String [] args) { Scanner in = new Scanner(System.in); int r =in.nextInt(); int c =in.nextInt(); char [][] chs =new char[r][c]; String [] grids =new String[r]; for(int i =0;i<r;i++) { grids[i] =in.next(); for(int k=0;k<grids[i].length();k++) { if(grids[i].charAt(k)=='.') { chs[i][k] ='D'; } else { chs[i][k] =grids[i].charAt(k); } } } printAns(chs,r,c); } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
be035cd1df9b97f5165e17f505850c2d
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.Scanner; public class ProtectSheep { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); char[][] animals = new char[n][m]; sc.nextLine(); for (int i = 0; i < animals.length; i++) { animals[i] = sc.nextLine().toCharArray(); } boolean possible = true; for (int i = 0; i < animals.length; i++) { for (int j = 0; j < animals[0].length; j++) { if (animals[i][j] == 'S') { if (i > 0 && animals[i - 1][j] == 'W') { possible = false; } if (i < n - 1 && animals[i + 1][j] == 'W') { possible = false; } if (j > 0 && animals[i][j - 1] == 'W') { possible = false; } if (j < m - 1 && animals[i][j + 1] == 'W') { possible = false; } } } } if (possible) { System.out.println("Yes"); for (int i = 0; i < animals.length; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < animals[i].length; j++) { if (animals[i][j] == '.') { sb.append('D'); } else { sb.append(animals[i][j]); } } System.out.println(sb); } } else { System.out.println("No"); } sc.close(); } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
f309d552b347920ca36003d425236559
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int r=sc.nextInt(); int c=sc.nextInt(); char ch[][]=new char[r][c]; for(int j=0;j<r;j++){ String s=sc.next(); for(int h=0;h<c;h++){ ch[j][h]=s.charAt(h); } } int sum=0; for(int f=0;f<r;f++){ for(int v=0;v<c;v++){ if(ch[f][v]=='S'){ if(f>0){if(ch[f-1][v]=='W'){sum++;}} if(f<r-1){if(ch[f+1][v]=='W'){sum++;}} if(v>0){if(ch[f][v-1]=='W'){sum++;}} if(v<c-1){if(ch[f][v+1]=='W'){sum++;}} } } } if(sum!=0){System.out.println("No");}else{ System.out.println("Yes"); for(int ff=0;ff<r;ff++){ for(int vv=0;vv<c;vv++){ if(ch[ff][vv]=='S'){ if(ff>0){if(ch[ff-1][vv]!='S'){ch[ff-1][vv]='D';}} if(ff<r-1){if(ch[ff+1][vv]!='S'){ch[ff+1][vv]='D';}} if(vv>0){if(ch[ff][vv-1]!='S'){ch[ff][vv-1]='D';}} if(vv<c-1){if(ch[ff][vv+1]!='S'){ch[ff][vv+1]='D';}} } } } for(int ee=0;ee<r;ee++){ for(int ww=0;ww<c;ww++){ System.out.print(ch[ee][ww]); } System.out.println(); } } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
2e1b7b323d8ba1b02bdae0aa933495b5
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.*; import java.io.*; public class _948A { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str[] = br.readLine().split(" "); int r = Integer.parseInt(str[0]); int c = Integer.parseInt(str[1]); char ch[][] = new char[r+2][c+2]; for(int i=1;i<=r;i++) { String st = br.readLine(); for(int j=1;j<=c;j++) ch[i][j] = st.charAt(j-1); } boolean flag = true; for(int i=1;i<=r && flag;i++) { for(int j=1;j<=c && flag;j++) { if(ch[i][j] == 'W') { if(ch[i-1][j] == 'S' || ch[i][j+1] == 'S' || ch[i][j-1] == 'S' || ch[i+1][j] == 'S') flag = false; else { if(ch[i-1][j] == '.') ch[i-1][j] = 'D'; if(ch[i][j+1] == '.') ch[i][j+1] = 'D'; if(ch[i][j-1] == '.') ch[i][j-1] = 'D'; if(ch[i+1][j] == '.') ch[i+1][j] = 'D'; } } } } if(!flag) System.out.println("No"); else { System.out.println("Yes"); for(int i=1;i<=r;i++) { for(int j=1;j<=c;j++) System.out.print(ch[i][j]); System.out.println(); } } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
3f49e445c085be81a4acd08f2cae70bd
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.text.DecimalFormat; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); DecimalFormat df=new DecimalFormat("######0.0000"); int R=sc.nextInt(); int C=sc.nextInt(); char[][] arr=new char[R][C]; for(int i=0;i<R;i++){ String row=sc.next(); for(int j=0;j<C;j++){ arr[i][j]=row.charAt(j); } } for(int i=0;i<R;i++){ for(int j=0;j<C;j++){ if(arr[i][j]=='W'){ if(j>0){ if(arr[i][j-1]=='S'){ System.out.println("No"); return; } } if(j<C-1){ if(arr[i][j+1]=='S'){ System.out.println("No"); return; } } if(i>0){ if(arr[i-1][j]=='S'){ System.out.println("No"); return; } } if(i<R-1){ if(arr[i+1][j]=='S'){ System.out.println("No"); return; } } }else if(arr[i][j]=='.'){ arr[i][j]='D'; } } } System.out.println("Yes"); for(int i=0;i<R;i++){ for(int j=0;j<C;j++){ System.out.print(arr[i][j]); } System.out.println(); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
221a2e524f27e758aa833adfa9036b72
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; //Mann Shah [ DAIICT ]. //fast io public class Main { public static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public static void main(String args[] ) { in = new InputReader(System.in); out = new PrintWriter(System.out); int r = in.nextInt(); int c = in.nextInt(); String[] s = new String[r]; for(int i=0;i<r;i++) { s[i]=in.readString(); } int f=0; for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { if(s[i].charAt(j)=='S') { if(i+1<r) { if(s[i+1].charAt(j)=='W') { f=1; } else if(s[i+1].charAt(j)=='.') { StringBuilder ss = new StringBuilder(s[i+1]); ss.setCharAt(j,'D'); s[i+1]=ss.toString(); } } if(j+1<c) { if(s[i].charAt(j+1)=='W') { f=1; } else if(s[i].charAt(j+1)=='.') { StringBuilder ss = new StringBuilder(s[i]); ss.setCharAt(j+1,'D'); s[i]=ss.toString(); } } if(i-1>=0) { if(s[i-1].charAt(j)=='W') { f=1; } else if(s[i-1].charAt(j)=='.') { StringBuilder ss = new StringBuilder(s[i-1]); ss.setCharAt(j,'D'); s[i-1]=ss.toString(); } } if(j-1>=0) { if(s[i].charAt(j-1)=='W') { f=1; } else if(s[i].charAt(j-1)=='.'){ StringBuilder ss = new StringBuilder(s[i]); ss.setCharAt(j-1,'D'); s[i]=ss.toString(); } } if(f==1) { break; } } } if(f==1) { break; } } if(f==0) { out.println("YES"); for(int i=0;i<r;i++) { out.println(s[i]); } } else { out.println("NO"); } out.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } } //For Pair sorting //Arrays.sort(arr,new Comparator<Pair>() { // @Override public int compare(Pair p1, Pair p2) //{ // return p1.x - p2.x; //} //}); //Pair arr[] = new Pair[n]; //arr[0] = new Pair(10, 20); class Pair { int x; int y; // Constructor public Pair(int x, int y) { this.x = x; this.y = y; } } // class Compare { // //void return by default. // public Pair[] compare(Pair arr[], int n) // { // // Comparator to sort the pair according to first element. // Arrays.sort(arr, new Comparator<Pair>() { // @Override public int compare(Pair p1, Pair p2) // { // return p1.x - p2.x; // } // }); // // // return arr; // /* for (int i = 0; i < n; i++) { // System.out.print(arr[i].x + " " + arr[i].y + " "); // } // System.out.println(); */ // } //} // class couple implements Comparable<couple> { int x,y; public couple(int m,int f) { x=m; y=f; } public int compareTo(couple o) { return x-o.x; } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
7f707c5d35f1366ff0cc147c81a9e6cd
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.io.*; public class B { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String inp[]=br.readLine().split(" "); int r=Integer.parseInt(inp[0]); int c=Integer.parseInt(inp[1]); char ar[][]=new char[r][c]; int i,j; char in[]; for(i=0;i<r;i++) { in=br.readLine().toCharArray(); for(j=0;j<c;j++) ar[i][j]=in[j]; } for(i=0;i<r;i++) { for(j=0;j<c;j++){ if(ar[i][j]=='S') { if((j+1)<c){ if(ar[i][j+1]=='W') { System.out.println("No"); return; }} if((j-1)>=0){ if(ar[i][j-1]=='W') { System.out.println("No"); return; }} } } if(i>0){ for(j=0;j<c;j++){ if(ar[i][j]=='S'){ if(ar[i-1][j]=='W') { System.out.println("No"); return; }}}} if(i+1<r){ for(j=0;j<c;j++){ if(ar[i][j]=='S'){ if(ar[i+1][j]=='W') { System.out.println("No"); return; } }}} } System.out.println("Yes"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { if(ar[i][j]!='.') System.out.print(ar[i][j]); else System.out.print('D'); } System.out.println(); } } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
90d615aff57fedcb0f428bf718eead6d
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.*; import java.io.*; /** * @author mostafa */ public class B { static int [] dx = {1,-1,0,0}; static int [] dy = {0,0,1,-1}; static final int dir = 4 ; static char [][]arr ; static boolean [][] marked ; static int n , m ; static boolean status = true ; public static void main(String[] args) throws IOException { // Scanner sc = new Scanner(new File("in.txt")); Scanner sc = new Scanner(System.in); PrintWriter pr = new PrintWriter(System.out); n = sc.nextInt(); m = sc.nextInt(); arr = new char[n][m]; marked = new boolean [n][m]; for (int i = 0; i < n ; i++) arr[i] = sc.next().toCharArray(); for (int i = 0; i < n ; i++) { for (int k = 0; k < m ; k++) { if(arr[i][k]=='S' && !marked[i][k]) { dfs(i, k); if(!status) { System.out.println("No"); System.exit(0); } } } } pr.println("Yes"); for (int i = 0; i < n ; i++) { pr.println(arr[i]); } pr.close(); sc.close(); } static void dfs(int x , int y) { marked[x][y] = true ; for (int i = 0; i < dir ; i++ ) { int nX = x+dx[i]; int nY = y+dy[i]; if(possible(nX, nY) && !marked[nX][nY]) { if(arr[nX][nY]=='W') status = false ; else if(arr[nX][nY]=='.') arr[nX][nY] = 'D'; else if(arr[nX][nY]=='S') dfs(nX, nY) ; } } } static boolean possible(int x , int y) { if(x>=0&&x<=n-1&&y>=0&&y<=m-1) return true ; return false ; } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
09e0178bddf955a76d35e9fc97147181
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.util.Scanner; import java.util.Stack; public class A { static final int MAXN = 505; static int fd [][] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; static char map [][] = new char [MAXN][MAXN]; static int R, C; static class Node{ int x, y; Node(){} Node(int xx, int yy){ this.x = xx; this.y = yy; } } public static void main(String[] args) { Stack<Node> stack = new Stack<>(); Scanner in = new Scanner(System.in); R = in.nextInt(); C = in.nextInt(); for(int i = 0; i < R; i++){ map[i] = in.next().toCharArray(); // θΎ“ε…₯、、 } for(int i = 0; i < R; i++){ for(int j = 0; j < C; j++){ if(map[i][j] == 'W'){ stack.push(new Node(i, j)); // ζŠŠη‹Όηš„εζ ‡ε­˜θΏ›εŽ»γ€γ€ } } } boolean flag = true; if(stack.isEmpty()){ // ζ²‘ζœ‰η‹Όηš„ζƒ…ε†΅γ€γ€ System.out.println("Yes"); for(int i = 0; i < R; i++){ flag = true; for(int j = 0; j < C; j++){ if(map[i][j] != 'S'){ System.out.print("D"); }else{ System.out.print(map[i][j]); } } System.out.println(""); } }else{ while(!stack.isEmpty() && flag){ Node tmp = stack.pop(); // System.out.println("εΊ”θ―₯θΏ›ζ₯了吧、、、" + " tmp.x = " + tmp.x + " tmp.y = " + tmp.y + " map[x][y] = " + map[tmp.x][tmp.y]); flag = solve(tmp); } if(flag){ // true System.out.println("Yes"); for(int i = 0; i < R; i++){ for(int j = 0; j < C; j++){ if(j != C - 1){ System.out.print(map[i][j]); }else{ System.out.println(map[i][j]); } } } }else{ System.out.println("No"); } } } private static boolean solve(Node node){ int xx, yy; for(int i = 0; i < 4; i++){ xx = node.x + fd[i][0]; yy = node.y + fd[i][1]; if(xx >= 0 && xx < R && yy >= 0 && yy < C && map[xx][yy] == 'S'){ // η‹Όηš„ιš”ε£ε°±ζ˜―ηΎŠγ€γ€ return false; }else if(xx >= 0 && xx < R && yy >= 0 && yy < C && map[xx][yy] != 'S' && map[xx][yy] != 'W'){ // η‹Όηš„ιš”ε£ 不是羊 γ€δΉŸδΈζ˜―η‹Όγ€γ€ map[xx][yy] = 'D'; } } return true; } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
757dba7ebfd09282df91d5a7c1f061ce
train_002.jsonl
1520696100
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class Xorq { 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) throws IOException { FastReader sc = new FastReader(); int r = sc.nextInt(), c = sc.nextInt(); int wolf = 0, cnt = 0,dot=0; boolean chk = false; char[][] a = new char[r][c]; for (int i = 0; i < r; i++) { String str = sc.nextLine(); for (int j = 0; j < str.length(); j++) { if (str.charAt(j) == 'W') wolf++; cnt++; dot++; } a[i] = str.toCharArray(); for (int j = 1; j < str.length(); j++) { if ((str.charAt(j - 1) == 'W' && str.charAt(j) == 'S') || (str.charAt(j - 1) == 'S' && str.charAt(j) == 'W')) { chk = true; } } } for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ if(a[i][j]=='W'){ if(isPossible(i,j+1,r,c) && a[i][j+1]=='.')a[i][j+1]='D'; if(isPossible(i+1,j,r,c) && a[i+1][j]=='.')a[i+1][j]='D'; if(isPossible(i-1,j,r,c) && a[i-1][j]=='.')a[i-1][j]='D'; if(isPossible(i,j-1,r,c) && a[i][j-1]=='.')a[i][j-1]='D'; } } } if (!chk) { for (int j = 0; j < c; j++) { for (int i = 1; i < r; i++) { if ((a[i][j] == 'W' && a[i - 1][j] == 'S') || (a[i][j] == 'S' && a[i - 1][j] == 'W')) chk = true; } } } // System.out.println(chk); if (dot==0 || (chk)) { System.out.println("NO"); } else { System.out.println("YES"); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++){ System.out.print(a[i][j]); } System.out.println(); } } } private static boolean isPossible(int i, int j, int r, int c) { if(i>=0 && i<r && j>=0 && j<c) return true; return false; } }
Java
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Java 8
standard input
[ "implementation", "dfs and similar", "brute force", "graphs" ]
f55c824d8db327e531499ced6c843102
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
900
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
standard output
PASSED
56410d4beb2241e4bb56a336f9e94525
train_002.jsonl
1302706800
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.You can move your ship on the island edge, and it will be considered moving in the sea.Now you have a sea map, and you have to decide what is the minimum cost for your trip.Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.InputMismatchException; import java.math.BigInteger; import java.io.*; /** * Generated by Contest helper plug-in * Actual solution is at the bottom */ public class Main { public static void main(String[] args) { InputReader in = new StreamInputReader(System.in); PrintWriter out = new PrintWriter(System.out); run(in, out); } public static void run(InputReader in, PrintWriter out) { Solver solver = new TaskE(); solver.solve(1, in, out); Exit.exit(in, out); } } abstract class InputReader { private boolean finished = false; public abstract int read(); public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public void setFinished(boolean finished) { this.finished = finished; } public abstract void close(); } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } @Override public void close() { try { stream.close(); } catch (IOException ignored) { } } } class Exit { private Exit() { } public static void exit(InputReader in, PrintWriter out) { in.setFinished(true); in.close(); out.close(); } } interface Solver { public void solve(int testNumber, InputReader in, PrintWriter out); } class GeometryUtils { public static double epsilon = 1e-8; public static double fastHypot(double...x) { if (x.length == 0) return 0; else if (x.length == 1) return Math.abs(x[0]); else { double sumSquares = 0; for (double value : x) sumSquares += value * value; return Math.sqrt(sumSquares); } } } class Line { public final double a; public final double b; public final double c; public Line(double a, double b, double c) { double h = GeometryUtils.fastHypot(a, b); this.a = a / h; this.b = b / h; this.c = c / h; } public Point intersect(Line other) { if (parallel(other)) return null; double determinant = b * other.a - a * other.b; double x = (c * other.b - b * other.c) / determinant; double y = (a * other.c - c * other.a) / determinant; return new Point(x, y); } public boolean parallel(Line other) { return Math.abs(a * other.b - b * other.a) < GeometryUtils.epsilon; } public boolean contains(Point point) { return Math.abs(value(point)) < GeometryUtils.epsilon; } public Line perpendicular(Point point) { return new Line(-b, a, b * point.x - a * point.y); } public double value(Point point) { return a * point.x + b * point.y + c; } } class Point { public final double x; public final double y; public Point(double x, double y) { this.x = x; this.y = y; } public Line line(Point other) { if (equals(other)) return null; double a = other.y - y; double b = x - other.x; double c = -a * x - b * y; return new Line(a, b, c); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Point point = (Point) o; return Math.abs(x - point.x) <= GeometryUtils.epsilon && Math.abs(y - point.y) <= GeometryUtils.epsilon; } @Override public int hashCode() { int result; long temp; temp = x != +0.0d ? Double.doubleToLongBits(x) : 0L; result = (int) (temp ^ (temp >>> 32)); temp = y != +0.0d ? Double.doubleToLongBits(y) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } public double distance(Point other) { return GeometryUtils.fastHypot(x - other.x, y - other.y); } } class Segment { public final Point a; public final Point b; public Segment(Point a, Point b) { this.a = a; this.b = b; } public double length() { return a.distance(b); } public Point intersect(Segment other, boolean includeEnds) { Line line = line(); Line otherLine = other.a.line(other.b); if (line.parallel(otherLine)) return null; Point intersection = line.intersect(otherLine); if (contains(intersection, includeEnds) && other.contains(intersection, includeEnds)) return intersection; else return null; } public boolean contains(Point point, boolean includeEnds) { Line line = line(); if (a.equals(point) || b.equals(point)) return includeEnds; if (!line.contains(point)) return false; Line perpendicular = line.perpendicular(a); double aValue = perpendicular.value(a); double bValue = perpendicular.value(b); double pointValue = perpendicular.value(point); return aValue < pointValue && pointValue < bValue || bValue < pointValue && pointValue < aValue; } public Line line() { return a.line(b); } } class TaskE implements Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int xStart = in.readInt(); int yStart = in.readInt(); Point start = new Point(xStart, yStart); int xEnd = in.readInt(); int yEnd = in.readInt(); Point end = new Point(xEnd, yEnd); int pointCount = in.readInt(); Point[] points = new Point[pointCount]; for (int i = 0; i < pointCount; i++) { int x = in.readInt(); int y = in.readInt(); points[i] = new Point(x, y); } Segment path = new Segment(start, end); double[] edgePath = new double[2]; int index = 0; List<Point> intersectionPoints = new ArrayList<Point>(); for (int i = 0; i < pointCount; i++) { if (path.contains(points[i], false)) { Point next = points[(i + 1) % pointCount]; Point last = points[(i + pointCount - 1) % pointCount]; Line line = path.line(); if (!line.contains(next) && !line.contains(last) && line.value(next) * line.value(last) < 0) { index = 1 - index; intersectionPoints.add(points[i]); } } Segment edge = new Segment(points[i], points[(i + 1) % pointCount]); Point intersection = path.intersect(edge, false); if (intersection == null) edgePath[index] += edge.length(); else { edgePath[index] += new Segment(points[i], intersection).length(); index = 1 - index; edgePath[index] += new Segment(intersection, points[(i + 1) % pointCount]).length(); intersectionPoints.add(intersection); } } double result; if (intersectionPoints.size() == 0) result = path.length(); else result = Math.min(path.length() + new Segment(intersectionPoints.get(0), intersectionPoints.get(1)).length(), path.length() - new Segment(intersectionPoints.get(0), intersectionPoints.get(1)).length() + Math.min(edgePath[0], edgePath[1])); out.printf("%.9f\n", result); } }
Java
["1 7 6 7\n4\n4 2 4 12 3 12 3 2", "-1 0 2 0\n4\n0 0 1 0 1 1 0 1"]
2 seconds
["6.000000000", "3.000000000"]
null
Java 8
standard input
[ "geometry", "shortest paths" ]
732c0e1026ed385888adde5ec8b764c6
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≀ xStart, yStart, xEnd, yEnd ≀ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≀ n ≀ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≀ x, y ≀ 100), the polygon points will be distinct.
2,400
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
standard output
PASSED
abf6936e00d45b015aa48fa9e55c32a3
train_002.jsonl
1302706800
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.You can move your ship on the island edge, and it will be considered moving in the sea.Now you have a sea map, and you have to decide what is the minimum cost for your trip.Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
256 megabytes
import java.util.*; import static java.lang.Math.*; public class E { public static void main(String[] args){ Scanner in = new Scanner(System.in); st = new Point(in.nextInt(), in.nextInt()); en = new Point(in.nextInt(), in.nextInt()); int N = in.nextInt(); Point[] P = new Point[N]; for(int i = 0; i < N;i++) P[i] = new Point(in.nextInt(), in.nextInt()); ArrayList<ArrayList<Edge>> G = new ArrayList<ArrayList<Edge>>(); for(int i = 0; i < N;i++){ G.add(new ArrayList<Edge>()); int prev = (i-1+N)%N; int next = (i+1)%N; G.get(i).add(new Edge(prev, P[i].dist(P[prev]))); G.get(i).add(new Edge(next, P[i].dist(P[next]))); } ArrayList<Point> inter = new ArrayList<Point>(); inter.add(st); inter.add(en); for(int i = 0; i < N;i++){ Line s1 = new Line(st, en); Line s2 = new Line(P[i], P[(i+1)%N]); Point inte = segseg(s1, s2); if(inte != null) inter.add(inte); } Collections.sort(inter, new Comparator<Point>(){ public int compare(Point p1, Point p2) { double d1 = st.dist(p1); double d2 = st.dist(p2); if(d1 < d2) return -1; if(d1 > d2) return 1; return 0; }}); for(int i = 0; i < inter.size()-1;i++){ if(inter.get(i).equals(inter.get(i+1))){ inter.remove(i+1); } } if(inter.size() == 3) inter.remove(1); int stidx = -1, enidx = -1; for(int i = 0; i < inter.size(); i++){ G.add(new ArrayList<Edge>()); Point p = inter.get(i); if(p.equals(st)) stidx = i+N; if(p.equals(en)) enidx = i+N; for(int j = 0; j < N;j++){ if(onseg(new Line(P[j], P[(j+1)%N]), p)){ G.get(i+N).add(new Edge(j, p.dist(P[j]))); G.get(j).add(new Edge(i+N, p.dist(P[j]))); G.get(i+N).add(new Edge((j+1)%N, p.dist(P[(j+1)%N]))); G.get((j+1)%N).add(new Edge(i+N, p.dist(P[(j+1)%N]))); } } } for(int i = 0; i < inter.size()-1; i++){ int cost = i%2 == 0 ? 1 : 2; G.get(i+N).add(new Edge(i+N+1, cost*inter.get(i).dist(inter.get(i+1)))); G.get(i+N+1).add(new Edge(i+N, cost*inter.get(i).dist(inter.get(i+1)))); } double[] dist = new double[G.size()]; Arrays.fill(dist, Long.MAX_VALUE); dist[stidx] = 0; PriorityQueue<State> pq = new PriorityQueue<State>(); pq.add(new State(stidx, 0)); while(pq.size() > 0){ State at = pq.poll(); if(dist[at.at] < at.dist) continue; for(Edge e: G.get(at.at)){ if(at.dist+e.cost < dist[e.to]-eps){ dist[e.to] = at.dist+e.cost; pq.add(new State(e.to, dist[e.to])); } } } System.out.format("%.15f\n", dist[enidx]); } static Point st, en; static class Edge{ int to; double cost; public Edge(int to, double cost){ this.to = to; this.cost = cost; } } static class State implements Comparable<State>{ int at; double dist; public State(int at, double dist){ this.at = at; this.dist = dist; } public int compareTo(State s){ if(dist < s.dist) return -1; if(dist > s.dist) return 1; return 0; } } static double eps = 1e-9; static boolean EQ(double a, double b){return abs(a-b) < eps;} static double SQ(double d){return d*d;} static double normang(double t){ return ((t % (2*PI)) + 2*PI) % (2*PI); } static double angdiff(double t1, double t2){ return normang(t1 - t2 + PI) - PI; } static ArrayList<Point> makeVec(Point...P){ ArrayList<Point> ans = new ArrayList<Point>(); for(Point p:P) ans.add(p); return ans; } static class Point{ double x, y; public Point(double x, double y){this.x = x;this.y = y;} Point add(Point p){return new Point(x+p.x, y+p.y);} Point sub(Point p){return new Point(x-p.x, y-p.y);} Point mult(double d){return new Point(x*d, y*d);} double dot(Point p){return x*p.x+ y*p.y;} double cross(Point p){return x*p.y - y*p.x;} double len(){return hypot(x, y);} Point scale(double d){return mult(d/len());} double dist(Point p){return sub(p).len();} double ang(){return atan2(y, x);} static Point polar(double r, double theta){return new Point(r*cos(theta), r*sin(theta));} Point rot(double theta){return new Point(x*cos(theta)-y*sin(theta), x*sin(theta)+y*cos(theta));} Point perp(){return new Point(-y, x);} boolean equals(Point p){return EQ(0, dist(p));} double norm(){return dot(this);} public String toString(){return String.format("(%.03f, %.03f)", x, y);} } static class Line{ Point a, b; Line(Point a, Point b){this.a = a;this.b = b;} public String toString(){return String.format("{%s -> %s}", a, b);} } static class Circle{ Point p;double r; public Circle(Point p, double r){this.p = p;this.r = r;} public Circle(Point a, Point b, Point c){ Point p1 = a.add(b).mult(0.5); Line l1 = new Line(p1, p1.add(a.sub(b).perp())); Point p2 = b.add(c).mult(0.5); Line l2 = new Line(p2, p2.add(b.sub(c).perp())); p = lineline(l1, l2); assert(p != null); r = p.dist(a); } } static double ccw(Point p1, Point p2, Point p3){ return p2.sub(p1).cross(p3.sub(p1)); } static Point lineline(Line a, Line b){//tested double d = a.b.sub(a.a).cross(b.b.sub(b.a)); if(EQ(d, 0)) return null; return a.a.add((a.b.sub(a.a)).mult(b.b.sub(b.a).cross(a.a.sub(b.a))/d)); } static Point segline(Line a, Line b){ Point inter = lineline(a, b); if(inter == null || !onseg(a, inter)) return null; return inter; } static Point segseg(Line a, Line b){//tested Point inter = lineline(a, b); if(inter == null || !onseg(a, inter) || !onseg(b, inter)) return null; return inter; } static boolean onseg(Line l, Point p){ //tested Point delta = l.b.sub(l.a); return online(l, p) && delta.dot(l.a)-eps <= delta.dot(p) && delta.dot(p) <= delta.dot(l.b)+eps; } static boolean online(Line l, Point p){ //tested return EQ(ccw(l.a, l.b, p), 0); } static Point pointline(Point p, Line l){ Point v = l.b.sub(l.a).scale(1); double dot = p.sub(l.a).dot(v); return l.a.add(v.mult(dot)); } static Point pointseg(Point p, Line l){ Point v = l.b.sub(l.a).scale(1); double dot = p.sub(l.a).dot(v); dot = max(dot, 0); dot = min(dot, l.b.dist(l.a)); return l.a.add(v.mult(dot)); } static double pointsegdist(Point p, Line l){ return pointseg(p, l).dist(p); } static double pointlinedist(Point p, Line l){ return pointline(p, l).dist(p); } static double polyarea(Point[] poly){ double area = 0; for(int i = 0; i < poly.length; i++) area += poly[i].cross(poly[(i+1)%poly.length]); return abs(area)/2.0; } static int pointinpoly(Point[] poly, Point p){ double ang = 0.0; for(int i = 0; i < poly.length; i++){ Point a = poly[i]; Point b = poly[(i+1)%poly.length]; if(onseg(new Line(a, b), p)) return 0; ang += angdiff(a.sub(p).ang(), b.sub(p).ang()); } return EQ(ang, 0) ? -1 : 1; } static Point v0; static ArrayList<Point> convexhull(ArrayList<Point> P){//tested v0 = null; for(Point p:P) if(v0 == null || p.x < v0.x - eps || (EQ(p.x, v0.x) && p.y < v0.y)) v0 = p; Collections.sort(P, new Comparator<Point>(){ public int compare(Point a, Point b){ if(a == v0) return -1; if(b == v0) return 1; double ccw = ccw(v0, a, b); if(EQ(ccw, 0)){ double d1 = v0.dist(a); double d2 = v0.dist(b); if(d1 < d2) return -1; if(d1 > d2) return 1; return 0; } return (int) -signum(ccw); }}); ArrayList<Point> ch = new ArrayList<Point>(); for(Point p:P){ while(ch.size() >= 2 && ccw(ch.get(ch.size()-2), ch.get(ch.size()-1), p) <= 0) ch.remove(ch.size()-1); ch.add(p); } return ch; } //add half space intersection //circle static ArrayList<Point> circline(Circle c, Line l){ Point x = pointline(c.p, l); double d = x.dist(c.p); if(d > c.r + eps) return new ArrayList<Point>(); double h = sqrt(SQ(c.r) - SQ(d)); Point v = x.sub(c.p); return makeVec(c.p.add(v.scale(d)).add(v.scale(h)), c.p.add(v.scale(d)).add(v.scale(-h))); } static ArrayList<Point> circcirc(Circle a, Circle b){ double d = a.p.dist(b.p); if(d > a.r + b.r + eps) return new ArrayList<Point>(); if(d < abs(a.r - b.r) - eps) return new ArrayList<Point>(); double x = (SQ(d) - SQ(b.r) + SQ(a.r)) / 2*d; double y = sqrt(SQ(a.r) - SQ(x)); Point v = b.p.sub(a.p); return makeVec(a.p.add(v.scale(x)).add(v.perp().scale(y)), a.p.add(v.scale(x)).add(v.perp().scale(-y))); } static ArrayList<Line> circcirctan(Circle a, Circle b){//tested if(a.r < b.r) return circcirctan(b, a); ArrayList<Line> res = new ArrayList<Line>(); double d = a.p.dist(b.p); double d1 = a.r*d/(a.r + b.r); double t = acos(a.r/d1); Point v = b.p.sub(a.p); res.add(new Line(a.p.add(v.scale(a.r).rot(t)), b.p.add(v.scale(-b.r).rot(t)))); res.add(new Line(a.p.add(v.scale(a.r).rot(-t)), b.p.add(v.scale(-b.r).rot(-t)))); t = asin((a.r-b.r)/d)+PI/2; v = a.p.sub(b.p); res.add(new Line(a.p.add(v.scale(a.r).rot(t)), b.p.add(v.scale(b.r).rot(t)))); res.add(new Line(a.p.add(v.scale(a.r).rot(-t)), b.p.add(v.scale(b.r).rot(-t)))); return res; } //3d static class Point3{ double x, y, z; Point3(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } static Point3 sphere(double theta, double phi, double r){ return new Point3(r*cos(theta)*sin(phi),r*sin(theta)*sin(phi),r*cos(theta)); } double[] ang(){ return new double[]{atan(y/x), acos(z/len())}; } Point proj(){ return new Point(x, y); } Point3 add(Point3 p){ return new Point3(x+p.x, y+p.y, z+p.z); } Point3 sub(Point3 p){ return new Point3(x-p.x, y-p.y, z-p.z); } double dot(Point3 p){ return x*p.x+ y*p.y+ z*p.z; } Point3 cross(Point3 p){ return new Point3(y*p.z-p.y*z, z*p.x-p.z*x, x*p.y-p.x*y); } Point3 mult(double d){ return new Point3(x*d, y*d, z*d); } double len(){ return sqrt(x*x+y*y+z*z); } Point3 scale(double d){ return mult(d/len()); } double dist(Point3 p){ return sub(p).len(); } boolean equals(Point3 p){ return EQ(dist(p), 0); } } static Point3[] getbasis(Point3 z){ z = z.scale(1); Point3 t = new Point3(1, 0, 0); Point3 y = z.cross(t); if(EQ(y.len(), 0)){ t = new Point3(0, 1, 0); y = z.cross(t); } Point3 x = y.cross(z); assert(x.cross(y).equals(z)); return new Point3[]{x, y, z}; } static Point3 trans(Point3[] B, Point3 p){ return new Point3(B[0].dot(p), B[1].dot(p), B[2].dot(p)); } static Point3 invtrans(Point3[] B, Point3 p){ return B[0].mult(p.x).add(B[1].mult(p.y)).add(B[2].mult(p.z)); } }
Java
["1 7 6 7\n4\n4 2 4 12 3 12 3 2", "-1 0 2 0\n4\n0 0 1 0 1 1 0 1"]
2 seconds
["6.000000000", "3.000000000"]
null
Java 6
standard input
[ "geometry", "shortest paths" ]
732c0e1026ed385888adde5ec8b764c6
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≀ xStart, yStart, xEnd, yEnd ≀ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≀ n ≀ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≀ x, y ≀ 100), the polygon points will be distinct.
2,400
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
standard output
PASSED
ea1820617da751efbcac4f7b82b0a2a8
train_002.jsonl
1302706800
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.You can move your ship on the island edge, and it will be considered moving in the sea.Now you have a sea map, and you have to decide what is the minimum cost for your trip.Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) { } new Thread(null, new Runnable() { public void run() { try { new Main().run(); } catch (Throwable e) { e.printStackTrace(); exit(999); } } }, "1", 1 << 23).start(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); int n; int up(int z){ return (z + 1)%n; } int down(int z){ return (z - 1 + n)%n; } private void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); P s = new P(nextInt(), nextInt()); P t = new P(nextInt(), nextInt()); n = nextInt(); P m[] = new P[n]; double ds[] = new double[n]; double dt[] = new double[n]; fill(ds, 1e10); fill(dt, 1e10); for(int i = 0; i< n; i++) m[i] = new P(nextInt(), nextInt()); boolean strictly = true; L line = new L(); line.set(s,t); L dl = new L(); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++){ dl.set(m[i],m[j]); if(line.test(dl)){ strictly = false; } } if(strictly){ out.printf(Locale.US, "%.9f\n",dist(s,t)); in.close(); out.close(); return; } //οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½!!! οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½! double ans = Double.MAX_VALUE; dP dop[] = new dP[3]; int ind = 0; L l1 = new L(); L l2 = new L(); l2.set(s,t); for(int i = 0; i < n; i++){ l1.set(m[i], m[up(i)]); if(l1.test(l2) || l2.get(m[i]) == 0){ dop[ind++] = l1.inter(l2); boolean fst = true; boolean sec = true; for(int j = 0; j < n; j++){ if(l1.get(s) * l1.get(m[j]) > 0) fst = false; if(l1.get(t) * l1.get(m[j]) > 0) sec = false; } if(fst){ ds[i] = dist(s, dop[ind-1]) + dist(m[i], dop[ind-1]); ds[up(i)] = dist(s, dop[ind-1]) + dist(m[up(i)], dop[ind-1]); // System.err.println("fst " + i + " " + up(i)); } if(sec){ dt[i] = dist(t, dop[ind-1]) + dist(m[i], dop[ind-1]); dt[up(i)] = dist(t, dop[ind-1]) + dist(m[up(i)], dop[ind-1]); // System.err.println("sec " + i + " " + up(i)); // System.err.println(dt[i]); // System.err.println(dt[up(i)]); // System.err.println(m[i].x + " " + dop[ind-1].x + " " + m[up(i)].x); } // out.println(dop[ind-1].x + " " + dop[ind-1].y); } } if(ind == 2){ if(dist(s, dop[0]) > dist(s, dop[1])){ dop[2] = dop[0]; dop[0] = dop[1]; dop[1] = dop[2]; } ans = dist(s, t) + dist(dop[0], dop[1]); // out.println(ans); } if(ind == 1){//! οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ } for(int st = 0; st < n; st++) for(int ne = up(st); ne != st; ne = up(ne)){ if(ds[ne] > ds[st] + 2 * dist(m[st], m[ne])) ds[ne] = ds[st] + 2 * dist(m[st], m[ne]); } for(int cc = 0; cc < n+2; cc++) for(int st = 0; st < n; st++) { int ne = up(st); if(ds[ne] > ds[st] + dist(m[st], m[ne])) ds[ne] = ds[st] + dist(m[st], m[ne]); ne = down(st); if(ds[ne] > ds[st] + dist(m[st], m[ne])) ds[ne] = ds[st] + dist(m[st], m[ne]); } for(int i = 0; i < n; i++) if(ds[i] + dt[i] < ans) ans = ds[i] + dt[i]; // System.err.println(Arrays.toString(ds)); // System.err.println(Arrays.toString(dt)); out.printf(Locale.US, "%.9f\n",ans); in.close(); out.close(); } class P{ int x, y; P(int xx, int yy){ x = xx; y = yy; } } class dP{ double x, y; dP(double xx, double yy){ x = xx; y = yy; } } class L{ int a,b,c; P p1,p2; L(){ a = b = c = 0; } void set(P p1, P p2){ a = p1.y - p2.y; b = p2.x - p1.x; c = -(a * p1.x + b * p1.y); this.p1 = new P(p1.x, p1.y); this.p2 = new P(p2.x, p2.y); } int get(P p1){ int z = a * p1.x + b * p1.y + c; if(z == 0) return z; return z > 0 ? 1 : -1; } dP inter(L l){ dP p = new dP(0,0); double delta = a * l.b - b * l.a; p.x = ((-c * l.b) - (-l.c * b)) / delta; p.y = ((a * -l.c) - (-c * l.a)) / delta; return p; } boolean test(L l2){ boolean f = true; f &= l2.get(p1) * l2.get(p2) < 0; f &= get(l2.p1)* get(l2.p2) < 0; return f; } } double dist(P a, P b){ return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)); } double dist(P a, dP b){ return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)); } double dist(dP a, dP b){ return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)); } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["1 7 6 7\n4\n4 2 4 12 3 12 3 2", "-1 0 2 0\n4\n0 0 1 0 1 1 0 1"]
2 seconds
["6.000000000", "3.000000000"]
null
Java 6
standard input
[ "geometry", "shortest paths" ]
732c0e1026ed385888adde5ec8b764c6
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≀ xStart, yStart, xEnd, yEnd ≀ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≀ n ≀ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≀ x, y ≀ 100), the polygon points will be distinct.
2,400
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
standard output
PASSED
22b109a1b745e452b8a76873996d72bb
train_002.jsonl
1302706800
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.You can move your ship on the island edge, and it will be considered moving in the sea.Now you have a sea map, and you have to decide what is the minimum cost for your trip.Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.InputMismatchException; import java.math.BigInteger; import java.io.*; /** * Generated by Contest helper plug-in * Actual solution is at the bottom */ public class Main { public static void main(String[] args) { InputReader in = new StreamInputReader(System.in); PrintWriter out = new PrintWriter(System.out); run(in, out); } public static void run(InputReader in, PrintWriter out) { Solver solver = new TaskE(); solver.solve(1, in, out); Exit.exit(in, out); } } abstract class InputReader { private boolean finished = false; public abstract int read(); public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public void setFinished(boolean finished) { this.finished = finished; } public abstract void close(); } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } @Override public void close() { try { stream.close(); } catch (IOException ignored) { } } } class Exit { private Exit() { } public static void exit(InputReader in, PrintWriter out) { in.setFinished(true); in.close(); out.close(); } } interface Solver { public void solve(int testNumber, InputReader in, PrintWriter out); } class GeometryUtils { public static double epsilon = 1e-8; public static double fastHypot(double...x) { if (x.length == 0) return 0; else if (x.length == 1) return Math.abs(x[0]); else { double sumSquares = 0; for (double value : x) sumSquares += value * value; return Math.sqrt(sumSquares); } } } class Line { public final double a; public final double b; public final double c; public Line(double a, double b, double c) { double h = GeometryUtils.fastHypot(a, b); this.a = a / h; this.b = b / h; this.c = c / h; } public Point intersect(Line other) { if (parallel(other)) return null; double determinant = b * other.a - a * other.b; double x = (c * other.b - b * other.c) / determinant; double y = (a * other.c - c * other.a) / determinant; return new Point(x, y); } public boolean parallel(Line other) { return Math.abs(a * other.b - b * other.a) < GeometryUtils.epsilon; } public boolean contains(Point point) { return Math.abs(value(point)) < GeometryUtils.epsilon; } public Line perpendicular(Point point) { return new Line(-b, a, b * point.x - a * point.y); } public double value(Point point) { return a * point.x + b * point.y + c; } } class Point { public final double x; public final double y; public Point(double x, double y) { this.x = x; this.y = y; } public Line line(Point other) { if (equals(other)) return null; double a = other.y - y; double b = x - other.x; double c = -a * x - b * y; return new Line(a, b, c); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Point point = (Point) o; return Math.abs(x - point.x) <= GeometryUtils.epsilon && Math.abs(y - point.y) <= GeometryUtils.epsilon; } @Override public int hashCode() { int result; long temp; temp = x != +0.0d ? Double.doubleToLongBits(x) : 0L; result = (int) (temp ^ (temp >>> 32)); temp = y != +0.0d ? Double.doubleToLongBits(y) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } public double distance(Point other) { return GeometryUtils.fastHypot(x - other.x, y - other.y); } } class Segment { public final Point a; public final Point b; public Segment(Point a, Point b) { this.a = a; this.b = b; } public double length() { return a.distance(b); } public Point intersect(Segment other, boolean includeEnds) { Line line = line(); Line otherLine = other.a.line(other.b); if (line.parallel(otherLine)) return null; Point intersection = line.intersect(otherLine); if (contains(intersection, includeEnds) && other.contains(intersection, includeEnds)) return intersection; else return null; } public boolean contains(Point point, boolean includeEnds) { Line line = line(); if (a.equals(point) || b.equals(point)) return includeEnds; if (!line.contains(point)) return false; Line perpendicular = line.perpendicular(a); double aValue = perpendicular.value(a); double bValue = perpendicular.value(b); double pointValue = perpendicular.value(point); return aValue < pointValue && pointValue < bValue || bValue < pointValue && pointValue < aValue; } public Line line() { return a.line(b); } } class TaskE implements Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int xStart = in.readInt(); int yStart = in.readInt(); Point start = new Point(xStart, yStart); int xEnd = in.readInt(); int yEnd = in.readInt(); Point end = new Point(xEnd, yEnd); int pointCount = in.readInt(); Point[] points = new Point[pointCount]; for (int i = 0; i < pointCount; i++) { int x = in.readInt(); int y = in.readInt(); points[i] = new Point(x, y); } Segment path = new Segment(start, end); double[] edgePath = new double[2]; int index = 0; List<Point> intersectionPoints = new ArrayList<Point>(); for (int i = 0; i < pointCount; i++) { if (path.contains(points[i], false)) { Point next = points[(i + 1) % pointCount]; Point last = points[(i + pointCount - 1) % pointCount]; Line line = path.line(); if (!line.contains(next) && !line.contains(last) && line.value(next) * line.value(last) < 0) { index = 1 - index; intersectionPoints.add(points[i]); } } Segment edge = new Segment(points[i], points[(i + 1) % pointCount]); Point intersection = path.intersect(edge, false); if (intersection == null) edgePath[index] += edge.length(); else { edgePath[index] += new Segment(points[i], intersection).length(); index = 1 - index; edgePath[index] += new Segment(intersection, points[(i + 1) % pointCount]).length(); intersectionPoints.add(intersection); } } double result; if (intersectionPoints.size() == 0) result = path.length(); else result = Math.min(path.length() + new Segment(intersectionPoints.get(0), intersectionPoints.get(1)).length(), path.length() - new Segment(intersectionPoints.get(0), intersectionPoints.get(1)).length() + Math.min(edgePath[0], edgePath[1])); out.printf("%.9f\n", result); } }
Java
["1 7 6 7\n4\n4 2 4 12 3 12 3 2", "-1 0 2 0\n4\n0 0 1 0 1 1 0 1"]
2 seconds
["6.000000000", "3.000000000"]
null
Java 6
standard input
[ "geometry", "shortest paths" ]
732c0e1026ed385888adde5ec8b764c6
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≀ xStart, yStart, xEnd, yEnd ≀ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≀ n ≀ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≀ x, y ≀ 100), the polygon points will be distinct.
2,400
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
standard output
PASSED
9b3ba54eb7b3f451b777a6a132ff4dae
train_002.jsonl
1302706800
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.You can move your ship on the island edge, and it will be considered moving in the sea.Now you have a sea map, and you have to decide what is the minimum cost for your trip.Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
256 megabytes
import java.util.Scanner; public class ShipShortestPath { static class Line { double a, b, c, x1, x2, y1, y2; public Line(double x1, double y1, double x2, double y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; a = -1 * (y2 - y1); b = (x2 - x1); c = y1 * (x2 - x1) - x1 * (y2 - y1); } public double getLength() { return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } } static class Point { double x, y; public Point(double xx, double yy) { x = xx; y = yy; } } public static Point intersect(Line i, Line j) { double det = i.a * j.b - i.b * j.a; if (det == 0) return null; double xin = j.b * i.c - i.b * j.c; xin = xin / det; double yin = i.a * j.c - i.c * j.a; yin = yin / det; //System.out.println(yin+" "+xin); if (xin <= Math.max(i.x1, i.x2) && xin >= Math.min(i.x1, i.x2) && xin <= Math.max(j.x1, j.x2) && xin >= Math.min(j.x1, j.x2)) if (yin <= Math.max(i.y1, i.y2) && yin >= Math.min(i.y1, i.y2) && yin <= Math.max(j.y1, j.y2) && yin >= Math.min(j.y1, j.y2)) return new Point(xin, yin); return null; } public static boolean equal(Point x,Point y) { if(Math.abs(x.x-y.x)<1e-7&&Math.abs(x.y-y.y)<1e-7) return true; return false; } public static double getDist(Point a ,Point b) { return Math.sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); double sx, sy, ex, ey; sx = sc.nextDouble(); sy = sc.nextDouble(); ex = sc.nextDouble(); ey = sc.nextDouble(); Line trip=new Line(sx, sy, ex, ey); //System.out.println(trip.a+" "+trip.b+" "+trip.c); Point s=new Point(sx,sy); Point e=new Point(ex,ey); int n = sc.nextInt(); double x1 = sc.nextDouble(), y1 = sc.nextDouble(), x2, y2, x11 = x1, y11 = y1; Line[] Poly = new Line[n]; for (int i = 0; i < n - 1; i++) { x2 = sc.nextDouble(); y2 = sc.nextDouble(); Poly[i] = new Line(x1, y1, x2, y2); x1 = x2; y1 = y2; } Poly[n - 1] = new Line(x1, y1, x11, y11); Point int1=null,int2=null; int i=0; int f=0,se=0; for(;i<n;i++) { Point t=intersect(trip, Poly[i]); if(t==null) continue; else { //System.out.println(t.x); int1=t; f=i;break; } } if(int1!=null) { for(;i<n;i++) { Point t=intersect(trip, Poly[i]); if(t==null) continue; else { if(equal(t, int1)) continue; int2=t; se=i;break; } } if(int2!=null) { //System.out.println(int1.x+" "+int1.y+"\n "+int2.x+" "+int2.y); double a1=0,a2=0; //System.out.println(f+" das "+se); for(int j=f+1;j<se;j++) a1+=Poly[j].getLength(); //System.out.println(a1); a1+=getDist(int1, new Point(Poly[f+1].x1, Poly[f+1].y1))+ getDist(int2, new Point(Poly[se].x1, Poly[se].y1)); a2+=getDist(int1, new Point(Poly[(f-1+n)%n].x2, Poly[(f-1+n)%n].y2)); for(int j=(se+1)%n;j!=f;j=(j+1)%n) a2+=Poly[j].getLength(); //System.out.println(getDist(int1, new Point(Poly[(f-1+n)%n].x2, Poly[(f-1+n)%n].y2))+" "+getDist(int2, new Point(Poly[(se+1)%n].x1, Poly[(se+1)%n].y1))); a2+=getDist(int2, new Point(Poly[(se+1)%n].x1, Poly[(se+1)%n].y1)); double t1,t2,t3; if(getDist(s, int1)<getDist(s, int2)) { t1=getDist(s, int1)+getDist(int1, int2)*2+getDist(int2, e); t2=getDist(s, int1)+a1+getDist(int2, e); t3=getDist(s, int1)+a2+getDist(int2, e); } else { t1=getDist(s, int2)+getDist(int2, int1)*2+getDist(int1, e); t2=getDist(s, int2)+a1+getDist(int1, e); t3=getDist(s, int2)+a2+getDist(int1, e); } //System.out.println(t1+" "+t2+" "+t3+" "+a1+" "+a2); System.out.println(Math.min(Math.min(t1, t2), t3)); return; } } System.out.println(trip.getLength()*1); } }
Java
["1 7 6 7\n4\n4 2 4 12 3 12 3 2", "-1 0 2 0\n4\n0 0 1 0 1 1 0 1"]
2 seconds
["6.000000000", "3.000000000"]
null
Java 6
standard input
[ "geometry", "shortest paths" ]
732c0e1026ed385888adde5ec8b764c6
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≀ xStart, yStart, xEnd, yEnd ≀ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≀ n ≀ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≀ x, y ≀ 100), the polygon points will be distinct.
2,400
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
standard output
PASSED
68a4ad8235d9eeab80f62c0f70eeef28
train_002.jsonl
1302706800
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.You can move your ship on the island edge, and it will be considered moving in the sea.Now you have a sea map, and you have to decide what is the minimum cost for your trip.Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
256 megabytes
import java.util.*; public class Ship { public static double EPS = 1e-9; public static void main(String[] args){ Scanner reader = new Scanner(System.in); Point s = new Point(reader.nextDouble(), reader.nextDouble()); Point t = new Point(reader.nextDouble(), reader.nextDouble()); int n = reader.nextInt(); Point[] p = new Point[n]; for(int i = 0; i < n; i++) p[i] = new Point(reader.nextDouble(), reader.nextDouble()); //1. Find points of intersection between segment ST and each segment along the polygon, // add to treeset for uniqueness TreeSet<Point> set = new TreeSet<Point>(); boolean flag = false; for(int i = 0; i < n; i++){ Point a = p[i]; Point b = p[(i+1)%n]; if(segmentIntersect(s,t,a,b)){ Point c = intersect(s,t,a,b); flag |= c==null; //System.out.println(c); if(c != null) set.add(c); } } //2.a If set size <= 1, return 0! if(set.size() <= 1 || flag){ System.out.printf("%.10f\n", s.dis(t)); }else{ //2.b Build graph of size n + 4 int m = n+4; double[][] g = new double[m][m]; for(double[] e:g)Arrays.fill(e,1e9); for(int i = 0; i < m; i++) g[i][i] = 0; ArrayList<Point> h = new ArrayList<Point>(); for(Point c:set) h.add(c); //Add edges from start and end to polygon intersects for(int i = 0; i < 2; i++){ if(h.get(i).dis(s) < h.get((i+1)%2).dis(s)){ g[0][i+2] = h.get(i).dis(s); g[i+2][0] = g[0][i+2]; }else{ g[i+2][1] = h.get(i).dis(t); g[1][i+2] = g[i+2][1]; } } //Add edge between intersects g[2][3] = 2*h.get(0).dis(h.get(1)); g[3][2] = g[2][3]; //Add edges from intersects to polygon vertices for(int j = 0; j < 2; j++){ for(int i = 0; i < n; i++){ Point a = p[i]; Point b = p[(i+1)%n]; if(pldist(a,b,h.get(j)) < EPS){ g[j+2][i+4] = a.dis(h.get(j)); g[i+4][j+2] = g[j+2][i+4]; g[j+2][(i+1)%n+4] = b.dis(h.get(j)); g[(i+1)%n+4][j+2] = g[j+2][(i+1)%n+4]; } g[j+2][i+4] = Math.min(g[j+2][i+4], 2*a.dis(h.get(j))); g[i+4][j+2] = Math.min(g[i+4][j+2], g[j+2][i+4]); } } for(int i = 0; i < n; i++){ //Add edges from polygon vertices to polygon vertices for(int j = 0; j < n; j++){ double d = p[i].dis(p[j])*2; if(j == (i+1)%n || j == (i-1+n)%n) d /= 2; g[i+4][j+4] = d; g[j+4][i+4] = d; } //Add edges from start point to polygon vertices /*TreeSet<Point> chk = new TreeSet<Point>(); for(int j = 0; j < n; j++){ Point a = p[j]; Point b = p[(j+1)%n]; if(segmentIntersect(s,p[i],a,b)){ Point c = intersect(s,p[i],a,b); if(c != null) chk.add(c); } } if(chk.size() == 1){ g[0][i+4] = s.dis(p[i]); g[i+4][0] = g[0][i+4]; } chk.clear(); //Add edges from polygon vertices to end point chk = new TreeSet<Point>(); for(int j = 0; j < n; j++){ Point a = p[j]; Point b = p[(j+1)%n]; if(segmentIntersect(p[i],t,a,b)){ Point c = intersect(p[i],t,a,b); if(c != null) chk.add(c); } } if(chk.size() == 1){ g[1][i+4] = t.dis(p[i]); g[i+4][1] = g[1][i+4]; }*/ } // for(double[] e:g) // System.out.println(Arrays.toString(e)); //3. Floyd's! for(int k = 0; k < m; k++){ for(int i = 0; i < m; i++){ for(int j = 0; j < m; j++){ g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); } } } System.out.printf("%.10f",g[0][1]); } } static boolean segmentIntersect(Point a, Point b, Point c, Point d){ Point e = b.sub(a); Point f = d.sub(c); if(Math.abs(c.sub(a).cross(e)) < EPS && Math.abs(d.sub(a).cross(e)) < EPS) return (c.sub(a).dot(e) > -EPS && c.sub(b).dot(a.sub(b)) > -EPS) || (d.sub(a).dot(e) > -EPS && d.sub(b).dot(a.sub(b)) > -EPS) || (a.sub(c).dot(f) > -EPS && a.sub(d).dot(c.sub(d)) > -EPS) || (b.sub(c).dot(f) > -EPS && b.sub(d).dot(c.sub(d)) > -EPS); return Math.signum(b.sub(c).cross(f)) != Math.signum(a.sub(c).cross(f)) && Math.signum(c.sub(a).cross(e)) != Math.signum(d.sub(a).cross(e)); } //Point-line distance //Input: Line from A to B, point to be tested p public static double pldist(Point a, Point b, Point p){ Point c = p.sub(a); Point d = b.sub(a); if(c.dot(d) < 0) return p.dis(a); if(p.sub(b).dot(d.scale(-1)) < 0) return p.dis(b); return Math.abs(c.cross(d))/d.mag(); } //Line-line intersection //Input: Line AB, Line CD //Returns: null if the lines are parallel, point of intersection otherwise //Notes: Detects coincidence, handling left for a per-problem basis static Point intersect(Point a, Point b, Point c, Point d){ Point e = d.sub(c), f = a.sub(c), g = b.sub(a); double AB = e.cross(f); double CD = g.cross(f); double D = g.cross(e); //if AB == CD == D == 0, then the lines are coincident //if D == 0, the lines are parallel if(Math.abs(D) < EPS) return null; return a.add(g.scale(AB/D)); } public static class Point implements Comparable<Point>{ double x,y; public Point(double _x, double _y){ x = _x; y = _y; } public Point sub(Point p){ return new Point(x-p.x, y-p.y); } public Point add(Point p){ return new Point(x+p.x, y+p.y); } public Point scale(double L){ return new Point(x*L, y*L); } public Point rot(double t){ double c = Math.cos(t); double s = Math.sin(t); return new Point(x*c-y*s, x*s+y*c); } public Point norm(){ return new Point(x/mag(), y/mag()); } public Point project(Point p){ return p.scale(dot(p)/p.dot(p)); } public double dot(Point p){ return x*p.x + y*p.y; } public double cross(Point p){ return x*p.y-y*p.x; } public double angBetween(Point p){ double d = Math.abs(ang()-p.ang()); return Math.min(d, 2*Math.PI-d); } public double mag(){ return Math.abs(Math.sqrt(x*x + y*y)); } public double ang(){ double a = Math.atan2(y,x); if(a<0) a+=2*Math.PI; return a; } public double dis(Point p){ return sub(p).mag(); } public int compareTo(Point p){ if(Math.abs(x-p.x) < EPS){ if(Math.abs(y-p.y) < EPS) return 0; return (int)Math.signum(y-p.y); } return (int)Math.signum(x-p.x); } public String toString(){ return "("+x+", "+y+")"; } } }
Java
["1 7 6 7\n4\n4 2 4 12 3 12 3 2", "-1 0 2 0\n4\n0 0 1 0 1 1 0 1"]
2 seconds
["6.000000000", "3.000000000"]
null
Java 6
standard input
[ "geometry", "shortest paths" ]
732c0e1026ed385888adde5ec8b764c6
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≀ xStart, yStart, xEnd, yEnd ≀ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≀ n ≀ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≀ x, y ≀ 100), the polygon points will be distinct.
2,400
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
standard output
PASSED
451d9e2020b5dac244cb3521af0afb34
train_002.jsonl
1302706800
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.You can move your ship on the island edge, and it will be considered moving in the sea.Now you have a sea map, and you have to decide what is the minimum cost for your trip.Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
256 megabytes
//package round67; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Locale; import java.util.StringTokenizer; public class E { static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static String nextToken() throws IOException{ while (st==null || !st.hasMoreTokens()){ String s = bf.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } static int nextInt() throws IOException{ return Integer.parseInt(nextToken()); } static long nextLong() throws IOException{ return Long.parseLong(nextToken()); } static String nextStr() throws IOException{ return nextToken(); } static double nextDouble() throws IOException{ return Double.parseDouble(nextToken()); } static double sqr(double a){ return a*a; } public static void main(String[] args) throws IOException{ int x1 = nextInt(), y1 = nextInt(), x2 = nextInt(), y2 = nextInt(), n = nextInt(), x[] = new int[n+1], y[] = new int[n+1]; for (int i=0; i<n; i++){ x[i] = nextInt(); y[i] = nextInt(); } x[n] = x[0]; y[n] = y[0]; int a = y2-y1, b = x1-x2, c = -(a*x1+b*y1); double d = Math.sqrt(sqr(x2-x1)+sqr(y2-y1)); for (int i=0; i<n; i++) if (a*x[i]+b*y[i]+c==0 && a*x[i+1]+b*y[i+1]+c==0){ out.printf(Locale.US, "%.7f", d); out.flush(); return; } int s1 = -1, s2 = -1; for (int i=0; i<n; i++){ int aa = y[i]-y[i+1], bb = x[i+1]-x[i], cc = -(aa*x[i]+bb*y[i]); if ((a*x[i]+b*y[i]+c)*(long)(a*x[i+1]+b*y[i+1]+c) <= 0 && (aa*x1+bb*y1+cc)*(long)(aa*x2+bb*y2+cc) <= 0){ if (s1 == -1){ if (a*x[i]+b*y[i]+c != 0) s1 = i; } else if (a*x[i]+b*y[i]+c != 0){ s2 = i; break; } } } if (s2 == -1){ out.printf(Locale.US, "%.7f", d); out.flush(); return; } double l1 = 0; for (int i=(s1+1)%n; i!=s2; i=(i+1)%n) l1 += Math.sqrt(sqr(x[i+1]-x[i])+sqr(y[i+1]-y[i])); double l2 = 0; for (int i=(s2+1)%n; i!=s1; i=(i+1)%n) l2 += Math.sqrt(sqr(x[i+1]-x[i])+sqr(y[i+1]-y[i])); int aa = y[s1]-y[s1+1], bb = x[s1+1]-x[s1], cc = -(aa*x[s1]+bb*y[s1]); double x0 = -(c*bb-b*cc)*1.0/(a*bb-b*aa); double y0 = -(a*cc-c*aa)*1.0/(a*bb-b*aa); l1 += Math.sqrt(sqr(x0-x[s1+1])+sqr(y0-y[s1+1])); l2 += Math.sqrt(sqr(x0-x[s1])+sqr(y0-y[s1])); aa = y[s2]-y[s2+1]; bb = x[s2+1]-x[s2]; cc = -(aa*x[s2]+bb*y[s2]); double xx0 = -(c*bb-b*cc)*1.0/(a*bb-b*aa); double yy0 = -(a*cc-c*aa)*1.0/(a*bb-b*aa); l2 += Math.sqrt(sqr(xx0-x[s2+1])+sqr(yy0-y[s2+1])); l1 += Math.sqrt(sqr(xx0-x[s2])+sqr(yy0-y[s2])); double d1 = Math.sqrt(sqr(x0-xx0)+sqr(y0-yy0)); double res = d-d1 + Math.min(Math.min(l1, l2), d1*2); out.printf(Locale.US, "%.7f", res); out.flush(); } }
Java
["1 7 6 7\n4\n4 2 4 12 3 12 3 2", "-1 0 2 0\n4\n0 0 1 0 1 1 0 1"]
2 seconds
["6.000000000", "3.000000000"]
null
Java 6
standard input
[ "geometry", "shortest paths" ]
732c0e1026ed385888adde5ec8b764c6
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≀ xStart, yStart, xEnd, yEnd ≀ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≀ n ≀ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≀ x, y ≀ 100), the polygon points will be distinct.
2,400
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
standard output
PASSED
bcc496c5874c57dca746f7a3ca42f7a9
train_002.jsonl
1302706800
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.You can move your ship on the island edge, and it will be considered moving in the sea.Now you have a sea map, and you have to decide what is the minimum cost for your trip.Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { BufferedReader in; StringTokenizer st; PrintWriter out; static class Point { double x, y; public Point(double x, double y) { this.x = x; this.y = y; } } static double sqr(double a) { return a * a; } static double dist(Point p1, Point p2) { return sqrt(sqr(p1.x - p2.x) + sqr(p1.y - p2.y)); } static class Segment { Point p1, p2; double a, b, c; double dist() { return Main.dist(p1, p2); } public Segment(Point p1, Point p2) { this.p1 = p1; this.p2 = p2; make(p1, p2); } void make(Point p1, Point p2) { a = p2.y - p1.y; b = p1.x - p2.x; c = -(p1.x * a + p1.y * b); } boolean cross(Segment s) { double q = a * s.p1.x + b * s.p1.y + c; double w = a * s.p2.x + b * s.p2.y + c; double e = s.a * p1.x + s.b * p1.y + s.c; double r = s.a * p2.x + s.b * p2.y + s.c; q = norm(q); w = norm(w); e = norm(e); r = norm(r); if (q == 0.0) return false; if (q * w <= 0 && e * r <= 0) { if (q == 0 && w == 0 && e == 0 && r == 0) return false; return true; } return false; } Point crossPoint(Segment s) { double st = -a * s.b + s.a * b; double x = (c * s.b - s.c * b) / st; double y = (a * s.c - s.a * c) / st; return new Point(x, y); } } static double norm(double a) { if (a > 0) return 1; if (a < 0) return -1; return 0; } Point start, end; int n; Point[] polygon; Segment[] segms; void solve() throws IOException { start = new Point(ni(), ni()); end = new Point(ni(), ni()); n = ni(); polygon = new Point[n]; for (int i = 0; i < polygon.length; i++) { polygon[i] = new Point(ni(), ni()); } segms = new Segment[n]; double hullLen = 0; for (int i = 0; i < n; ++i) { int j = (i + 1) % n; segms[i] = new Segment(polygon[i], polygon[j]); hullLen += segms[i].dist(); } Segment line = new Segment(start, end); Point p1 = null, p2 = null; int id1 = 0, id2 = 0; for (int i = 0; i < n; ++i) if (line.cross(segms[i])) { if (p1 == null) { p1 = line.crossPoint(segms[i]); id1 = i; } else { p2 = line.crossPoint(segms[i]); id2 = i; } } double ret = 1e+20; if (p1 == null || p2 ==null) { ret = line.dist(); } else { double a = dist(start, p1); double b = dist(start, p2); double c = dist(end, p1); double d = dist(end, p2); double dist = min(a, b) + min(c, d); double d1 = dist(p1, p2) * 2; double d2 = lenClockwise(id1, id2, p1, p2); double d3 = hullLen - lenClockwise(id1, id2, p1, p2); ret = dist + d1; if (dist + d2 < ret) ret = dist + d2; if (dist + d3 < ret) ret = dist + d3; } out.println(ret); } double lenClockwise(int id1, int id2, Point p1, Point p2) { double ret = 0; for (int i = (id1 + 1); i < id2; ++i) ret += segms[i].dist(); ret += dist(segms[id1].p2, p1); ret += dist(segms[id2].p1, p2); return ret; } public Main() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int ni() throws IOException { return Integer.valueOf(ns()); } long nl() throws IOException { return Long.valueOf(ns()); } double nd() throws IOException { return Double.valueOf(ns()); } public static void main(String[] args) throws IOException { new Main(); } }
Java
["1 7 6 7\n4\n4 2 4 12 3 12 3 2", "-1 0 2 0\n4\n0 0 1 0 1 1 0 1"]
2 seconds
["6.000000000", "3.000000000"]
null
Java 6
standard input
[ "geometry", "shortest paths" ]
732c0e1026ed385888adde5ec8b764c6
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≀ xStart, yStart, xEnd, yEnd ≀ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≀ n ≀ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≀ x, y ≀ 100), the polygon points will be distinct.
2,400
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
standard output
PASSED
3559d296cb6beff423e1fa1558d6fe71
train_002.jsonl
1527608100
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Random; import java.util.StringTokenizer; public class Solution{ public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = 1; while(tt-->0) { int n= fs.nextInt(); int[] p = new int[n]; for(int i=0;i<n;i++) { p[i] = fs.nextInt()-1; } int ans = 0; for(int i=0;i<n;i++) { if(p[i]==-1 ) continue; int j = i; while(p[j]!=-1) { int k = j; j = p[j]; p[k] = -1; if(p[j]!=-1) ans++; } } if((n%2==1 && ans%2==1) || (n%2==0 && ans%2==0)) { out.println("Petr"); } else { out.println("Um_nik"); } } out.close(); } static final Random random=new Random(); static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
Java
["5\n2 4 5 1 3"]
2 seconds
["Petr"]
NotePlease note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.Due to randomness of input hacks in this problem are forbidden.
Java 11
standard input
[ "combinatorics", "math" ]
a9cc20ba7d6e31706ab1743bdde97669
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$). In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$Β β€” the permutation of size $$$n$$$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$Β β€” the size of the permutation. Then we randomly choose a method to generate a permutationΒ β€” the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
1,800
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
standard output
PASSED
fb2e65b686158bf495731239160675e2
train_002.jsonl
1527608100
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.
256 megabytes
import java.io.*; import java.util.*; // CODE JAM SHIT public class Q2 { static int find(int x,int[] arr){ if(x==arr[x]) return x; arr[x]=arr[arr[x]]; return find(arr[x],arr); } public static void main(String[] args) { InputReader in = new InputReader(true); PrintWriter out = new PrintWriter(System.out); int N =in.nextInt() ; int arr[]=new int[N]; for(int i =0;i<N;i++) arr[i]=in.nextInt(); int dsu[]=new int[N+1]; for(int i=0;i<dsu.length;i++) dsu[i]=i; for(int i =0;i<N;i++){ int a=arr[i],b=i+1; int x=find(a,dsu),y=find(b,dsu); dsu[x]=y; } // int cnt[]=new int[N+1]; int p=0; for(int i =1;i<=N;i++){ if(dsu[i]!=i){ int val =find(dsu[i],dsu); dsu[i]=val; // cnt[val]++; p++; } } if((p&1)==(N&1)){ out.println("Petr"); }else out.println("Um_nik"); out.close(); } // public static void main(String[] args) { // // InputReader in = new InputReader(); // PrintWriter out = new PrintWriter(System.out); // // int t = in.nextInt(), l = 0; // // while (t-- > 0) { // // out.print("Case #" + (++l) + ": "); // // int N = in.nextInt(), x = in.nextInt(), max = 0; // HashMap<Double, Integer> map = new HashMap<>(); // double arr[] = new double[N]; // // for (int i = 0; i < N; i++) { // arr[i] = in.nextDouble(); // map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); // max = Math.max(max, map.get(arr[i])); // } // // if (max >= x) // out.println(0); // else if (x == 2) // out.println(1); // else { // // int flag = 0; // for (int i = 0; i < N; i++) { // if (arr[i] % 2 == 0) { // if (map.containsKey(arr[i] / 2)) // flag = 1; // } // } // // if (N == 1) // out.println(2); // else if (flag == 1) // out.println(1); // else{ // // double min = Integer.MAX_VALUE; // for (int i = 0; i < N; i++) { // if (map.get(arr[i]) == 2) { // min = Math.min(min, arr[i]); // } // } // // if (min < Integer.MAX_VALUE) { // for (int i = 0; i < N; i++) { // if (arr[i] > min) // flag = 1; // } // } // // if (flag == 1 && max!=1) // out.println(1); // else // out.println(2); // } // } // } // out.close(); // // } static class InputReader { InputStream is; public InputReader(boolean onlineJudge) { is = System.in; } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; 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++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { 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(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); int c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } long[] shuffle(long[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); long c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } long[] uniq(long[] arr) { Arrays.sort(arr); long[] rv = new long[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } int[] reverse(int[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } long[] reverse(long[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } int[] compress(int[] arr) { int n = arr.length; int[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } long[] compress(long[] arr) { int n = arr.length; long[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } void deepFillInt(Object array, int val) { if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof int[]) { int[] intArray = (int[]) array; Arrays.fill(intArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFillInt(obj, val); } } } void deepFillLong(Object array, long val) { if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof long[]) { long[] intArray = (long[]) array; Arrays.fill(intArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFillLong(obj, val); } } } } }
Java
["5\n2 4 5 1 3"]
2 seconds
["Petr"]
NotePlease note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.Due to randomness of input hacks in this problem are forbidden.
Java 11
standard input
[ "combinatorics", "math" ]
a9cc20ba7d6e31706ab1743bdde97669
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$). In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$Β β€” the permutation of size $$$n$$$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$Β β€” the size of the permutation. Then we randomly choose a method to generate a permutationΒ β€” the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
1,800
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
standard output
PASSED
b9bc4f14ef7259d3d1443dd30dbae5ca
train_002.jsonl
1527608100
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.
256 megabytes
import java.io.*; import java.util.*; // CODE JAM SHIT public class Q2 { static void swap(int a ,int b ,int []arr){ int t=arr[a]; arr[a]=arr[b]; arr[b]=t; } public static void main(String[] args) { InputReader in = new InputReader(true); PrintWriter out = new PrintWriter(System.out); int N =in.nextInt() ; int arr[]=new int[N],pos[]=new int[N+1]; for(int i =0;i<N;i++){ arr[i]=in.nextInt(); pos[arr[i]]=i; } int p=0; for(int i =0;i<N;i++){ if(arr[i]!=i+1){ swap(i,pos[i+1],arr); swap(i+1,arr[pos[i+1]],pos); p++; } } if((p&1)==(N&1)){ out.println("Petr"); }else out.println("Um_nik"); out.close(); } // public static void main(String[] args) { // // InputReader in = new InputReader(); // PrintWriter out = new PrintWriter(System.out); // // int t = in.nextInt(), l = 0; // // while (t-- > 0) { // // out.print("Case #" + (++l) + ": "); // // int N = in.nextInt(), x = in.nextInt(), max = 0; // HashMap<Double, Integer> map = new HashMap<>(); // double arr[] = new double[N]; // // for (int i = 0; i < N; i++) { // arr[i] = in.nextDouble(); // map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); // max = Math.max(max, map.get(arr[i])); // } // // if (max >= x) // out.println(0); // else if (x == 2) // out.println(1); // else { // // int flag = 0; // for (int i = 0; i < N; i++) { // if (arr[i] % 2 == 0) { // if (map.containsKey(arr[i] / 2)) // flag = 1; // } // } // // if (N == 1) // out.println(2); // else if (flag == 1) // out.println(1); // else{ // // double min = Integer.MAX_VALUE; // for (int i = 0; i < N; i++) { // if (map.get(arr[i]) == 2) { // min = Math.min(min, arr[i]); // } // } // // if (min < Integer.MAX_VALUE) { // for (int i = 0; i < N; i++) { // if (arr[i] > min) // flag = 1; // } // } // // if (flag == 1 && max!=1) // out.println(1); // else // out.println(2); // } // } // } // out.close(); // // } static class InputReader { InputStream is; public InputReader(boolean onlineJudge) { is = System.in; } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; 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++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { 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(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); int c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } long[] shuffle(long[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); long c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } long[] uniq(long[] arr) { Arrays.sort(arr); long[] rv = new long[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } int[] reverse(int[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } long[] reverse(long[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } int[] compress(int[] arr) { int n = arr.length; int[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } long[] compress(long[] arr) { int n = arr.length; long[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } void deepFillInt(Object array, int val) { if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof int[]) { int[] intArray = (int[]) array; Arrays.fill(intArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFillInt(obj, val); } } } void deepFillLong(Object array, long val) { if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof long[]) { long[] intArray = (long[]) array; Arrays.fill(intArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFillLong(obj, val); } } } } }
Java
["5\n2 4 5 1 3"]
2 seconds
["Petr"]
NotePlease note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.Due to randomness of input hacks in this problem are forbidden.
Java 11
standard input
[ "combinatorics", "math" ]
a9cc20ba7d6e31706ab1743bdde97669
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$). In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$Β β€” the permutation of size $$$n$$$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$Β β€” the size of the permutation. Then we randomly choose a method to generate a permutationΒ β€” the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
1,800
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
standard output
PASSED
482a2f6a63cd27d4496d8154323f2b18
train_002.jsonl
1527608100
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.
256 megabytes
import java.io.*; import java.util.*; public class PetrAndPermutations { private static int mergeAndCount(int[] arr, int l, int m, int r) { // Left subarray int[] left = Arrays.copyOfRange(arr, l, m + 1); // Right subarray int[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l, swaps = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) arr[k++] = left[i++]; else { arr[k++] = right[j++]; swaps += (m + 1) - (l + i); } } // Fill from the rest of the left subarray while (i < left.length) arr[k++] = left[i++]; // Fill from the rest of the right subarray while (j < right.length) arr[k++] = right[j++]; return swaps; } // Merge sort function private static int mergeSortAndCount(int[] arr, int l, int r) { // Keeps track of the inversion count at a // particular node of the recursion tree int count = 0; if (l < r) { int m = (l + r) / 2; // Total inversion count = left subarray count // + right subarray count + merge count // Left subarray count count += mergeSortAndCount(arr, l, m); // Right subarray count count += mergeSortAndCount(arr, m + 1, r); // Merge count count += mergeAndCount(arr, l, m, r); } return count; } public static void main(String[] args) throws Exception { BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int n = Integer.parseInt(buffer.readLine()); String [] inp = buffer.readLine().split(" "); int [] arr = new int[n]; for (int pos = 0; pos < n; pos++) { arr[pos] = Integer.parseInt(inp[pos]); } int inversions = 3*n-mergeSortAndCount(arr, 0, arr.length - 1); if (inversions%2==0) System.out.println("Petr"); else System.out.println("Um_nik"); } }
Java
["5\n2 4 5 1 3"]
2 seconds
["Petr"]
NotePlease note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.Due to randomness of input hacks in this problem are forbidden.
Java 11
standard input
[ "combinatorics", "math" ]
a9cc20ba7d6e31706ab1743bdde97669
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$). In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$Β β€” the permutation of size $$$n$$$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$Β β€” the size of the permutation. Then we randomly choose a method to generate a permutationΒ β€” the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
1,800
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
standard output
PASSED
39a0a9b95fce12498624e8349693f623
train_002.jsonl
1527608100
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.
256 megabytes
import java.io.*; import java.util.*; public class PetrAndPermutations { public static void main(String[] args) throws Exception { BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int n = Integer.parseInt(buffer.readLine()); String [] inp = buffer.readLine().split(" "); int [] valueArr = new int[n]; int [] indexArr = new int[n+1]; for (int pos = 0; pos < n; pos++) { valueArr[pos] = pos+1; indexArr[pos+1] = pos; } int inversions = 0; for (int pos = 0; pos < n; pos++) { int num = Integer.parseInt(inp[pos]); if (valueArr[pos]!=num){ int i = indexArr[num]; valueArr[i] = valueArr[i]^ valueArr[pos]^(valueArr[pos]=valueArr[i]); indexArr[num] = pos; indexArr[valueArr[i]] = i; inversions++; } } inversions = 3*n-inversions; if (inversions%2==0) System.out.println("Petr"); else System.out.println("Um_nik"); } }
Java
["5\n2 4 5 1 3"]
2 seconds
["Petr"]
NotePlease note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.Due to randomness of input hacks in this problem are forbidden.
Java 11
standard input
[ "combinatorics", "math" ]
a9cc20ba7d6e31706ab1743bdde97669
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$). In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$Β β€” the permutation of size $$$n$$$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$Β β€” the size of the permutation. Then we randomly choose a method to generate a permutationΒ β€” the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
1,800
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
standard output
PASSED
e92390773cd2c8119976ae5a6c9ce66b
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1351a { public static void main(String[] args) throws IOException { int t = ri(); while(t --> 0) { int a = rni(), b = ni(); prln(a + b); } close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void sort(int[] a) {shuffle(a); Arrays.sort(a);} static void sort(long[] a) {shuffle(a); Arrays.sort(a);} static void sort(double[] a) {shuffle(a); Arrays.sort(a);} static void qsort(int[] a) {Arrays.sort(a);} static void qsort(long[] a) {Arrays.sort(a);} static void qsort(double[] a) {Arrays.sort(a);} static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
111c48c9b8c3dbfef67c9755098d1d15
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; // Give me a scanner and easy access to most everything else import static java.lang.System.*; //shorten printing public class AdditionalProblem { //global variables public static void main (String[] args) { //Code will begin here Scanner in = new Scanner(System.in); int numCases = in.nextInt(); for (int t=0; t<numCases; t++) { int a = in.nextInt(); int b = in.nextInt(); out.println(a+b); } } //functions }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
b1732a2500dc99416e0bd33ce96872e1
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; import static java.lang.System.*; public class AddingProblem { public static void main(String[] args) { Scanner in = new Scanner(System.in); int numCases = in.nextInt(); for (int t=0; t<numCases; t++) { int a = in.nextInt(); int b = in.nextInt(); out.println(a + b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
17293aecb8f638a6b5e7ff1c098c381b
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.Scanner; public class trialproblem { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t-->0) { int a = scn.nextInt(); int b = scn.nextInt(); int sum = a+b; System.out.println(sum); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
f930442ba935dc74bf581891a027a93c
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; import java.util.regex.*; public class Tringle { public static void main(String args[]) { Scanner scan=new Scanner(System.in); int t=Integer.parseInt(scan.nextLine()); while(t-->0) { long x=scan.nextInt(); long y=scan.nextInt(); System.out.println(x+y); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
5d84c804a1aed07e2517076f52f17acf
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t; t=sc.nextInt(); ArrayList<Long> a=new ArrayList<Long>(); ArrayList<Long> b=new ArrayList<Long>(); ArrayList<Long> c=new ArrayList<Long>(); for(int i=0;i<t;i++) { a.add(Long.parseLong(sc.next())); b.add(Long.parseLong(sc.next())); c.add(a.get(i)+b.get(i)); } for(long i : c) System.out.println(i); } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
00ecf8a841d4b1bdd7b89aec8b7bd063
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class GFG { public static void main (String[] args) { Scanner sc=new Scanner(System.in); long t; t=sc.nextLong(); long x[][]=new long[(int)t][2]; for(int i=0;i<t;i++) { for(int j=0;j<2;j++) x[i][j]=sc.nextLong(); } for(int i=0;i<t;i++) { long c=0; for(int j=0;j<2;j++) { c+=x[i][j]; } System.out.println(c); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
1924a76513e60d841242ec072ebb7eaa
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class MyClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int j=0; j<t; j++) { short a = sc.nextShort(); short b = sc.nextShort(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
c048d6630663aa1c50824e55d9b7d99c
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; import static java.lang.Math.*; public class Demo{ public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t-->0){ int a = in.nextInt(); int b = in.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
25fd04d0531563488ddc1dc2d7a0adf6
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.Scanner; public class Solution{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int test=sc.nextInt(); for(int t=0;t<test;t++){ int a=sc.nextInt(); int b=sc.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
d25c1eafc0be8af29f2431bb5ef9dc51
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; import java.io.*; import java.math.*; public class Main{ 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){ long a = sc.nextLong(); long b = sc.nextLong(); System.out.println(a+b); } } public static class pair{ int x; int y; } public static class comp implements Comparator<pair>{ public int compare(pair o1, pair o2){ if(o1.x==o2.x){ return o1.y-o2.y; } return o1.x-o2.x; } } static HashMap<Integer,Integer> visited = new HashMap<>(); static class Node{ int node; int d; ArrayList<Integer> al = new ArrayList<>(); } static long gcd(long a, long 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
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
66c455e6fbfa4e324443f58ee7110cb9
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class trial { public static void main(String[] args) { { int a,b,sum; Scanner sc= new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { a=sc.nextInt(); b=sc.nextInt(); sum=a+b; System.out.println(sum); sum=0; } } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
3171c0b5e9dceb8f363a23e27e3ba88f
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.Scanner; public class simplesum { public static void main(String[] args) { Scanner as=new Scanner(System.in); int n=as.nextInt(); for (int i=0;i<n;i++) { int a=as.nextInt(); int b=as.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
73d47f87631358f6d13b2cc9213c3c38
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader bf= new BufferedReader(new InputStreamReader(System.in)); int cases= Integer.parseInt(bf.readLine()); for(int i=0;i<cases;i++) { StringTokenizer st = new StringTokenizer(bf.readLine()); int a = Integer.parseInt(st.nextToken()); int b=Integer.parseInt(st.nextToken()); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
c0980c432226ed9f80833c738cf9b3e9
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
//package firsttest; import java.util.Date; import java.util.Scanner; /** * * @author Asad Bin Saber * @date 12 05 2020 */ public class Main{ /** * @param args the command line arguments */ static Scanner sc=new Scanner(System.in); public static void main(String[] args) { // TODO code application logic here // Integers, doubles are base... int n, a, b, i; n = sc.nextInt(); for(i=1; i<=n; i++){ a = sc.nextInt(); b = sc.nextInt(); System.out.println(a + b + "\n"); } //System.out.println("May I know your name?\n"); //String name = sc.nextLine(); //System.out.println("Hello " + name); } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
02d31ebe3ec22c4b12134413dcc13c31
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.Scanner; public class HelloWorld { public static void main(String[] args) { //Scanner in=new Scanner(System.in); //int a = in.nextInt();// //System.out.println("enter an integer" +a);// //for(int i=0;i<a;i++) { // //int b=in.nextInt();// //System.out.println("enter an integer" +b);// //in.close(); //System.out.println(a+b);// Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t!=0){ int a=sc.nextInt(); int b=sc.nextInt(); System.out.println(a+b); t--;} sc.close();}} //Scanner scanner = new Scanner(System.in); //Scanner in=new Scanner(System.in);
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
8b5709f67c154ce1424bc6300d01b001
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; public class Main { public static void main(String[] args) { BufferedReader x=new BufferedReader(new InputStreamReader(System.in)); try{ String n1=x.readLine(); int n=Integer.parseInt(n1); int ans[]=new int[n]; for(int i=0;i<n;i++){ String question[]=x.readLine().split(" "); ans[i]=Integer.parseInt(question[0])+Integer.parseInt(question[1]); } for(int i=0;i<n;i++){ System.out.println(ans[i]); } } catch (Exception e) { e.printStackTrace(); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
3179c3b197719f866b13b60de380a481
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Codeforces_1351A { public static void main(String args[]) { Scanner input = new Scanner(System.in); int num_cases = input.nextInt(); for (int i = 0; i < num_cases; i++) { int a = input.nextInt(); int b = input.nextInt(); System.out.println(a + b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
7794c060fb70e03a8f04a70ff5e59cd8
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.io.*; import java.util.*; // Author- Prashant Gupta public class A { public static void main(String[] args) throws IOException { // write your code here PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); // Scanner sc = new Scanner(System.in); Reader sc = new Reader(); int t = sc.nextInt(); while (t-- > 0) { int a = sc.nextInt(); int b = sc.nextInt(); out.println(a + b); } out.close(); } /*-------------------------------------------------------------------------------------*/ public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long power(long x, long y) { long res = 1; while (x > 0) { if (y % 2 == 0) { x *= x; y /= 2; } else { res *= x; y--; } } return res; } public static long lcm(long x, long y) { return (x * y) / gcd(x, y); } public static int lowerBound(Vector<Integer> v, int e) { int start = 0, end = v.size() - 1, ind = 0; while (start <= end) { int mid = (start + end) / 2; if (v.get(mid) == e) { ind = mid + 1; break; } else if (v.get(mid) < e) { ind = mid + 1; start = mid + 1; } else { end = mid - 1; } } return ind; } // Fast I/p static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { 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
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
6dca0e54a51c771d5d6919d2c0ce9f67
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.io.*; import java.util.*; public class solution { static class sort implements Comparator<ArrayList<Integer>> { @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { int c = o2.get(1).compareTo(o1.get(1)); if (c == 0) { c = o2.get(0).compareTo(o1.get(0)); } return c; } } public static void merge(long arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; long L[] = new long[n1]; long R[] = new long[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void sort(long arr[], int l, int r) { if (l < r) { int m = (l + r) / 2; sort(arr, l, m); sort(arr, m + 1, r); merge(arr, l, m, r); } } public static long gcd(long a, long b) { if (b == 0) { return a; } else return gcd(b, a % b); } public static long lcm(long a, long b) { long gcd = gcd(a, b); long pord = a * b; return pord / gcd; } static class graphs { private int V; private ArrayList<Integer> adj[]; graphs(int v) { V = v; adj = new ArrayList[v]; for (int i = 0; i < v; i++) { adj[i] = new ArrayList<>(); } } void addedge(int u, int v) { adj[u].add(v); } void BFS(int v) { boolean visited[] = new boolean[V]; Queue<Integer> Q = new LinkedList<>(); visited[v] = true; Q.add(v); while (!Q.isEmpty()) { int temp = Q.peek(); System.out.print(temp + " "); Q.remove(); Iterator<Integer> it = adj[temp].listIterator(); while (it.hasNext()) { int n = it.next(); if (!visited[n]) { visited[n] = true; Q.add(n); } } } } void DFSUtil(int v, boolean visited[]) { visited[v] = true; System.out.print(v + " "); Iterator<Integer> it = adj[v].listIterator(); while (it.hasNext()) { int n = it.next(); if (!visited[n]) { DFSUtil(n, visited); } } } void DFS(int v) { boolean visited[] = new boolean[V]; DFSUtil(v, visited); } } public static int Binaraysearch(long a[], int low, int high, long key) { while (low <= high) { int mid = low + (high - low) / 2; if (a[mid] == key) { return mid; } else if (a[mid] < key) { low = mid; } else { high = mid; } } return -1; } public static void seive(boolean prime[]) { Arrays.fill(prime, true); int n = prime.length - 1; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } } public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for(int ii=0;ii<t;ii++){ StringTokenizer st = new StringTokenizer(br.readLine()); long a = Long.parseLong(st.nextToken()); long b = Long.parseLong(st.nextToken()); long ans = a+b; System.out.println(ans); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
07dfc2a2f964deb2185cfa9e1f6c54d6
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.Scanner; public class practice{ static public void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while((t--)>0) { System.out.println(sc.nextInt()+sc.nextInt()); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
20373da0b1f34bdb1c88a522532986db
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Main { public static void main(String args[]) { Scanner s=new Scanner(System.in); int t; t=s.nextInt(); for(int i=0;i<t;i++) { int a,b; a=s.nextInt(); b=s.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
8f0d0586b28ac0c079a4e64c99071b4c
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.io.PrintStream; import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintStream pw = new PrintStream(System.out); long t = in.nextLong(); while (t-- > 0) { int s = in.nextInt(),r = in.nextInt(); pw.println(s+r); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
d2343ca65c666a612ca522cd1dc8e9e8
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.Scanner; public class Add { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t--!=0) { int a=sc.nextInt(); int b=sc.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
c9f05a37b8c8b9bc2f40fbc819d78879
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); int cases = scan.nextInt(); for (int i = 0; i < cases; i++) { int a = scan.nextInt(); int b = scan.nextInt(); System.out.println(a + b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
38687b3ba919f06e22d27c7035153e49
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.Scanner; public class Problem3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); int[] a = new int[t]; int[] b = new int[t]; int[] total = new int[t]; for(int i=0;i<t;i++) { a[i] = in.nextInt(); b[i] = in.nextInt(); total[i] = a[i]+b[i]; } in.close(); for(int i=0;i<t;i++) { System.out.println(total[i]); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output
PASSED
218b9b2734c612a2b0168a30782b97fe
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class AB { public static void main(String[] args) { Scanner input = new Scanner(System.in); int i = input.nextInt(); for (int j = 0; j < i; j++) { int a = input.nextInt(); int b = input.nextInt(); System.out.println(a + b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers β€” the required numbers $$$a+b$$$.
standard output