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 | c9c12a45536ab5e74264261b192f7f06 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
new A().solve();
}
Scanner in;
private void solve() {
in = new Scanner(System.in);
int t = in.nextInt();
while (t-- > 0) {
boolean red = false;
boolean blue = false;
boolean green = false;
boolean failed = false;
String[] keysAnsDoors = in.next().split("");
for (String keyOrDoor : keysAnsDoors) {
if (keyOrDoor.equals("r")) {
red = true;
continue;
}
if (keyOrDoor.equals("b")) {
blue = true;
continue;
}
if (keyOrDoor.equals("g")) {
green = true;
continue;
}
if (keyOrDoor.equals("R") && !red
|| keyOrDoor.equals("B") && !blue
|| keyOrDoor.equals("G") && !green) {
failed = true;
}
}
System.out.println(failed ? "NO" : "YES");
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 384831b9b0fd7abc884b3ae9321500d9 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Arrays;
public class Cv {
//==========================Solution============================//
public static void main(String[] args) {
FastScanner in = new FastScanner();
Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = input.nextInt();
while (t-- > 0) {
String s = input.next();
int r = 0;
int g = 0;
int b = 0;
boolean q = true;
for (int i = 0; i < 6; i++) {
char c = s.charAt(i);
if (c == 'r') {
r++;
}
if (c == 'g') {
g++;
}
if (c == 'b') {
b++;
}
if (c == 'R') {
if (r == 0) {
q = false;
break;
}
}
if (c == 'G') {
if (g == 0) {
q = false;
break;
}
}
if (c == 'B') {
if (b == 0) {
q = false;
break;
}
}
}
if (q) {
out.println("YES");
} else {
out.println("NO");
}
}
out.close();
}
//==============================================================//
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() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
byte nextByte() {
return Byte.parseByte(next());
}
short nextShort() {
return Short.parseShort(next());
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return java.lang.Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | cb0df3d0304b171b75e18643fb8ed0da | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | /*
I am dead inside
Do you like NCT, sKz, BTS?
5 4 3 2 1 Moonwalk
Imma knock it down like domino
Is this what you want? Is this what you want?
Let's ttalkbocky about that :()
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
public class x1644A
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
while(T-->0)
{
st = new StringTokenizer(infile.readLine());
char[] arr = st.nextToken().toCharArray();
int[] loc = new int[500];
for(int i=0; i < 6; i++)
loc[arr[i]] = i;
String res = "YES";
if(loc['R'] < loc['r'] || loc['B'] < loc['b'] || loc['G'] < loc['g'])
res = "NO";
sb.append(res+"\n");
}
System.out.print(sb);
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 1de9495fd9368068b61ac6ff06f1a8eb | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
public class solution{
public static void main(String[] args) throws java.lang.Exception{
Scanner scan = new Scanner(System.in);
int t;
t=scan.nextInt();
while(t-->0){
String s = scan.next();
if (s.indexOf('B')>s.indexOf('b')&&s.indexOf('G')>s.indexOf('g')&&s.indexOf('R')>s.indexOf('r')){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 0dfab85348171c5a855df72ceb0a1bc6 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Arrays;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
for(int i = 0; i < T; i++) {
String S = scan.next();
char[] ch = S.toCharArray();
int r = 0;
int g = 0;
int b = 0;
int R = 0;
int G = 0;
int B = 0;
for(int j = 0; j < ch.length; j++) {
if(ch[j] == 'r') {
r = j;
}
if(ch[j] == 'g') {
g = j;
}
if(ch[j] == 'b') {
b = j;
}
if(ch[j] == 'R') {
R = j;
}
if(ch[j] == 'G') {
G = j;
}
if(ch[j] == 'B') {
B = j;
}
}
if(r<R && g<G && b<B) {
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 28270a32fed9bcbf6ee3b36d83773f7d | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.Scanner;
public class A1644 {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
int cases=sc.nextInt();
for(int i=0;i<cases;i++){
String st=sc.next();
if(st.indexOf('r')<st.indexOf('R') & st.indexOf('b')<st.indexOf('B') & st.indexOf('g')<st.indexOf('G')){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | b348250d12d6df6e0d139c867eb6d73e | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
public class DoorsAndKeys {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int a= Integer.parseInt(sc.nextLine());
for(int i=0; i<a; i++) {
String string = sc.nextLine();
String output = canKnightOpenAllDoors(string);
System.out.println(output);
}
sc.close();
}
private static String canKnightOpenAllDoors(String string) {
char[] charArray = string.toCharArray();
HashSet<Character> set = new HashSet<>();
for(int i=0; i<charArray.length; i++) {
if(charArray[i]=='r' || charArray[i]=='g' || charArray[i]=='b') {
set.add(charArray[i]);
}
if(charArray[i]=='R' || charArray[i]=='G' || charArray[i]=='B') {
char charLowerCase = Character.toLowerCase(charArray[i]);
if(!set.contains(charLowerCase)) {
return "NO";
}
}
}
return "YES";
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 8c4ca31c708184627f3c484772b8732c | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
try {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-- > 0) {
String s=sc.next();
if((s.indexOf('r') < s.indexOf('R')) && (s.indexOf('b') < s.indexOf('B')) && (s.indexOf('g') < s.indexOf('G'))) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
} catch(Exception e) {
}
// your code goes here
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 29bcb6be3ee6559a5cedce4eb3624682 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
String str = sc.next();
int n = str.length();
int c=0;
int r=0;
int g=0;
int b=0;
for(int i=0; i<n; i++){
if(str.charAt(i)=='r'){
r++;
}
if(str.charAt(i)=='g'){
g++;
}
if(str.charAt(i)=='b'){
b++;
}
if(str.charAt(i)=='R' && r==0){
c++;
}
if(str.charAt(i)=='G' && g==0){
c++;
}
if(str.charAt(i)=='B' && b==0){
c++;
}
}
if(c>0){
System.out.println("NO");
}else{
System.out.println("YES");
}
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 72eab00eb3d2fd3415236461684ddefc | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Roy
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
ADoorsAndKeys solver = new ADoorsAndKeys();
solver.solve(1, in, out);
out.close();
}
static class ADoorsAndKeys {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int tCases = in.readInteger();
for (int cs = 1; cs <= tCases; ++cs) {
String hallway = in.readString();
int ln = hallway.length();
boolean possible = true;
boolean redKey = false, blueKey = false, greenKey = false;
for (int i = 0; i < ln && possible; i++) {
char c = hallway.charAt(i);
if (c == 'r') redKey = true;
else if (c == 'g') greenKey = true;
else if (c == 'b') blueKey = true;
else if (c == 'R' && !redKey) possible = false;
else if (c == 'G' && !greenKey) possible = false;
else if (c == 'B' && !blueKey) possible = false;
}
if (possible) out.printLine("YES");
else out.printLine("NO");
}
}
}
static class InputReader {
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
private final InputStream stream;
private final byte[] buf = new byte[1024];
public InputReader(InputStream stream) {
this.stream = stream;
}
private long readWholeNumber(int c) {
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInteger() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = (int) readWholeNumber(c);
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
this.print(objects);
writer.println();
}
public void close() {
writer.flush();
writer.close();
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 816ebd32240dcb978a65cd550c21a3e4 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static void main (String[] args) throws java.lang.Exception
{
FastReader sc=new FastReader();
FastWriter out=new FastWriter();
int t=sc.nextInt();
while(t-->0)
{
String s=sc.nextLine();
boolean r=false,g=false,b=false,flag=false;
for(int i=0;i<6;i++)
{ char ch=s.charAt(i);
if(ch=='r')
r=true;
if(ch=='g')
g=true;
if(ch=='b')
b=true;
else
{
if(ch=='R' && !r)
flag=true;
if(ch=='B' && !b)
flag=true;
if(ch=='G' && !g)
flag=true;
}
}
if(flag)
System.out.println("NO");
else
System.out.println("YES");
}
out.close();
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | cf7f61e597025cdaeae180cacad8bdf2 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.Scanner;
public class A1644 {
public static void main(String[] args) {
char[] keys = new char[] {'r', 'g', 'b'};
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for (int t=0; t<T; t++) {
String S = in.next();
boolean possible = true;
for (char key : keys) {
char door = Character.toUpperCase(key);
if (S.indexOf(key) > S.indexOf(door)) {
possible = false;
break;
}
}
System.out.println(possible ? "YES" : "NO");
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | fb85e3646748cd68ac7a8c480e4022e8 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes |
import java.util.*;
import java.lang.Math.*;
public class Inheritance{
static int highestPowerOf2(int n)
{
return (n & (~(n - 1)));
}
public static void main(String[] args){
Scanner s=new Scanner(System.in);
int t=s.nextInt();
while(t-->0)
{
String s1=s.next();
int arr[]=new int[3];
int flag=1;
for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)=='r')
arr[0]=1;
if(s1.charAt(i)=='g')
arr[1]=1;
if(s1.charAt(i)=='b')
arr[2]=1;
if(s1.charAt(i)=='R' && arr[0]!=1)
{
flag=0;
System.out.println("NO");
break;
}
if(s1.charAt(i)=='G' && arr[1]!=1)
{
flag=0;
System.out.println("NO");
break;
}
if(s1.charAt(i)=='B' && arr[2]!=1)
{
flag=0;
System.out.println("NO");
break;
}
}
if(flag==1)
System.out.println("YES");
}
// for(int i=0;i<n;i++)
// {
// int ans1=32768-arr[i];
// int ans2=0;
// if(arr[i]%2==0)
// {
// int count=0;
// int i1=arr[i];
// while(i1%2==0)
// {
// count++;
// i1=i1/2;
// }
// ans2=15-count;
// }
// else
// {
// int count=0;
// int i1=arr[i]+1;
// while(i1%2==0)
// {
// count++;
// i1=i1/2;
// }
// //System.out.println(count);
// ans2=15-count+1;
// }
// System.out.print(Math.min(ans2, ans1)+" ");
// }
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 1268bbbfe189c5403c9ee26f855b99f2 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | /*package whatever //do not write package name here */
import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
String s = sc.next();
int r=0,g=0,b=0;
boolean f=true;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='r') r++;
else if(s.charAt(i)=='g') g++;
else if(s.charAt(i)=='b') b++;
else if(s.charAt(i)=='R' && r==0){
f = false;
break;
}else if(s.charAt(i)=='G' && g==0){
f = false;
break;
}else if(s.charAt(i)=='B' && b==0){
f = false;
break;
}
}
if(f) System.out.println("YES");
else System.out.println("NO");
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 7c9336b82614a4519b3e705dc20dea00 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
public class test {
public static void main(String[] args) {
Scanner inputul = new Scanner(System.in);
long t = inputul.nextInt();
for (int i = 0; i < t; i++) {
String text = inputul.next();
int r_ind = text.indexOf("r");
int g_ind = text.indexOf("g");
int b_ind = text.indexOf("b");
int R_ind = text.indexOf("R");
int G_ind = text.indexOf("G");
int B_ind = text.indexOf("B");
if(r_ind<R_ind && g_ind<G_ind && b_ind<B_ind) System.out.println("YES");
else System.out.println("NO");
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | b150d6286761f14ea99a978d8e93a195 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import javafx.scene.layout.Priority;
public class Main
{
public static void main(String args[])
{
FastScanner input = new FastScanner();
int tc = input.nextInt();
work:
while (tc-- > 0) {
char a[] = input.next().toCharArray();
TreeSet<Character> small = new TreeSet<>();
for (int i = 0; i <a.length; i++) {
if(a[i]>='a'&&a[i]<='z')
{
small.add(a[i]);
}
else
{
char c = (char)(a[i]+32);
if(!small.contains(c))
{
System.out.println("NO");
continue work;
}
}
}
System.out.println("YES");
}
}
static class FastScanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next()
{
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine() throws IOException
{
return br.readLine();
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | f1199a9a4600a0956a74a9b5d98ba76a | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
public class DoorsAndKeys {
public static boolean yesOrNo(String s){
HashMap<Character,Integer>hashMap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if(Character.isLowerCase(s.charAt(i))){
hashMap.put(s.charAt(i),1);
}
else {
if(hashMap.getOrDefault(Character.toLowerCase(s.charAt(i)),0) == 0){
return false;
}
}
}
return true;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
for (int i = 0; i < t; i++) {
String s = input.next();
if(yesOrNo(s)){
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 03f08cb9751eadb353ea1f89eba3bb5f | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.*;
public class test2 {
/*static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}*/
public static long[] merge(long[] x,long[] y) {
long[] r=new long[x.length+y.length];
int i=0;int j=0;
int k=0;
while(i<x.length||j<y.length) {
if(i>=x.length) {
r[k]=y[j];
j++;
}
else if(j>=y.length) {
r[k]=x[i];
i++;
}
else {
if(x[i]>y[j]) {
r[k]=y[j];
j++;
}
else {
r[k]=x[i];
i++;
}
}
k++;
}
return r;
}
public static boolean sorted(long[] x) {
for(int i=0;i<x.length-1;i++) {
if(x[i]>x[i+1])return false;
}
return true;
}
public static void mergesort(long[] x) {
if(!sorted(x)) {
int mid=x.length/2;
long[] p1=new long[mid];
long[] p2=new long[x.length-mid];
for(int i=0;i<p1.length;i++)p1[i]=x[i];
//System.out.println(Arrays.toString(p1));
int k=0;
for(int i=mid;i<x.length;i++) {
p2[k]=x[i];
k++;
}
// c++;
//System.out.println(c);
//System.out.println(Arrays.toString(p2));
mergesort(p1);
mergesort(p2);
long[] r=merge(p1,p2);
for(int i=0;i<r.length;i++)x[i]=r[i];
}
//{1,2,3,4,5,6,8}
}
public static int abs(int x) {
if(x<0)x=-1*x;
return x;
}
public static String rev(String s) {
String r="";
for(int i=0;i<s.length();i++)r=s.charAt(i)+r;
return r;
}
public static void generate(int n,String r) {
if(n==0) {
System.out.println(r);
return;
}
for(char i='a';i<='z';i++) {
generate(n-1, r+i);
}
}
public static boolean acc(int[] x,int i,int c) {
if(c==23)return true;
else {
if(i==x.length)return false;
else{
if(i==0) {
return acc(x,i+1,c+x[i]);
}
else {
return acc(x,i+1,c+x[i])||acc(x,i+1,c-x[i])||acc(x,i+1,c*x[i]);
}
}
}
}
public static int val(char c) {
if(c=='+')return 0;
if(c=='-')return 1;
else return 2;
}
/*public static int evaluate(String s) {
Stack<Integer> x=new Stack<Integer>();
Stack<Character> y=new Stack<Character>();
for(int i=0;i<s.length();i++) {
}
}*/
public static boolean sum(int[] x,int i,int c,boolean[] take) {
//System.out.println(c);
//if(i==5&&c==23)System.out.println(c);
if(i==x.length&&c==23) {
//System.out.println(s);
return true;
}
else if(i==x.length)return false;
else{
boolean ret=false;
for(int j=0;j<5;j++) {
if(!take[j]) {
take[j]=true;
if(i==0) {
ret|=sum(x,i+1,c+x[j],take);
}
else {
ret|=sum(x,i+1,c+x[j],take)||sum(x,i+1,c-x[j],take)||sum(x,i+1,c*x[j],take);
}
take[j]=false;
}
}
return ret;
}
}
public static void genSum(int[] x,int i,String s,int sum,int t,Stack<String> q) {
if(i==x.length&&sum==t) {
//System.out.println(s);
q.push(s);
return;
}
else if(i==x.length)return;
else {
if(s.isEmpty()) {
genSum(x, i+1, s+x[i], sum+x[i], t, q);
genSum(x, i+1, s, sum, t, q);
}
else {
genSum(x, i+1, s+"+"+x[i], sum+x[i], t, q);
genSum(x, i+1, s, sum, t, q);
}
}
}
public static int count(int[] x,int i,int s,int c,String st) {
if(i==x.length) {
if(c==s) {
System.out.println(st);
return 1;
}
else return 0;
}
if(st!="")
return count(x,i+1,s,c+x[i],st+" "+x[i])+count(x,i+1,s,c,st);
else {
return count(x,i+1,s,c+x[i],st+""+x[i])+count(x,i+1,s,c,st);
}
}
public static void perm(int[] x,boolean[] t,int i,String s,int c) {
if(i==x.length) {
if(c==x.length)
System.out.println(s);
return;
}
for(int j=0;j<x.length;j++) {
if(!t[j]) {
t[j]=true;
perm(x,t,i+1,s+x[j]+" ",c+1);
t[j]=false;
}
}
}
public static void dev(int i,String s,Stack<Integer> q,boolean[] take) {
if(s.length()==5) {
//System.out.println(s);
q.push(Integer.parseInt(s));
return;
}
for(int j=0;j<10;j++) {
//System.out.println("k");
if(!take[j]) {
take[j]=true;
dev(i+1,s+""+j,q,take);
take[j]=false;
}
}
}
public static void circ(int[] x,int i,String s,HashSet<Integer> y,int prev,boolean[] t,int c,Queue<String> q) {
if(i==x.length) {
if(c==x.length&&y.contains(prev+1))
q.add(s);
return;
}
for(int j=1;j<x.length;j++) {
if(!t[j]) {
if(y.contains(prev+x[j])) {
t[j]=true;
circ(x,i+1,s+" "+x[j],y,x[j],t,c+1,q);
}
t[j]=false;
}
}
}
public static boolean isPrim(int x) {
boolean r=true;
for(int i=2;i<x;i++) {
if(x%i==0)return false;
}
return true;
}
public static boolean check(String s) {
for(int i=0;i<s.length()-1;i++) {
if(s.charAt(i)=='t') {
if(s.charAt(i+1)=='t')return false;
}
}
return true;
}
public static void quiz(char[] y,int c,boolean[] take,HashSet<String> x,int i,String s) {
if(i==y.length) {
if(check(s)) {
x.add(s);
}
return;
}
for(int j=0;j<y.length;j++) {
if(!take[j]) {
take[j]=true;
quiz(y, c+1, take, x, i+1, s+""+y[j]);
take[j]=false;
}
}
}
public static void del(String a,String b,int c,HashSet<Integer>x) {
if(a.equals(b)) {
x.add(c);
return;
}
else if(a.isEmpty()||b.isEmpty())return;
else {
String r1="";
for(int i=1;i<a.length();i++)r1+=a.charAt(i);
del(r1,b,c+1,x);
r1="";
for(int i=0;i<a.length()-1;i++)r1+=a.charAt(i);
del(r1,b,c+1,x);
r1="";
for(int i=1;i<b.length();i++)r1+=b.charAt(i);
del(a,r1,c+1,x);
r1="";
for(int i=0;i<b.length()-1;i++)r1+=b.charAt(i);
del(a,r1,c+1,x);
}
}
public static long power3(long x) {
return x*x*x;
}
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter sp=new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0) {
String s=sc.next();
boolean r=false;boolean b=false;
boolean g=false;
boolean f=true;
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='r')r=true;
else if(s.charAt(i)=='b')b=true;
else if(s.charAt(i)=='g')g=true;
else {
if(s.charAt(i)=='R') {
if(!r) {
f=false;
break;
}
}
else if(s.charAt(i)=='G') {
if(!g) {
f=false;
break;
}
}
else if(s.charAt(i)=='B') {
if(!b) {
f=false;
break;
}
}
}
}
if(f)sp.println("YES");
else sp.println("NO");
}
sp.flush();
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 331b66e96b7bb20aaebbf6af421d062d | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.Scanner;
public class Problem_1644A {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
boolean hasR, hasG, hasB, isSuccess;
for (int i = 0; i < t; i++) {
hasR = false;
hasG = false;
hasB = false;
isSuccess = true;
char[] digits = scanner.next().toCharArray();
for (char digit: digits) {
switch (digit) {
case 'r':
hasR = true;
break;
case 'g':
hasG = true;
break;
case 'b':
hasB = true;
break;
case 'R':
if (!hasR) {
isSuccess = false;
}
break;
case 'G':
if (!hasG) {
isSuccess = false;
}
break;
case 'B':
if (!hasB) {
isSuccess = false;
}
break;
}
}
if (isSuccess) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 1bcafdfe6500e063a903dc7cfb96b017 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.Scanner;
/**
*
* <a href = "https://codeforces.com/problemset/problem/1644/A"> Link </a>.
* @author Bris
* @version 1.0
* @since 8:32:51 PM - Mar 31, 2022
*/
public class A1644 {
/**
* The main method.
* @param args Unused.
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-->0) {
String s = scanner.next();
boolean hasR = false;
boolean hasG = false;
boolean hasB = false;
String ans = "YES";
for (int i = 0; i < 6; i++) {
char ch = s.charAt(i);
switch (ch) {
case 'R':
if (!hasR) {
ans = "NO";
}
break;
case 'G':
if (!hasG) {
ans = "NO";
}
break;
case 'B':
if (!hasB) {
ans = "NO";
}
break;
case 'r':
hasR = true;
break;
case 'g':
hasG = true;
break;
case 'b':
hasB = true;
break;
}
}
System.out.println(ans);
}
scanner.close();
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 215c8e3bb13811905c63759431d43352 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
public class doorsAndKeys
{
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String s[]=new String[n];
for(int i=0;i<n;i++)
{
s[i]=sc.next();
}
sc.close();
int arr[]=new int[3];
Arrays.fill(arr,9);
for(int i=0;i<n;i++)
{
String str=s[i];
for(int j=0;j<str.length();j++)
{
if(str.charAt(j)=='r') arr[0]=j;
else if(str.charAt(j)=='g') arr[1]=j;
else if(str.charAt(j)=='b') arr[2]=j;
}
int flag=0;
for(int k=0;k<str.length();k++)
{
if(str.charAt(k)=='R'&&arr[0]<k) flag++;
else if(str.charAt(k)=='G'&& arr[1]<k) flag++;
else if(str.charAt(k)=='B'&&arr[2]<k) flag++;
}
if(flag==3) System.out.println("YES");
else System.out.println("NO");
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | e75ac5231b0a43c58021ee85c1dc45a5 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader(){
try {br = new BufferedReader(
new FileReader("input.txt"));
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);}
catch(Exception e){ 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) {
int i;
FastReader read = new FastReader();
int n =read.nextInt();
for(i=0;i<n;i++){
String door =read.next();
System.out.println(key(door));
}
}
static String key(String door){
int i;
int check =0;
for(i=0;i<door.length();i++){
for(int j =i-1;j>=0;j--){
if(door.charAt(j)=='r' && door.charAt(i)=='R'){
check++;
}
if(door.charAt(j)=='g' && door.charAt(i)=='G'){
check++;
}
if(door.charAt(j)=='b' && door.charAt(i)=='B'){
check++;
}
}
}
if(check==3){
return "YES";
}
else{
return "NO";
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 2b810244c4ec82cb48d529318ed29d1e | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
import java.io.*;
public class contest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-->0) {
String s = sc.next();
ArrayList<Character> l = new ArrayList<>();
for (int i = 0;i<s.length();i++) {
l.add(s.charAt(i));
}
if (l.indexOf('r')<l.indexOf('R') && l.indexOf('g')<l.indexOf('G') && l.indexOf('b')<l.indexOf('B')) {
System.out.println("YES");
}else {
System.out.println("NO");
}
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 5dd03bfcbdffdc2b6a83245abdc63c34 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes |
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int t=in.nextInt();
ArrayList<Character>arr=new ArrayList<>();
for (int i = 0; i < t; i++) {
String s=in.next();
boolean ans=true;
for (int j = 0; j < s.length(); j++) {
if(s.charAt(j)=='r'|| s.charAt(j)=='b'||s.charAt(j)=='g')
arr.add(s.charAt(j));
else if(s.charAt(j)=='R'){
if(arr.contains('r'))
arr.remove((Object)'r');
else{
ans=false; break;
}
}
else if(s.charAt(j)=='G'){
if(arr.contains('g') )
arr.remove((Object)'g');
else{
ans=false; break;
}
}
else if(s.charAt(j)=='B'){
if(arr.contains('b'))
arr.remove((Object)'b');
else{
ans=false; break;
}
}
}
if (ans)
System.out.println("YES");
else
System.out.println("NO");
arr.clear();
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | f0dc128354033b33dfed585a059a5aaa | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Array;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import org.w3c.dom.Node;
public class codechef3 {
static class comp implements Comparator<String>
{
@Override
public int compare(String o1, String o2) {
if(o1.length()>o2.length())
return 1;
else if(o1.length()<o2.length())
return -1;
else return o1.compareTo(o2);
}
}
static class Pair<Integer,Intetger>
{
int k=0;
int v=0;
public Pair(int a,int b)
{
k=a;
v=b;
}
public int getKey()
{
return k;
}
}
static class FastReader
{BufferedReader br;
StringTokenizer st;
public FastReader()
{ br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
//-------------------------------------------------------------------------------------------
public static void main(String[] args) {
FastReader s=new FastReader();
int t=s.nextInt();
while(t-->0)
{
String s1=s.next();
int r=0,b=0,g=0;
int flag=0;
for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)=='G'&&g==0||s1.charAt(i)=='B'&&b==0||s1.charAt(i)=='R'&&r==0)
{
flag=1;
break;
}else if(s1.charAt(i)=='g')
g++;else if(s1.charAt(i)=='r')r++;
else if(s1.charAt(i)=='b')
b++;
}
if(flag==0)
System.out.println("YES");
else System.out.println("NO");
}
}
//1 1 1 1 1 1 1 1 1 1 1 1
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | b825307bfaa21d2bcc3be4d9ff7d1e49 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.Scanner;
public class DoorsAndKeys {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int i = 0; i < t; i++) {
boolean result = true;
boolean rKey = false , gKey = false , bKey = false;
char ch[] = in.next().toCharArray();
for(int j=0 ; j<ch.length ; j++){
switch(ch[j]){
case 'r':
rKey = true;
break;
case 'b':
bKey = true;
break;
case 'g':
gKey = true;
break;
case 'R':
if(!rKey)
result = false;
break;
case 'G':
if(!gKey)
result = false;
break;
case 'B':
if(!bKey)
result = false;
break;
}
if(!result)
break;
}
if(result)
System.out.println("YES");
else
System.out.println("NO");
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 1a3277f700deef55e5f01e576e42822b | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.awt.*;
import java.util.*;
import java.io.*;
public class Codeforces {
static FScanner sc = new FScanner();
static PrintWriter out = new PrintWriter(System.out);
static final Random random = new Random();
static long mod = 1000000007L;
static HashMap<String, Integer> map = new HashMap<>();
static boolean[] sieve = new boolean[1000000];
static double[] fib = new double[1000000];
public static void main(String args[]) throws IOException {
int T = sc.nextInt();
while (T-- > 0) {
String s=sc.next();
int r=0,R=0,g=0,G=0,b=0,B=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='r')
r=i;
else if(s.charAt(i)=='R')
R=i;
else if(s.charAt(i)=='g')
g=i;
else if(s.charAt(i)=='G')
G=i;
else if(s.charAt(i)=='b')
b=i;
else
B=i;
}
if(b>B||r>R||g>G)
out.println("NO");
else
out.println("YES");
}
out.close();
}
// TemplateCode
static void fib() {
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < fib.length; i++)
fib[i] = fib[i - 1] + fib[i - 2];
}
static void primeSieve() {
for (int i = 0; i < sieve.length; i++)
sieve[i] = true;
for (int i = 2; i * i <= sieve.length; i++) {
if (sieve[i]) {
for (int j = i * i; j < sieve.length; j += i) {
sieve[j] = false;
}
}
}
}
static int max(int a, int b) {
if (a < b)
return b;
return a;
}
static int min(int a, int b) {
if (a < b)
return a;
return b;
}
static void ruffleSort(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static <E> void print(E res) {
System.out.println(res);
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static int abs(int a) {
if (a < 0)
return -1 * a;
return a;
}
static class FScanner {
BufferedReader br;
StringTokenizer st;
public FScanner() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readintarray(int n) {
int res[] = new int[n];
for (int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
long[] readlongarray(int n) {
long res[] = new long[n];
for (int i = 0; i < n; i++) res[i] = nextLong();
return res;
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | a87c67135c1a8a0215756f2422afdebb | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class CpTemplate {
//Avinash template
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0) {
String keyDoor = sc.next();
int r = 0, g = 0, b =0;
boolean canPass = true;
for (int i =0;i<keyDoor.length();i++){
if(keyDoor.charAt(i) == 'r')
r++;
else if(keyDoor.charAt(i) == 'g')
g++;
else if(keyDoor.charAt(i) == 'b')
b++;
else if( (keyDoor.charAt(i) == 'R' && r<=0) || (keyDoor.charAt(i) == 'B' && b<=0) || (keyDoor.charAt(i) == 'G' && g<=0))
canPass = false;
}
if(canPass)
out.println("YES");
else
out.println("NO");
}
out.flush();
}
static boolean power(long a) {
return a != 0 && ((a & (a - 1)) == 0);
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sortReverse(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l,Collections.reverseOrder());
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readArrayLong(long n) {
long[] a=new long[(int)n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
long nextLong()
{
return Long.parseLong(next());
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 95f6894f8db0437049df376b958d8c17 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
public class DoorsAndKeys {
static void log(int[] a) {
System.out.println(Arrays.toString(a));
}
static void log(double[] a) {
System.out.println(Arrays.toString(a));
}
static void log(long[] a) {
System.out.println(Arrays.toString(a));
}
static void log(ArrayList a) {
System.out.println(a.toString());
}
static void log(int a) {
System.out.println(a);
}
static void log(double a) {
System.out.println(a);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i = 0; i < t; i++) {
String str = sc.next();
int r = 0, g = 0, b = 0;
boolean canPass = true;
for(int j = 0; j < str.length(); j++) {
if(str.charAt(j) == 'r') {
r++;
}
else if(str.charAt(j) == 'b') {
b++;
}
else if(str.charAt(j) == 'g') {
g++;
}
else if((str.charAt(j) == 'R' && r <= 0) || (str.charAt(j) == 'B' && b <= 0) || (str.charAt(j) == 'G' && g <= 0)) {
canPass = false;
break;
}
}
if(canPass) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 28fd3373bf4528d0e79454429221cd56 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pranay
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ADoorsAndKeys solver = new ADoorsAndKeys();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class ADoorsAndKeys {
public void solve(int testNumber, FastReader in, PrintWriter out) {
char[] c = in.next().toCharArray();
HashSet<Character> h = new HashSet<>();
for (char e : c) {
if (Character.isUpperCase(e)) {
if (!h.contains(Character.toLowerCase(e))) {
out.println("NO");
return;
}
} else {
h.add(e);
}
}
out.println("YES");
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) return -1;
}
return buf[curChar++];
}
public 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 boolean isSpaceChar(int c) {
if (filter != null) return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | b10b48c024b002718566ae0ba8f34dfb | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pranay
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ADoorsAndKeys solver = new ADoorsAndKeys();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class ADoorsAndKeys {
public void solve(int testNumber, FastReader in, PrintWriter out) {
char[] c = in.next().toCharArray();
HashSet<Character> h = new HashSet<>();
for (char e : c) {
if (Character.isUpperCase(e)) {
if (!h.contains(Character.toLowerCase(e))) {
out.println("NO");
return;
}
} else {
h.add(e);
}
}
out.println("YES");
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) return -1;
}
return buf[curChar++];
}
public 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 boolean isSpaceChar(int c) {
if (filter != null) return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 036b3a3d6be1abc9b38690460c9672cd | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.*;
import java.util.*;
public class MainSolve {
public static void main(String[] args) throws IOException {
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out));
int testNum=Integer.parseInt(reader.readLine());
for (int i = 0; i < testNum; i++) {
String str=reader.readLine();
out.write(solve(str)+"\n");
}
out.flush();
out.close();
reader.close();
}
public static String solve(String s){
HashSet<Character> door=new HashSet<>(3);
HashSet<Character> key=new HashSet<>(3);
char[] charArray=s.toCharArray();
int i=0;
while (true){
if (Character.isLowerCase(charArray[i])){
key.add(charArray[i]);
}else if (!Character.isLowerCase(charArray[i])){
if (!key.contains(Character.toLowerCase(charArray[i]))){
return "NO";
}
}
if (i==charArray.length-1){
return "YES";
}
i++;
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | e7379a45de6ebbbf4e91c19c5102af69 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.*;
public class DoorsAndKeys
{
public static void main(String []args)throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(in.readLine());
for(int i=0; i<tc; i++)
{
String s[] = new String[1];
s = in.readLine().split("");
int r=0, g=0, b=0, R=0, G=0, B=0;
for(int j=0; j<6; j++)
{
if(s[j].equals("R"))
R=j;
else if(s[j].equals("G"))
G=j;
else if(s[j].equals("B"))
B=j;
else if(s[j].equals("r"))
r=j;
else if(s[j].equals("g"))
g=j;
else
b=j;
}
if(r>R || g>G || b>B)
System.out.println("NO");
else
System.out.println("YES");
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | cd9cb824f0f2392aea6b2d11ccb09c67 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class P1644A {
public static void main(String[] args) throws IOException{
BufferedReader io = new BufferedReader(new InputStreamReader(System.in));
Integer cnt = Integer.valueOf(io.readLine());
List<String> rs = new ArrayList<String>();
while (cnt > 0) {
cnt--;
String input = io.readLine();
int[] keys = new int[3];
boolean flag = true;
for(int i = 0; i < input.length(); i++) {
if(input.charAt(i) == 'R') {
if (keys[0] != 1) {
flag = false;
}
} else if (input.charAt(i) == 'G') {
if (keys[1] != 1) {
flag = false;
}
} else if (input.charAt(i) == 'B') {
if (keys[2] != 1) {
flag = false;
}
} else if (input.charAt(i) == 'r') {
keys[0] = 1;
} else if (input.charAt(i) == 'g') {
keys[1] = 1;
} else if (input.charAt(i) == 'b') {
keys[2] = 1;
}
}
if (flag) {
rs.add("YES");
} else {
rs.add("NO");
}
}
for (String string : rs) {
System.out.println(string);
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | ba68fcc0938860e56f24d78572111e32 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static void solve(String s){
Map<Character, Integer> count = new HashMap<>();
count.put('r', 0);
count.put('g', 0);
count.put('b', 0);
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(Character.isLowerCase(ch)){
count.put(ch, count.get(ch) + 1);
}
else{
char k = Character.toLowerCase(ch);
if(count.get(k) <= 0){
System.out.println("NO");
return;
}
count.put(k, count.get(k) - 1);
}
}
System.out.println("YES");
}
public static void main(String[] args){
MyScanner scanner = new MyScanner();
int num = scanner.nextInt();
for(int i = 0; i < num; i++){
solve(scanner.nextLine());
}
}
//public static PrintWriter out;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 318276f0330ca58acf26a21f144179e0 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int m = sc.nextInt();
while (m-- > 0) {
String s = sc.next();
char [] c = s.toCharArray();
boolean flag = false;
for (int i = 0; i < c.length; i++) {
if(c[i]=='r'||c[i]=='g'||c[i]=='b') {
flag = false;
for (int j = i; j < c.length; j++) {
if(c[j]==(c[i]-32)) {
flag = true;
break;
}
}
if(flag ==false) {
System.out.println("NO");
break;
}
}
}
if(flag==true) {
System.out.println("YES");
}
}
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 95a963e77fb90d75470ca2db1165432d | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
public class Main
{
public static String openAllDoors(String s,int n)
{
boolean r,g,b;
r = g = b = false;
for(int i=0;i<n;i++)
{
char c = s.charAt(i);
if(c=='r') r = true;
else if(c=='g') g = true;
else if(c=='b') b = true;
else
{
if(c=='R')
if(!r) return "NO";
if(c=='G')
if(!g) return "NO";
if(c=='B')
if(!b) return "NO";
}
}
return "YES";
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
while(test-->0)
{
String s = sc.next();
System.out.println(openAllDoors(s,s.length()));
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 7caba960d4d2f67ebde95fe98d3bb974 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
public class Solution{
public static void main(String[] args)throws java.lang.Exception {
Scanner sc=new Scanner(System.in);
int t;
t=sc.nextInt();
while(t-->0)
{
String s=sc.next();
if(s.indexOf('B')>s.indexOf('b')&&s.indexOf('G')>s.indexOf('g')&&s.indexOf('R')>s.indexOf('r'))
System.out.println("YES");
else
System.out.println("NO");
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | dcb3a405a70514d37979f8d6cc444b03 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | //package archive.a.hundred.h17;
import java.util.*;
public class A1644 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
GAME: for (int i = 0; i < n; i++) {
String level = scan.next();
Map<Character, Integer> keys = new HashMap<>();
keys.put('r', 0);
keys.put('g', 0);
keys.put('b', 0);
for (char now : level.toCharArray()) {
Integer value;
switch (now) {
case 'r':
case 'g':
case 'b':
value = keys.get(now) + 1;
keys.replace(now, value);
break;
case 'R':
case 'G':
case 'B':
char key = (char)(now - 'A' + 'a');
value = keys.get(key);
if (value > 0) {
keys.replace(now, value - 1);
} else {
System.out.println("NO");
continue GAME;
}
break;
}
}
System.out.println("YES");
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 8 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 64fac24ba2d30e41a5687f8676e4ce66 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
public class file
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
String s=sc.next();
if((s.indexOf('b')<s.indexOf('B'))&&(s.indexOf('g')<s.indexOf('G'))&&(s.indexOf('r')<s.indexOf('R')))
System.out.println("YES");
else
System.out.println("NO");
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 3899993e717b526330dbbf201ab46513 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
import static java.lang.System.*;
import static java.util.Arrays.*;
import static java.util.stream.IntStream.iterate;
public class Template {
private static final FastScanner scanner = new FastScanner();
private static void solve() {
var a = s().toCharArray();
int r = 0, b = 0, g = 0;
for (char i : a) {
if (i == 'r') r++;
else if (i == 'b') b++;
else if (i == 'g') g++;
else if (i == 'G') {
if (g>0) g--;
else {
no();
return;
}
} else if (i == 'B') {
if (b>0) b--;
else {
no();
return;
}
} else if (i == 'R') {
if (r>0) r--;
else {
no();
return;
}
}
}
yes();
}
public static void main(String[] args) {
int t = i();
while (t-->0) {
solve();
}
}
private static long fac(int n) {
long res = 1;
for (int i = 2; i<=n; i++) {
res*=i;
}
return res;
}
private static BigInteger factorial(int n) {
BigInteger res = BigInteger.valueOf(1);
for (int i = 2; i <= n; i++){
res = res.multiply(BigInteger.valueOf(i));
}
return res;
}
private static long l() {
return scanner.nextLong();
}
private static int i() {
return scanner.nextInt();
}
private static String s() {
return scanner.next();
}
private static void yes() {
out.println("YES");
}
private static void no() {
out.println("NO");
}
private static int toInt(char c) {
return Integer.parseInt(c+"");
}
private static void printArray(long[] a) {
StringBuilder builder = new StringBuilder();
for (long i : a)
builder.append(i).append(' ');
out.println(builder);
}
private static void printArray(int[] a) {
StringBuilder builder = new StringBuilder();
for (int i : a)
builder.append(i).append(' ');
out.println(builder);
}
private static int binPow(int a, int n) {
if (n == 0)
return 1;
if (n % 2 == 1)
return binPow(a, n-1) * a;
else {
int b = binPow(a, n/2);
return b * b;
}
}
private static boolean isPrime(long n) {
return iterate(2, i -> (long) i * i <= n, i -> i + 1).noneMatch(i -> n % i == 0);
}
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
private static void stableSort(int[] a) {
List<Integer> list = stream(a).boxed().sorted().toList();
setAll(a, list::get);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] readLong(int n) {
long[] a = new long[n];
for (int i = 0; i<n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class SegmentTreeRMXQ {
static int getMid(int s, int e) {
return s + (e - s) / 2;
}
static int MaxUtil(int[] st, int ss, int se, int l, int r, int node) {
if (l <= ss && r >= se)
return st[node];
if (se < l || ss > r)
return -1;
int mid = getMid(ss, se);
return max(
MaxUtil(st, ss, mid, l, r,
2 * node + 1),
MaxUtil(st, mid + 1, se, l, r,
2 * node + 2));
}
static void updateValue(int[] arr, int[] st, int ss, int se, int index, int value, int node) {
if (index < ss || index > se) {
System.out.println("Invalid Input");
return;
}
if (ss == se) {
arr[index] = value;
st[node] = value;
} else {
int mid = getMid(ss, se);
if (index <= mid)
updateValue(arr, st, ss, mid,
index, value,
2 * node + 1);
else
updateValue(arr, st, mid + 1, se, index,
value, 2 * node + 2);
st[node] = max(st[2 * node + 1],
st[2 * node + 2]);
}
}
static int getMax(int[] st, int n, int l, int r) {
if (l < 0 || r > n - 1 || l > r) {
System.out.print("Invalid Input\n");
return -1;
}
return MaxUtil(st, 0, n - 1, l, r, 0);
}
static int constructSTUtil(int[] arr, int ss, int se, int[] st, int si) {
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
int mid = getMid(ss, se);
st[si] = max(
constructSTUtil(arr, ss, mid,
st, si * 2 + 1),
constructSTUtil(arr, mid + 1,
se, st,
si * 2 + 2));
return st[si];
}
static int[] constructST(int[] arr, int n) {
int x = (int)Math.ceil(Math.log(n) / Math.log(2));
int max_size = 2 * (int)Math.pow(2, x) - 1;
int[] st = new int[max_size];
constructSTUtil(arr, 0, n - 1, st, 0);
return st;
}
}
static class SegmentTreeRMNQ {
int[] st;
int minVal(int x, int y) {
return min(x, y);
}
int getMid(int s, int e) {
return s + (e - s) / 2;
}
int RMQUtil(int ss, int se, int qs, int qe, int index) {
if (qs <= ss && qe >= se)
return st[index];
if (se < qs || ss > qe)
return Integer.MAX_VALUE;
int mid = getMid(ss, se);
return minVal(RMQUtil(ss, mid, qs, qe, 2 * index + 1),
RMQUtil(mid + 1, se, qs, qe, 2 * index + 2));
}
int RMQ(int n, int qs, int qe) {
if (qs < 0 || qe > n - 1 || qs > qe) {
System.out.println("Invalid Input");
return -1;
}
return RMQUtil(0, n - 1, qs, qe, 0);
}
int constructSTUtil(int[] arr, int ss, int se, int si) {
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
int mid = getMid(ss, se);
st[si] = minVal(constructSTUtil(arr, ss, mid, si * 2 + 1),
constructSTUtil(arr, mid + 1, se, si * 2 + 2));
return st[si];
}
void constructST(int[] arr, int n) {
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
int max_size = 2 * (int) Math.pow(2, x) - 1;
st = new int[max_size]; // allocate memory
constructSTUtil(arr, 0, n - 1, 0);
}
}
static class SegmentTreeRSQ
{
int[] st; // The array that stores segment tree nodes
/* Constructor to construct segment tree from given array. This
constructor allocates memory for segment tree and calls
constructSTUtil() to fill the allocated memory */
SegmentTreeRSQ(int[] arr, int n)
{
// Allocate memory for segment tree
//Height of segment tree
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
//Maximum size of segment tree
int max_size = 2 * (int) Math.pow(2, x) - 1;
st = new int[max_size]; // Memory allocation
constructSTUtil(arr, 0, n - 1, 0);
}
// A utility function to get the middle index from corner indexes.
int getMid(int s, int e) {
return s + (e - s) / 2;
}
/* A recursive function to get the sum of values in given range
of the array. The following are parameters for this function.
st --> Pointer to segment tree
si --> Index of current node in the segment tree. Initially
0 is passed as root is always at index 0
ss & se --> Starting and ending indexes of the segment represented
by current node, i.e., st[si]
qs & qe --> Starting and ending indexes of query range */
int getSumUtil(int ss, int se, int qs, int qe, int si)
{
// If segment of this node is a part of given range, then return
// the sum of the segment
if (qs <= ss && qe >= se)
return st[si];
// If segment of this node is outside the given range
if (se < qs || ss > qe)
return 0;
// If a part of this segment overlaps with the given range
int mid = getMid(ss, se);
return getSumUtil(ss, mid, qs, qe, 2 * si + 1) +
getSumUtil(mid + 1, se, qs, qe, 2 * si + 2);
}
/* A recursive function to update the nodes which have the given
index in their range. The following are parameters
st, si, ss and se are same as getSumUtil()
i --> index of the element to be updated. This index is in
input array.
diff --> Value to be added to all nodes which have I in range */
void updateValueUtil(int ss, int se, int i, int diff, int si)
{
// Base Case: If the input index lies outside the range of
// this segment
if (i < ss || i > se)
return;
// If the input index is in range of this node, then update the
// value of the node and its children
st[si] = st[si] + diff;
if (se != ss) {
int mid = getMid(ss, se);
updateValueUtil(ss, mid, i, diff, 2 * si + 1);
updateValueUtil(mid + 1, se, i, diff, 2 * si + 2);
}
}
// The function to update a value in input array and segment tree.
// It uses updateValueUtil() to update the value in segment tree
void updateValue(int arr[], int n, int i, int new_val)
{
// Check for erroneous input index
if (i < 0 || i > n - 1) {
System.out.println("Invalid Input");
return;
}
// Get the difference between new value and old value
int diff = new_val - arr[i];
// Update the value in array
arr[i] = new_val;
// Update the values of nodes in segment tree
updateValueUtil(0, n - 1, i, diff, 0);
}
// Return sum of elements in range from index qs (query start) to
// qe (query end). It mainly uses getSumUtil()
int getSum(int n, int qs, int qe)
{
// Check for erroneous input values
if (qs < 0 || qe > n - 1 || qs > qe) {
System.out.println("Invalid Input");
return -1;
}
return getSumUtil(0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree for array[ss..se].
// si is index of current node in segment tree st
int constructSTUtil(int arr[], int ss, int se, int si)
{
// If there is one element in array, store it in current node of
// segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then recur for left and
// right subtrees and store the sum of values in this node
int mid = getMid(ss, se);
st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) +
constructSTUtil(arr, mid + 1, se, si * 2 + 2);
return st[si];
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 473461748e9466bebe688c0473c917d9 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
public class ARestoringThreeNumbers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t=in.nextInt();
while(t>0){
int r=0,g=0,b=0;
String s=in.next();
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='r')
r=1;
else if(s.charAt(i)=='g')
g=1;
else if(s.charAt(i)=='b')
b=1;
if((s.charAt(i)=='R'&&r!=1)||(s.charAt(i)=='G'&&g!=1)||(s.charAt(i)=='B'&&b!=1)){
System.out.println("NO");
break;
}
}
if(r==1&&g==1&&b==1)
System.out.println("YES");
t--;
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 6475e6c7a044b5b39339f2c8e2dda2f5 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t>0){
t--;
String s=sc.next();
int r=0,g=0,b=0,count=0;
for(int i=0;i<6;i++){
if(s.charAt(i)=='r'){
r++;
}if(s.charAt(i)=='g'){
g++;
}if(s.charAt(i)=='b'){
b++;
}
if(s.charAt(i)=='R' && r==0)
{
count++;
}if(s.charAt(i)=='G'&& g==0)
{
count++;
}if(s.charAt(i)=='B' && b==0)
{
count++;
}
}
if(count>0){
System.out.println("NO");
}else{
System.out.println("YES");
}
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 71c22db977a0929f11f4c62451d412e1 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
import java.lang.*;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int r=0,b=0,g=0,R=0,B=0,G=0;
for(int i=0;i<t;i++){
String s = sc.next();
for(int j=0;j<s.length();j++){
char c = s.charAt(j);
if(c=='r'){
r=j;
}
else if(c=='b'){
b = j;
}
else if(c=='g'){
g = j;
}
else if(c=='R'){
R = j;
}
else if(c=='B'){
B = j;
}
else if(c=='G'){
G = j;
}
}
if((r<R)&&(b<B)&&(g<G)){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 19ca2a36088a418f08d951a39b1efefa | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.Scanner;
public class DoorsAndKeys {
public static void main(String[]args) {
Scanner sn = new Scanner(System.in);
int n = sn.nextInt();
sn.nextLine();
for(int i=0; i<n; i++) {
String sent = sn.nextLine();
// System.out.println(sent);
int r=0, g=0, b=0;
boolean poss = true;
for(int j =0; j<sent.length(); j++) {
char ch = sent.charAt(j);
if(ch=='r') {
r++;
} else if(ch=='g') {
g++;
} else if(ch=='b') {
b++;
} else if(ch=='R') {
//System.out.println(r);
if(r==0) {
poss = false; break;
}
} else if(ch=='G') {
if(g==0) {
poss = false; break;
}
} else if(ch=='B') {
if(b==0) {
poss = false; break;
}
}
}
if(poss) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 57cd4698b1fa4c9b74281b7b81385202 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes |
//https://codeforces.com/problemset/problem/1644/A
import java.util.Scanner;
public class Doors_and_Keys {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcase = sc.nextInt();
while (testcase != 0) {
testcase--;
boolean red = false, green = false, blue = false, okay = true;
String s = sc.next();
char[] str = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
if (str[i] == 'r')
red = true;
else if (str[i] == 'g')
green = true;
else if (str[i] == 'b')
blue = true;
if ((str[i] == 'R' && !red) || (str[i] == 'G' && !green) || (str[i] == 'B' && !blue)) {
okay = false;
break;
}
}
if (okay)
System.out.print("YES");
else
System.out.print("NO");
if (testcase > 0)
System.out.println();
}
sc.close();
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | d79205586f343035f9e21dde4e8ab64d | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc =new Scanner(System.in);
int tc = sc.nextInt();
while(tc-- > 0){
String s = sc.next();
boolean gotr = false;
boolean gotg = false;
boolean gotb = false;
boolean ans = true;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(ch == 'r'){
gotr = true;
}else if(ch == 'g'){
gotg = true;
}else if(ch == 'b'){
gotb = true;
}else if(ch == 'R'){
if(gotr) continue;
else{
ans = false;
break;
}
}else if(ch == 'G'){
if(gotg) continue;
else{
ans = false;
break;
}
}else{
if(gotb) continue;
else{
ans = false;
break;
}
}
}
if(ans) System.out.println("YES");
else System.out.println("NO");
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 6f606a6b77e9b95c19e245bc4a3b91c0 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.Scanner;
public class Solution{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int test_cases = sc.nextInt();
for(int h=0;h<test_cases;h++){
String s = sc.next();
boolean r = false, g=false, b=false, done = false;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='R' && r){
continue;
}
else if(s.charAt(i)=='B' && b){
continue;
}
else if(s.charAt(i)=='G' && g){
continue;
}
else if(s.charAt(i)=='r'){
r=true;
}
else if(s.charAt(i)=='g'){
g=true;
}
else if(s.charAt(i)=='b'){
b = true;
}
else{
done =true;
System.out.println("NO");
break;
}
}
if(!done){
System.out.println("YES");
}
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 609009351bb516c2b4a6c016ad1d507b | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.*;
import java.util.*;
public
class Main {
public
static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
Scanner st = new Scanner(System.in);
int t = 1;
t = sc.nextInt();
while (t-- > 0) {
String s = sc.next();
if(s.indexOf("r") < s.indexOf("R") && s.indexOf("b") < s.indexOf("B")
&& s.indexOf("g") < s.indexOf("G") ){
System.out.println("YES");
}
else System.out.println("NO");
}
}
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 {
if (st.hasMoreTokens()) {
str = st.nextToken("\n");
} else {
str = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 630bfedbf629e808bdc87ab051b2ee33 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.io.*;
import java.text.MessageFormat;
import java.util.*;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
* Start writing the hardest code first
*/
public class A {
final boolean ONLINE_JUDGE = java.lang.System.getProperty("ONLINE_JUDGE") != null;
final boolean ANTI_TEST_FINDER_MODE = false;
final Random random = new Random(42);
private int solveOne(int testCase) {
char[] s = System.in.readStringAsCharArray();
Map<Character, Integer> map = new HashMap();
int p=0;
for(char ch : s) map.put(ch, p++);
boolean ok =
map.get('r') < map.get('R') &&
map.get('g') < map.get('G') &&
map.get('b') < map.get('B');
System.out.println(ok ? "YES" : "NO");
return 0;
}
class InputData {
<T> T next() {
return null;
}
}
private int solveOneNaive(int testCase) {
return 0;
}
private void solve() {
if (ANTI_TEST_FINDER_MODE) {
int t = 100_000;
for (int testCase = 0; testCase < t; testCase++) {
int expected = solveOneNaive(testCase);
int actual = solveOne(testCase);
if (expected != actual) {
throw new AssertionRuntimeException(
this.getClass().getSimpleName(),
testCase,
expected,
actual);
}
}
} else {
int t = nextInt();
for (int testCase = 0; testCase < t; testCase++) {
solveOne(testCase);
}
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(String testName,
int testCase,
Object expected,
Object actual, Object... input) {
super("Testcase: " + testCase + "\n expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private void assertThat(boolean b) {
if (!b) throw new RuntimeException();
}
private void assertThat(boolean b, String s) {
if (!b) throw new RuntimeException(s);
}
private int assertThatInt(long a) {
assertThat(Integer.MIN_VALUE <= a && a <= Integer.MAX_VALUE);
return (int) a;
}
void _______debug(String str, Object... os) {
if (!ONLINE_JUDGE) {
System.out.println(MessageFormat.format(str, os));
}
}
void _______debug(Object o) {
if (!ONLINE_JUDGE) {
_______debug("{0}", String.valueOf(o));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new A().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
final boolean USE_IO = ONLINE_JUDGE;
if (USE_IO) {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
} else {
final String nameIn = "input.txt";
final String nameOut = "output.txt";
try {
System.in = new FastInputStream(new FileInputStream(nameIn));
System.out = new FastPrintStream(new PrintStream(nameOut));
solve();
System.out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerFlush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
if (ptr == BUF_SIZE) innerFlush();
}
}
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerFlush();
if (x < 0) {
print((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerFlush();
if (x < 0) {
print((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(Object x) {
return print(x.toString()).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
private void innerFlush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerFlush");
}
}
public void flush() {
innerFlush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
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 long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public char[] readStringAsCharArray() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
char[] resArr = new char[res.length()];
res.getChars(0, res.length(), resArr, 0);
return resArr;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 0916d50f6e1c155486bf7ad64042df69 | train_108.jsonl | 1645540500 | The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundEdu123A {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
RoundEdu123A sol = new RoundEdu123A();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = true;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
String s = in.next();
if(isDebug){
out.printf("Test %d\n", i);
}
boolean ans = solve(s);
out.printlnAns(ans);
if(isDebug)
out.flush();
}
in.close();
out.close();
}
private boolean solve(String s) {
boolean[] haveKeys = new boolean['Z'+1];
for(int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if('a' <= ch && ch <= 'z')
haveKeys[ch + ('A'-'a')] = true;
else if(!haveKeys[ch])
return false;
}
return true;
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextTreeEdges(int n, int offset){
int[][] e = new int[n-1][2];
for(int i=0; i<n-1; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextPairs(int n){
return nextPairs(n, 0);
}
int[][] nextPairs(int n, int offset) {
int[][] xy = new int[2][n];
for(int i=0; i<n; i++) {
xy[0][i] = nextInt() + offset;
xy[1][i] = nextInt() + offset;
}
return xy;
}
int[][] nextGraphEdges(){
return nextGraphEdges(0);
}
int[][] nextGraphEdges(int offset) {
int m = nextInt();
int[][] e = new int[m][2];
for(int i=0; i<m; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
int[] inIdx = new int[n];
int[] outIdx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][outIdx[u]++] = v;
inNeighbors[v][inIdx[v]++] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
int[] idx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][idx[u]++] = v;
neighbors[v][idx[v]++] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["4\n\nrgbBRG\n\nRgbrBG\n\nbBrRgG\n\nrgRGBb"] | 2 seconds | ["YES\nNO\nYES\nNO"] | NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | Java 17 | standard input | [
"implementation"
] | 60eb29b2dfb4d6b136c58b33dbd2558e | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once. | 800 | For each testcase, print YES if the knight can open all doors. Otherwise, print NO. | standard output | |
PASSED | 883835e979054de4244bddcfb4dd2b37 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Set;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
* Start writing the hardest code first
*/
public class D {
final boolean ONLINE_JUDGE = java.lang.System.getProperty("ONLINE_JUDGE") != null;
private void solveOne() {
int n = nextInt();
int m = nextInt();
int k = nextInt();
int q = nextInt();
int[] x = new int[q];
int[] y = new int[q];
for (int i = 0; i < q; i++) {
x[i] = nextInt() - 1;
y[i] = nextInt() - 1;
}
Struct bitX = new Struct(n);
Struct bitY = new Struct(m);
int pow = 0;
for (int i = q - 1; i >= 0; i--) {
boolean iCoveredLater = bitX.isCovered(x[i]) && bitY.isCovered(y[i])
|| bitX.getSize() == n || bitY.getSize() == m;
if (!iCoveredLater) {
pow++;
}
bitX.set(x[i]);
bitY.set(y[i]);
}
System.out.println(powMod(k, pow, 998_244_353));
}
public long powMod(long base, long exp, long mod) {
long ans = 1;
while (exp > 0) {
if ((exp & 1) == 1) {
ans *= base;
ans %= mod;
}
base *= base;
base %= mod;
exp >>= 1;
}
return ans;
}
class Struct {
Struct(int size) {
//a = new int[size];
}
Set<Integer> a = new HashSet<>();
int size;
void set(int i) {
// if(a[i] == 0) {
// a[i] = 1;
// size++;
// }
a.add(i);
}
boolean isCovered(int i){
return a.contains(i);
}
int getSize(){
return a.size();
}
}
static class BinaryIndexedTree {
private final long[] value;
public BinaryIndexedTree(int size) {
value = new long[size];
}
public long get(int from, int to) {
if (from > to) {
return 0;
}
return get(to) - get(from - 1);
}
private long get(int to) {
long result = 0;
while (to >= 0) {
result += value[to];
to = (to & (to + 1)) - 1;
}
return result;
}
public void add(int at, long value) {
while (at < this.value.length) {
this.value[at] += value;
at = at | (at + 1);
}
}
}
private void solve() {
int t = nextInt();
for (int testCase = 0; testCase < t; testCase++) {
solveOne();
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(String testName,
int testCase,
Object expected,
Object actual, Object... input) {
super("Testcase: " + testCase + "\n expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private void assertThat(boolean b) {
if (!b) throw new RuntimeException();
}
private void assertThat(boolean b, String s) {
if (!b) throw new RuntimeException(s);
}
private int assertThatInt(long a) {
assertThat(Integer.MIN_VALUE <= a && a <= Integer.MAX_VALUE);
return (int) a;
}
void _______debug(String str, Object... os) {
if (!ONLINE_JUDGE) {
System.out.println(MessageFormat.format(str, os));
}
}
void _______debug(Object o) {
if (!ONLINE_JUDGE) {
_______debug("{0}", String.valueOf(o));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new D().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
final boolean USE_IO = ONLINE_JUDGE;
if (USE_IO) {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
} else {
final String nameIn = "input.txt";
final String nameOut = "output.txt";
try {
System.in = new FastInputStream(new FileInputStream(nameIn));
System.out = new FastPrintStream(new PrintStream(nameOut));
solve();
System.out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerFlush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
if (ptr == BUF_SIZE) innerFlush();
}
}
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerFlush();
if (x < 0) {
print((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerFlush();
if (x < 0) {
print((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(long[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(long[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(Object x) {
return print(x.toString()).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
private void innerFlush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerFlush");
}
}
public void flush() {
innerFlush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public char[][] readTable(int rowCount, int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readCharArray(columnCount);
}
return table;
}
public int[][] readIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readIntArray(columnCount);
}
return table;
}
public double[][] readDoubleTable(int rowCount, int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readDoubleArray(columnCount);
}
return table;
}
public long[][] readLongTable(int rowCount, int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readLongArray(columnCount);
}
return table;
}
public String[][] readStringTable(int rowCount, int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readStringArray(columnCount);
}
return table;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public void readStringArrays(String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readString();
}
}
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
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 long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 17 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 88459d1003ee3a94084a92053a4f79c8 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Array;
import java.math.*;
public class Simple{
public static class Node{
int v;
int val;
public Node(int v,int val){
this.val = val;
this.v = v;
}
}
static final Random random=new Random();
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static void ruffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
long oi=random.nextInt(n), temp=a[(int)oi];
a[(int)oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
public static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
public int compareTo(Pair other){
return this.y - other.y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
// public boolean equals(Pair other){
// if(this.x == other.x && this.y == other.y)return true;
// return false;
// }
// public int hashCode(){
// return 31*x + y;
// }
// @Override
// public int compareTo(Simple.Pair o) {
// // TODO Auto-generated method stub
// return 0;
// }
}
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static long modInverse(long n, long p)
{
return power(n, p - 2, p);
}
static long[] fac = new long[100000 + 1];
// Returns nCr % p using Fermat's
// little theorem.
static long nCrModPFermat(long n, long r,
long p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
return (fac[(int)n] * modInverse(fac[(int)r], p)
% p * modInverse(fac[(int)n - (int)r], p)
% p)
% p;
}
static int nCrModp(int n, int r, int p)
{
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
// static int gcd(int a, int b)
// {
// if(a == 0)return a;
// if (b == 0)
// return a;
// return gcd(b, a % b);
// }
static long gcd_long(long a, long b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd_long(a%b, b);
return gcd_long(a, b%a);
}
public static class DSU{
int n;
int par[];
int rank[];
public DSU(int n){
this.n = n;
par = new int[n+1];
rank = new int[n+1];
for(int i=1;i<=n;i++){
par[i] = i ;
rank[i] = 0;
}
}
public int findPar(int node){
if(node==par[node]){
return node;
}
return par[node] = findPar(par[node]);//path compression
}
public void union(int u,int v){
u = findPar(u);
v = findPar(v);
if(rank[u]<rank[v]){
par[u] = v;
}
else if(rank[u]>rank[v]){
par[v] = u;
}
else{
par[v] = u;
rank[u]++;
}
}
}
static final int MAXN = 100001;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
static void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j=i*i; j<MAXN; j+=i)
// marking spf[j] if it is not
// previously marked
if (spf[j]==j)
spf[j] = i;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
static Vector<Integer> getFactorization(int x)
{
Vector<Integer> ret = new Vector<>();
while (x != 1)
{
ret.add(spf[x]);
x = x / spf[x];
}
return ret;
}
// A utility function to get the
// middle index of given range.
static int getMid(int s, int e)
{
return s + (e - s) / 2;
}
/*
* A recursive function to get the sum
of values in given range of the array.
* The following are parameters
for this function.
*
* st -> Pointer to segment tree
* node -> Index of current node in
* the segment tree.
* ss & se -> Starting and ending indexes
* of the segment represented
* by current node, i.e., st[node]
* l & r -> Starting and ending indexes
* of range query
*/
static int MaxUtil(int[] st, int ss,
int se, int l,
int r, int node)
{
// If segment of this node is completely
// part of given range, then return
// the max of segment
if (l <= ss && r >= se)
return st[node];
// If segment of this node does not
// belong to given range
if (se < l || ss > r)
return -1;
// If segment of this node is partially
// the part of given range
int mid = getMid(ss, se);
return Math.max(
MaxUtil(st, ss, mid, l, r,
2 * node + 1),
MaxUtil(st, mid + 1, se, l, r,
2 * node + 2));
}
/*
* A recursive function to update the
nodes which have the given index in their
* range. The following are parameters
st, ss and se are same as defined above
* index -> index of the element to be updated.
*/
static void updateValue(int arr[], int[]
st, int ss,
int se, int index,
int value,
int node)
{
if (index < ss || index > se) {
System.out.println("Invalid Input");
return;
}
if (ss == se) {
// update value in array and in
// segment tree
arr[index] = value;
st[node] = value;
}
else {
int mid = getMid(ss, se);
if (index >= ss && index <= mid)
updateValue(arr, st, ss, mid,
index, value,
2 * node + 1);
else
updateValue(arr, st, mid + 1, se, index,
value, 2 * node + 2);
st[node] = Math.max(st[2 * node + 1],
st[2 * node + 2]);
}
return;
}
// Return max of elements in range from
// index l (query start) to r (query end).
static int getMax(int[] st, int n, int l, int r)
{
// Check for erroneous input values
if (l < 0 || r > n - 1 || l > r) {
System.out.printf("Invalid Input\n");
return -1;
}
return MaxUtil(st, 0, n - 1, l, r, 0);
}
// A recursive function that constructs Segment
// Tree for array[ss..se]. si is index of
// current node in segment tree st
static int constructSTUtil(int arr[],
int ss, int se,
int[] st, int si)
{
// If there is one element in array, store
// it in current node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then
// recur for left and right subtrees and
// store the max of values in this node
int mid = getMid(ss, se);
st[si] = Math.max(
constructSTUtil(arr, ss, mid,
st, si * 2 + 1),
constructSTUtil(arr, mid + 1,
se, st,
si * 2 + 2));
return st[si];
}
/*
* Function to construct segment tree from
given array. This function allocates
* memory for segment tree.
*/
static int[] constructST(int arr[], int n)
{
// Height of segment tree
int x = (int)Math.ceil(Math.log(n) / Math.log(2));
// Maximum size of segment tree
int max_size = 2 * (int)Math.pow(2, x) - 1;
// Allocate memory
int[] st = new int[max_size];
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, st, 0);
// Return the constructed segment tree
return st;
}
static int gcd(int a, int b)
{
if(a == 0)return a;
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void main(String args[]){
try {
FastReader s=new FastReader();
// FastWriter out = new FastWriter();
// Scanner s = new Scanner(System.in);
int testCases= s.nextInt();
for(int t = 1; t <= testCases; t++){
int n = s.nextInt();
int m = s.nextInt();
long k = s.nextInt();
int q = s.nextInt();
long mod = 998244353 ;
int query[][] = new int[q][2];
Set<Integer> row = new HashSet<>();
Set<Integer> col = new HashSet<>();
for(int i =0; i < q; i++) {
query[i][0] = s.nextInt();
query[i][1] = s.nextInt();
}
long ans = 1;
for(int i = q-1; i >= 0; i--) {
boolean bool = false;
if(row.contains(query[i][0]) == false) {
row.add(query[i][0]);
bool = true;
}
if(col.contains(query[i][1]) == false) {
col.add(query[i][1]);
bool = true;
}
if(bool) {
ans = (ans * k ) % mod;
}
if(row.size() == n || col.size() == m)break;
}
System.out.println(ans);
}
}
catch (Exception e) {
System.out.println(e.toString());
// System.ouintt.println("Eh");
return;
}
}
}
/*
1 3 4 5 2
2 4 3 5 1
*/ | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 17 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | ffd93d54190dc358e7640e7de6b5b530 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class p4
{
BufferedReader br;
StringTokenizer st;
BufferedWriter bw;
public static void main(String[] args)throws Exception
{
new p4().run();
}
void run()throws IOException
{
br = new BufferedReader(new InputStreamReader(System.in));
bw=new BufferedWriter(new OutputStreamWriter(System.out));
solve();
}
void solve() throws IOException
{
// for(int i=100000-1;++i<=100000;)
// {
// for(int j=0;++j<2;)
// {
// long ans=nPowerM(i, 100000);
// System.out.println(i+" power 100000 is "+ans);
// }
// }
int t=ni();
int a[]=new int[200005];
int b[]=new int[200005];
while(t-->0)
{
int n=ni();
int m=ni();
int k=ni();
int q=ni();
int d1[]=new int[q];
int d2[]=new int[q];
for(int i=-1;++i<q;)
{
d1[i]=ni()-1;
d2[i]=ni()-1;
}
int x=0;
int j=0;
for(int i=q;--i>=0;)
{
if(a[d1[i]]==0 || b[d2[i]]==0)
{
if(a[d1[i]]==0)
{
a[d1[i]]=1;
n--;
}
if(b[d2[i]]==0)
{
b[d2[i]]=1;
m--;
}
x++;
}
j=i;
if(n==0 || m==0)
break;
}
for(int i=q;--i>=j;)
{
a[d1[i]]=0;
b[d2[i]]=0;
}
long ans=nPowerM(k, x);
bw.write(ans+"\n");
}
bw.flush();
}
public long nPowerM(int n, int m)
{
if(m==0)
return 1L;
int mod=998244353;
long ans=nPowerM(n, m/2);
ans*=ans;
ans%=mod;
if(m%2==1)
{
ans*=n;
ans%=mod;
}
ans%=mod;
return ans;
}
public long mod(long a)
{
int mod=1000000007;
//int mod=998244353;
a%=mod;
if(a<0)
a+=mod;
return a;
}
public static class data
{
int a,b;
public data(int a, int b)
{
this.a=a;
this.b=b;
}
}
public data[] dataArray(int n)
{
data d[]=new data[n];
for(int i=-1;++i<n;)
d[i]=new data(ni(), ni());
return d;
}
/////////////////////////////////////// FOR INPUT ///////////////////////////////////////
int[] nai(int n) { int a[]=new int[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;}
Integer[] naI(int n) { Integer a[]=new Integer[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;}
long[] nal(int n) { long a[]=new long[n]; for(int i=-1;++i<n;)a[i]=nl(); return a;}
char[] nac() {char c[]=nextLine().toCharArray(); return c;}
char [][] nmc(int n) {char c[][]=new char[n][]; for(int i=-1;++i<n;)c[i]=nac(); return c;}
int[][] nmi(int r, int c) {int a[][]=new int[r][c]; for(int i=-1;++i<r;)a[i]=nai(c); return a;}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
byte nb() { return Byte.parseByte(next()); }
short ns() { return Short.parseShort(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String nextLine()
{
String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 17 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 68e6a7a053d2489a7a111d9c3ce0ce2b | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundEdu123D {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
final long MOD = 998244353;
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
RoundEdu123D sol = new RoundEdu123D();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = true;
initIO(isFileIO);
//test();
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int q = in.nextInt();
int[][] xy = in.nextPairs(q, -1);
int[] x = xy[0];
int[] y = xy[1];
if(isDebug){
out.printf("Test %d\n", i);
}
int ans = solve(n, m, k, x, y);
out.printlnAns(ans);
if(isDebug)
out.flush();
}
in.close();
out.close();
}
private void test() {
int t = 0;
while(true) {
System.out.println(t);
int n = 100;
int m = 100;
int k = 10;
int q = 10000;
int[] r = new int[q];
int[] c = new int[q];
Random rand = new Random();
for(int i=0; i<q; i++) {
r[i] = rand.nextInt(n);
c[i] = rand.nextInt(n);
}
int[][] board = new int[n][m];
for(int i=0; i<q; i++) {
for(int j=0; j<n; j++)
board[j][c[i]] = i+1;
for(int j=0; j<m; j++)
board[r[i]][j] = i+1;
}
HashSet<Integer> remaining = new HashSet<>();
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
if(board[i][j]!= 0)
remaining.add(board[i][j]);
int num = remaining.size();
long expected = 1;
for(int i=0; i<num; i++)
expected = expected * k % MOD;
int ans = solve(n, m, k, r, c);
if((int)expected != ans) {
solve(n, m, k, r, c);
break;
}
t++;
}
}
// 0 1 2 1 1
// 1 2 0 0 1
// q3 q4 q1
// q4 q4 q4
// q3 q4 q2
private int solve(int n, int m, long k, int[] r, int[] c) {
// k: # of non-white colors
int q = r.length;
// q0 x
// q0 q0
// q1 q1
// q1 q0
// q1 q2
// q2 q2
// partition # of visible q's into k sets
// k^qq (for each visible q, k ways)
// qi is useless if ri = rj, ri = rk for j, k > i(j, k can be same)
// or for all r, r = rj for some j > i
// or for all c, c = cj for some j > i
// find minimum time t s.t. all covering is not happening?
HashMap<Integer, Integer> lastOpCoveringR = new HashMap<>();
HashMap<Integer, Integer> lastOpCoveringC = new HashMap<>();
// int[] lastOpCoveringR = new int[n];
// Arrays.fill(lastOpCoveringR, -1);
// int[] lastOpCoveringC = new int[m];
// Arrays.fill(lastOpCoveringC, -1);
for(int i=0; i<q; i++) {
lastOpCoveringR.put(r[i], i);
lastOpCoveringC.put(c[i], i);
}
int timeR = -1;
if(lastOpCoveringR.size() == n) {
timeR = q;
for(int i=0; i<n; i++)
timeR = Math.min(timeR, lastOpCoveringR.get(i));
}
int timeC = -1;
if(lastOpCoveringC.size() == m) {
timeC = q;
for(int i=0; i<m; i++)
timeC = Math.min(timeC, lastOpCoveringC.get(i));
}
int time = Math.max(timeR, timeC);
long ans = 1;
for(int i=0; i<q; i++) {
if(i < time)
continue;
if(i < lastOpCoveringR.get(r[i]) && i < lastOpCoveringC.get(c[i]))
continue;
ans = ans*k % MOD;
}
// int[] lastOpCoveringR = new int[n];
// Arrays.fill(lastOpCoveringR, -1);
// int[] lastOpCoveringC = new int[m];
// Arrays.fill(lastOpCoveringC, -1);
//
// for(int i=0; i<q; i++) {
// lastOpCoveringR[r[i]] = i;
// lastOpCoveringC[c[i]] = i;
// }
//
// int timeR = q;
// for(int i=0; i<n; i++)
// timeR = Math.min(timeR, lastOpCoveringR[i]);
//
// int timeC = q;
// for(int i=0; i<m; i++)
// timeC = Math.min(timeC, lastOpCoveringC[i]);
//
// int time = Math.max(timeR, timeC);
//
// long ans = 1;
// for(int i=0; i<q; i++) {
// if(i < time)
// continue;
// if(i < lastOpCoveringR[r[i]] && i < lastOpCoveringC[c[i]])
// continue;
// ans = ans*k % MOD;
// }
return (int)ans;
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextTreeEdges(int n, int offset){
int[][] e = new int[n-1][2];
for(int i=0; i<n-1; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextPairs(int n){
return nextPairs(n, 0);
}
int[][] nextPairs(int n, int offset) {
int[][] xy = new int[2][n];
for(int i=0; i<n; i++) {
xy[0][i] = nextInt() + offset;
xy[1][i] = nextInt() + offset;
}
return xy;
}
int[][] nextGraphEdges(){
return nextGraphEdges(0);
}
int[][] nextGraphEdges(int offset) {
int m = nextInt();
int[][] e = new int[m][2];
for(int i=0; i<m; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
int[] inIdx = new int[n];
int[] outIdx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][outIdx[u]++] = v;
inNeighbors[v][inIdx[v]++] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
int[] idx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][idx[u]++] = v;
neighbors[v][idx[v]++] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 17 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 04e9761ff739af872f600cad6d40c5bc | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
private static final int START_TEST_CASE = 1;
private static final int MOD = 998244353;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final int K = io.nextInt();
final int Q = io.nextInt();
int[] X = new int[Q];
int[] Y = new int[Q];
for (int q = 0; q < Q; ++q) {
X[q] = io.nextInt();
Y[q] = io.nextInt();
}
HashSet<IntKey> xDone = new HashSet<>();
HashSet<IntKey> yDone = new HashSet<>();
int visible = 0;
for (int q = Q - 1; q >= 0; --q) {
IntKey xKey = IntKey.of(X[q]);
IntKey yKey = IntKey.of(Y[q]);
if (xDone.size() >= N || yDone.size() >= M) {
continue;
}
if (xDone.contains(xKey) && yDone.contains(yKey)) {
continue;
}
xDone.add(xKey);
yDone.add(yKey);
++visible;
}
io.println(LongModMath.modPow(K, visible));
}
public static class IntKey {
public int value;
private IntKey(int value) {
this.value = value;
}
@Override
public int hashCode() {
return mulberry32(value + ADD_MIX);
}
@Override
public boolean equals(Object obj) {
IntKey other = (IntKey) obj;
return value == other.value;
}
@Override
public String toString() {
return Integer.toString(value);
}
private static final int mulberry32(int x) {
int z = (x + 0x6D2B79F5);
z = (z ^ (z >>> 15)) * (z | 1);
z ^= z + (z ^ (z >>> 7)) * (z | 61);
return z ^ (z >>> 14);
}
public static IntKey of(int value) {
if (CACHE_MIN <= value && value < CACHE_MAX) {
return CACHE[value - CACHE_MIN];
}
return new IntKey(value);
}
private static final int ADD_MIX = mulberry32((int) System.nanoTime());
private static final int CACHE_MIN = -256;
private static final int CACHE_MAX = 256;
private static final IntKey[] CACHE = new IntKey[CACHE_MAX - CACHE_MIN];
static {
for (int i = CACHE_MIN; i < CACHE_MAX; ++i) {
CACHE[i - CACHE_MIN] = new IntKey(i);
}
}
}
/**
* Computes arithmetic operations modulo some constant MOD, should be a prime.
* It is guaranteed to not overflow, as long as all operands are within the range [0, MOD).
*
* NOTE: It's recommended to copy the code in this class and inline it within your other functions,
* since it's cumbersome to write `LongModMath.multiply(a, LongModMath.add(b, c)`,
* compared to simply writing `multiply(a, add(b, c))`.
*/
public static class LongModMath {
private static final long RAW_MULTIPLY_MAX = 3037000499L;
private static final int CHUNK_SIZE = Long.SIZE - Long.numberOfLeadingZeros(Long.MAX_VALUE / (MOD + 1) + 1) - 1;
private static final long CHUNK_MASK = (1L << CHUNK_SIZE) - 1;
@SuppressWarnings("unused")
public static long multiply(long a, long b) {
if (MOD <= RAW_MULTIPLY_MAX) {
return a * b % MOD;
}
return multiplyInternal(a, b);
}
public static long add(long a, long b) {
long ans = a + b;
if (ans >= MOD) {
ans -= MOD;
}
return ans;
}
public static long add(long... arr) {
long ans = 0;
for (long x : arr) {
ans = add(ans, x);
}
return ans;
}
public static long subtract(long a, long b) {
return add(a, MOD - b);
}
/**
* Computes the value of (b ^ e) % MOD.
*/
public static long modPow(long b, long e) {
long p = b;
long ans = 1;
while (e > 0) {
if ((e & 1) == 1) {
ans = multiply(ans, p);
}
p = multiply(p, p);
e >>= 1;
}
return ans;
}
/**
* Computes the modular inverse, such that: ak % MOD = 1, for some k.
* See this page for details: http://rosettacode.org/wiki/Modular_inverse
*/
public static long modInverse(long a) {
return modPow(a, MOD - 2);
}
private static long multiplyInternal(long a, long b) {
if (a > b) {
return multiplyInternal(b, a);
}
if (a == 0) {
return 0;
}
long ans = 0;
while (a > 0) {
long mask = a & CHUNK_MASK;
if (mask > 0) {
ans = add(ans, (mask * b) % MOD);
}
b = (b << CHUNK_SIZE) % MOD;
a >>= CHUNK_SIZE;
}
return ans;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 4e5f14e48af11b387bca013a21954de8 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
private static final int START_TEST_CASE = 1;
private static final int MOD = 998244353;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final int K = io.nextInt();
final int Q = io.nextInt();
int[] X = new int[Q];
int[] Y = new int[Q];
for (int q = 0; q < Q; ++q) {
X[q] = io.nextInt();
Y[q] = io.nextInt();
}
int visible = 0;
DenseIntSet xDone = new DenseIntSet(N + 1);
DenseIntSet yDone = new DenseIntSet(M + 1);
for (int q = Q - 1; q >= 0; --q) {
if (xDone.contains(X[q]) && yDone.contains(Y[q])) {
continue;
}
if (xDone.size() >= N || yDone.size() >= M) {
continue;
}
xDone.add(X[q]);
yDone.add(Y[q]);
++visible;
}
io.println(LongModMath.modPow(K, visible));
}
private static class DenseIntSet {
public boolean[] has;
public int count;
public DenseIntSet(int size) {
this.has = new boolean[size];
}
public void add(int x) {
if (!has[x]) {
has[x] = true;
++count;
}
}
public boolean contains(int x) {
return has[x];
}
public int size() {
return count;
}
}
/**
* Computes arithmetic operations modulo some constant MOD, should be a prime.
* It is guaranteed to not overflow, as long as all operands are within the range [0, MOD).
*
* NOTE: It's recommended to copy the code in this class and inline it within your other functions,
* since it's cumbersome to write `LongModMath.multiply(a, LongModMath.add(b, c)`,
* compared to simply writing `multiply(a, add(b, c))`.
*/
public static class LongModMath {
private static final long RAW_MULTIPLY_MAX = 3037000499L;
private static final int CHUNK_SIZE = Long.SIZE - Long.numberOfLeadingZeros(Long.MAX_VALUE / (MOD + 1) + 1) - 1;
private static final long CHUNK_MASK = (1L << CHUNK_SIZE) - 1;
@SuppressWarnings("unused")
public static long multiply(long a, long b) {
if (MOD <= RAW_MULTIPLY_MAX) {
return a * b % MOD;
}
return multiplyInternal(a, b);
}
public static long add(long a, long b) {
long ans = a + b;
if (ans >= MOD) {
ans -= MOD;
}
return ans;
}
public static long add(long... arr) {
long ans = 0;
for (long x : arr) {
ans = add(ans, x);
}
return ans;
}
public static long subtract(long a, long b) {
return add(a, MOD - b);
}
/**
* Computes the value of (b ^ e) % MOD.
*/
public static long modPow(long b, long e) {
long p = b;
long ans = 1;
while (e > 0) {
if ((e & 1) == 1) {
ans = multiply(ans, p);
}
p = multiply(p, p);
e >>= 1;
}
return ans;
}
/**
* Computes the modular inverse, such that: ak % MOD = 1, for some k.
* See this page for details: http://rosettacode.org/wiki/Modular_inverse
*/
public static long modInverse(long a) {
return modPow(a, MOD - 2);
}
private static long multiplyInternal(long a, long b) {
if (a > b) {
return multiplyInternal(b, a);
}
if (a == 0) {
return 0;
}
long ans = 0;
while (a > 0) {
long mask = a & CHUNK_MASK;
if (mask > 0) {
ans = add(ans, (mask * b) % MOD);
}
b = (b << CHUNK_SIZE) % MOD;
a >>= CHUNK_SIZE;
}
return ans;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | d9d3eb9af9de12c33c2de592158d4ac6 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
private static final int START_TEST_CASE = 1;
private static final int MOD = 998244353;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final int K = io.nextInt();
final int Q = io.nextInt();
int[] X = new int[Q];
int[] Y = new int[Q];
for (int q = 0; q < Q; ++q) {
X[q] = io.nextInt();
Y[q] = io.nextInt();
}
int visible = 0;
DenseIntSet xDone = new DenseIntSet(N + 1);
DenseIntSet yDone = new DenseIntSet(M + 1);
for (int q = Q - 1; q >= 0; --q) {
if (xDone.contains(X[q]) && yDone.contains(Y[q])) {
continue;
}
if (xDone.size() >= N || yDone.size() >= M) {
continue;
}
xDone.add(X[q]);
yDone.add(Y[q]);
++visible;
}
io.println(LongModMath.modPow(K, visible));
}
private static class DenseIntSet {
public boolean[] has;
public int count;
public DenseIntSet(int size) {
this.has = new boolean[size];
}
public void add(int x) {
if (has[x]) {
return;
}
has[x] = true;
++count;
}
public boolean contains(int x) {
return has[x];
}
public int size() {
return count;
}
}
/**
* Computes arithmetic operations modulo some constant MOD, should be a prime.
* It is guaranteed to not overflow, as long as all operands are within the range [0, MOD).
*
* NOTE: It's recommended to copy the code in this class and inline it within your other functions,
* since it's cumbersome to write `LongModMath.multiply(a, LongModMath.add(b, c)`,
* compared to simply writing `multiply(a, add(b, c))`.
*/
public static class LongModMath {
private static final long RAW_MULTIPLY_MAX = 3037000499L;
private static final int CHUNK_SIZE = Long.SIZE - Long.numberOfLeadingZeros(Long.MAX_VALUE / (MOD + 1) + 1) - 1;
private static final long CHUNK_MASK = (1L << CHUNK_SIZE) - 1;
@SuppressWarnings("unused")
public static long multiply(long a, long b) {
if (MOD <= RAW_MULTIPLY_MAX) {
return a * b % MOD;
}
return multiplyInternal(a, b);
}
public static long add(long a, long b) {
long ans = a + b;
if (ans >= MOD) {
ans -= MOD;
}
return ans;
}
public static long add(long... arr) {
long ans = 0;
for (long x : arr) {
ans = add(ans, x);
}
return ans;
}
public static long subtract(long a, long b) {
return add(a, MOD - b);
}
/**
* Computes the value of (b ^ e) % MOD.
*/
public static long modPow(long b, long e) {
long p = b;
long ans = 1;
while (e > 0) {
if ((e & 1) == 1) {
ans = multiply(ans, p);
}
p = multiply(p, p);
e >>= 1;
}
return ans;
}
/**
* Computes the modular inverse, such that: ak % MOD = 1, for some k.
* See this page for details: http://rosettacode.org/wiki/Modular_inverse
*/
public static long modInverse(long a) {
return modPow(a, MOD - 2);
}
private static long multiplyInternal(long a, long b) {
if (a > b) {
return multiplyInternal(b, a);
}
if (a == 0) {
return 0;
}
long ans = 0;
while (a > 0) {
long mask = a & CHUNK_MASK;
if (mask > 0) {
ans = add(ans, (mask * b) % MOD);
}
b = (b << CHUNK_SIZE) % MOD;
a >>= CHUNK_SIZE;
}
return ans;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 8b39164ea862b6509e55b0b31ca911f9 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
private static final int START_TEST_CASE = 1;
private static final int MOD = 998244353;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final int K = io.nextInt();
final int Q = io.nextInt();
int[] X = new int[Q];
int[] Y = new int[Q];
for (int q = 0; q < Q; ++q) {
X[q] = io.nextInt();
Y[q] = io.nextInt();
}
int visible = 0;
HashSet<IntKey> xDone = new HashSet<>();
HashSet<IntKey> yDone = new HashSet<>();
for (int q = Q - 1; q >= 0; --q) {
IntKey xKey = IntKey.of(X[q]);
IntKey yKey = IntKey.of(Y[q]);
if (xDone.size() >= N || yDone.size() >= M) {
continue;
}
if (xDone.contains(xKey) && yDone.contains(yKey)) {
continue;
}
xDone.add(xKey);
yDone.add(yKey);
++visible;
}
io.println(LongModMath.modPow(K, visible));
}
public static class IntKey {
public int value;
private IntKey(int value) {
this.value = value;
}
@Override
public int hashCode() {
return mulberry32(value + ADD_MIX);
}
@Override
public boolean equals(Object obj) {
IntKey other = (IntKey) obj;
return value == other.value;
}
@Override
public String toString() {
return Integer.toString(value);
}
private static final int mulberry32(int x) {
int z = (x + 0x6D2B79F5);
z = (z ^ (z >>> 15)) * (z | 1);
z ^= z + (z ^ (z >>> 7)) * (z | 61);
return z ^ (z >>> 14);
}
public static IntKey of(int value) {
if (CACHE_MIN <= value && value < CACHE_MAX) {
return CACHE[value - CACHE_MIN];
}
return new IntKey(value);
}
private static final int ADD_MIX = mulberry32((int) System.nanoTime());
private static final int CACHE_MIN = -256;
private static final int CACHE_MAX = 256;
private static final IntKey[] CACHE = new IntKey[CACHE_MAX - CACHE_MIN];
static {
for (int i = CACHE_MIN; i < CACHE_MAX; ++i) {
CACHE[i - CACHE_MIN] = new IntKey(i);
}
}
}
/**
* Computes arithmetic operations modulo some constant MOD, should be a prime.
* It is guaranteed to not overflow, as long as all operands are within the range [0, MOD).
*
* NOTE: It's recommended to copy the code in this class and inline it within your other functions,
* since it's cumbersome to write `LongModMath.multiply(a, LongModMath.add(b, c)`,
* compared to simply writing `multiply(a, add(b, c))`.
*/
public static class LongModMath {
private static final long RAW_MULTIPLY_MAX = 3037000499L;
private static final int CHUNK_SIZE = Long.SIZE - Long.numberOfLeadingZeros(Long.MAX_VALUE / (MOD + 1) + 1) - 1;
private static final long CHUNK_MASK = (1L << CHUNK_SIZE) - 1;
@SuppressWarnings("unused")
public static long multiply(long a, long b) {
// if (MOD <= RAW_MULTIPLY_MAX) {
// return a * b % MOD;
// }
return multiplyInternal(a, b);
}
public static long add(long a, long b) {
long ans = a + b;
if (ans >= MOD) {
ans -= MOD;
}
return ans;
}
public static long add(long... arr) {
long ans = 0;
for (long x : arr) {
ans = add(ans, x);
}
return ans;
}
public static long subtract(long a, long b) {
return add(a, MOD - b);
}
/**
* Computes the value of (b ^ e) % MOD.
*/
public static long modPow(long b, long e) {
long p = b;
long ans = 1;
while (e > 0) {
if ((e & 1) == 1) {
ans = multiply(ans, p);
}
p = multiply(p, p);
e >>= 1;
}
return ans;
}
/**
* Computes the modular inverse, such that: ak % MOD = 1, for some k.
* See this page for details: http://rosettacode.org/wiki/Modular_inverse
*/
public static long modInverse(long a) {
return modPow(a, MOD - 2);
}
private static long multiplyInternal(long a, long b) {
if (a > b) {
return multiplyInternal(b, a);
}
if (a == 0) {
return 0;
}
long ans = 0;
while (a > 0) {
long mask = a & CHUNK_MASK;
if (mask > 0) {
ans = add(ans, (mask * b) % MOD);
}
b = (b << CHUNK_SIZE) % MOD;
a >>= CHUNK_SIZE;
}
return ans;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 0e9d0a6402861a8be16395c5f4804437 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
private static final int START_TEST_CASE = 1;
private static final int MOD = 998244353;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final int K = io.nextInt();
final int Q = io.nextInt();
int[] X = new int[Q];
int[] Y = new int[Q];
for (int q = 0; q < Q; ++q) {
X[q] = io.nextInt();
Y[q] = io.nextInt();
}
int visible = 0;
HashSet<IntKey> xDone = new HashSet<>();
HashSet<IntKey> yDone = new HashSet<>();
for (int q = Q - 1; q >= 0; --q) {
IntKey xKey = IntKey.of(X[q]);
IntKey yKey = IntKey.of(Y[q]);
if (xDone.size() >= N || yDone.size() >= M) {
continue;
}
if (xDone.contains(xKey) && yDone.contains(yKey)) {
continue;
}
xDone.add(xKey);
yDone.add(yKey);
++visible;
}
io.println(LongModMath.modPow(K, visible));
}
public static class IntKey {
public int value;
private IntKey(int value) {
this.value = value;
}
@Override
public int hashCode() {
return mulberry32(value + ADD_MIX);
}
@Override
public boolean equals(Object obj) {
IntKey other = (IntKey) obj;
return value == other.value;
}
@Override
public String toString() {
return Integer.toString(value);
}
private static final int mulberry32(int x) {
int z = (x + 0x6D2B79F5);
z = (z ^ (z >>> 15)) * (z | 1);
z ^= z + (z ^ (z >>> 7)) * (z | 61);
return z ^ (z >>> 14);
}
public static IntKey of(int value) {
if (CACHE_MIN <= value && value < CACHE_MAX) {
return CACHE[value - CACHE_MIN];
}
return new IntKey(value);
}
private static final int ADD_MIX = mulberry32((int) System.nanoTime());
private static final int CACHE_MIN = -256;
private static final int CACHE_MAX = 256;
private static final IntKey[] CACHE = new IntKey[CACHE_MAX - CACHE_MIN];
static {
for (int i = CACHE_MIN; i < CACHE_MAX; ++i) {
CACHE[i - CACHE_MIN] = new IntKey(i);
}
}
}
/**
* Computes arithmetic operations modulo some constant MOD, should be a prime.
* It is guaranteed to not overflow, as long as all operands are within the range [0, MOD).
*
* NOTE: It's recommended to copy the code in this class and inline it within your other functions,
* since it's cumbersome to write `LongModMath.multiply(a, LongModMath.add(b, c)`,
* compared to simply writing `multiply(a, add(b, c))`.
*/
public static class LongModMath {
private static final long RAW_MULTIPLY_MAX = 3037000499L;
private static final int CHUNK_SIZE = Long.SIZE - Long.numberOfLeadingZeros(Long.MAX_VALUE / (MOD + 1) + 1) - 1;
private static final long CHUNK_MASK = (1L << CHUNK_SIZE) - 1;
@SuppressWarnings("unused")
public static long multiply(long a, long b) {
if (MOD <= RAW_MULTIPLY_MAX) {
return a * b % MOD;
}
return multiplyInternal(a, b);
}
public static long add(long a, long b) {
long ans = a + b;
if (ans >= MOD) {
ans -= MOD;
}
return ans;
}
public static long add(long... arr) {
long ans = 0;
for (long x : arr) {
ans = add(ans, x);
}
return ans;
}
public static long subtract(long a, long b) {
return add(a, MOD - b);
}
/**
* Computes the value of (b ^ e) % MOD.
*/
public static long modPow(long b, long e) {
long p = b;
long ans = 1;
while (e > 0) {
if ((e & 1) == 1) {
ans = multiply(ans, p);
}
p = multiply(p, p);
e >>= 1;
}
return ans;
}
/**
* Computes the modular inverse, such that: ak % MOD = 1, for some k.
* See this page for details: http://rosettacode.org/wiki/Modular_inverse
*/
public static long modInverse(long a) {
return modPow(a, MOD - 2);
}
private static long multiplyInternal(long a, long b) {
if (a > b) {
return multiplyInternal(b, a);
}
if (a == 0) {
return 0;
}
long ans = 0;
while (a > 0) {
long mask = a & CHUNK_MASK;
if (mask > 0) {
ans = add(ans, (mask * b) % MOD);
}
b = (b << CHUNK_SIZE) % MOD;
a >>= CHUNK_SIZE;
}
return ans;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 9465bb31016ba112d7fbebf436c4727e | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
private static final int START_TEST_CASE = 1;
private static final int MOD = 998244353;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final int K = io.nextInt();
final int Q = io.nextInt();
int[] X = new int[Q];
int[] Y = new int[Q];
for (int q = 0; q < Q; ++q) {
X[q] = io.nextInt();
Y[q] = io.nextInt();
}
int visible = 0;
HashSet<IntKey> xDone = new HashSet<>();
HashSet<IntKey> yDone = new HashSet<>();
for (int q = Q - 1; q >= 0; --q) {
IntKey xKey = IntKey.of(X[q]);
IntKey yKey = IntKey.of(Y[q]);
if (xDone.contains(xKey) && yDone.contains(yKey)) {
continue;
}
if (xDone.size() >= N || yDone.size() >= M) {
continue;
}
xDone.add(xKey);
yDone.add(yKey);
++visible;
}
io.println(LongModMath.modPow(K, visible));
}
public static class IntKey {
public int value;
private IntKey(int value) {
this.value = value;
}
@Override
public int hashCode() {
return mulberry32(value + ADD_MIX);
}
@Override
public boolean equals(Object obj) {
IntKey other = (IntKey) obj;
return value == other.value;
}
@Override
public String toString() {
return Integer.toString(value);
}
private static final int mulberry32(int x) {
int z = (x + 0x6D2B79F5);
z = (z ^ (z >>> 15)) * (z | 1);
z ^= z + (z ^ (z >>> 7)) * (z | 61);
return z ^ (z >>> 14);
}
public static IntKey of(int value) {
if (CACHE_MIN <= value && value < CACHE_MAX) {
return CACHE[value - CACHE_MIN];
}
return new IntKey(value);
}
private static final int ADD_MIX = mulberry32((int) System.nanoTime());
private static final int CACHE_MIN = -256;
private static final int CACHE_MAX = 256;
private static final IntKey[] CACHE = new IntKey[CACHE_MAX - CACHE_MIN];
static {
for (int i = CACHE_MIN; i < CACHE_MAX; ++i) {
CACHE[i - CACHE_MIN] = new IntKey(i);
}
}
}
/**
* Computes arithmetic operations modulo some constant MOD, should be a prime.
* It is guaranteed to not overflow, as long as all operands are within the range [0, MOD).
*
* NOTE: It's recommended to copy the code in this class and inline it within your other functions,
* since it's cumbersome to write `LongModMath.multiply(a, LongModMath.add(b, c)`,
* compared to simply writing `multiply(a, add(b, c))`.
*/
public static class LongModMath {
private static final long RAW_MULTIPLY_MAX = 3037000499L;
private static final int CHUNK_SIZE = Long.SIZE - Long.numberOfLeadingZeros(Long.MAX_VALUE / (MOD + 1) + 1) - 1;
private static final long CHUNK_MASK = (1L << CHUNK_SIZE) - 1;
@SuppressWarnings("unused")
public static long multiply(long a, long b) {
if (MOD <= RAW_MULTIPLY_MAX) {
return a * b % MOD;
}
return multiplyInternal(a, b);
}
public static long add(long a, long b) {
long ans = a + b;
if (ans >= MOD) {
ans -= MOD;
}
return ans;
}
public static long add(long... arr) {
long ans = 0;
for (long x : arr) {
ans = add(ans, x);
}
return ans;
}
public static long subtract(long a, long b) {
return add(a, MOD - b);
}
/**
* Computes the value of (b ^ e) % MOD.
*/
public static long modPow(long b, long e) {
long p = b;
long ans = 1;
while (e > 0) {
if ((e & 1) == 1) {
ans = multiply(ans, p);
}
p = multiply(p, p);
e >>= 1;
}
return ans;
}
/**
* Computes the modular inverse, such that: ak % MOD = 1, for some k.
* See this page for details: http://rosettacode.org/wiki/Modular_inverse
*/
public static long modInverse(long a) {
return modPow(a, MOD - 2);
}
private static long multiplyInternal(long a, long b) {
if (a > b) {
return multiplyInternal(b, a);
}
if (a == 0) {
return 0;
}
long ans = 0;
while (a > 0) {
long mask = a & CHUNK_MASK;
if (mask > 0) {
ans = add(ans, (mask * b) % MOD);
}
b = (b << CHUNK_SIZE) % MOD;
a >>= CHUNK_SIZE;
}
return ans;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | ceee66f4cd53a5ec8ac011a2582cd331 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
private static final int START_TEST_CASE = 1;
private static final int MOD = 998244353;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final int K = io.nextInt();
final int Q = io.nextInt();
int[] X = new int[Q];
int[] Y = new int[Q];
for (int q = 0; q < Q; ++q) {
X[q] = io.nextInt();
Y[q] = io.nextInt();
}
int visible = 0;
HashSet<Integer> xDone = new HashSet<>();
HashSet<Integer> yDone = new HashSet<>();
for (int q = Q - 1; q >= 0; --q) {
if (xDone.contains(X[q]) && yDone.contains(Y[q])) {
continue;
}
if (xDone.size() >= N || yDone.size() >= M) {
continue;
}
xDone.add(X[q]);
yDone.add(Y[q]);
++visible;
}
io.println(LongModMath.modPow(K, visible));
}
/**
* Computes arithmetic operations modulo some constant MOD, should be a prime.
* It is guaranteed to not overflow, as long as all operands are within the range [0, MOD).
*
* NOTE: It's recommended to copy the code in this class and inline it within your other functions,
* since it's cumbersome to write `LongModMath.multiply(a, LongModMath.add(b, c)`,
* compared to simply writing `multiply(a, add(b, c))`.
*/
public static class LongModMath {
private static final long RAW_MULTIPLY_MAX = 3037000499L;
private static final int CHUNK_SIZE = Long.SIZE - Long.numberOfLeadingZeros(Long.MAX_VALUE / (MOD + 1) + 1) - 1;
private static final long CHUNK_MASK = (1L << CHUNK_SIZE) - 1;
@SuppressWarnings("unused")
public static long multiply(long a, long b) {
if (MOD <= RAW_MULTIPLY_MAX) {
return a * b % MOD;
}
return multiplyInternal(a, b);
}
public static long add(long a, long b) {
long ans = a + b;
if (ans >= MOD) {
ans -= MOD;
}
return ans;
}
public static long add(long... arr) {
long ans = 0;
for (long x : arr) {
ans = add(ans, x);
}
return ans;
}
public static long subtract(long a, long b) {
return add(a, MOD - b);
}
/**
* Computes the value of (b ^ e) % MOD.
*/
public static long modPow(long b, long e) {
long p = b;
long ans = 1;
while (e > 0) {
if ((e & 1) == 1) {
ans = multiply(ans, p);
}
p = multiply(p, p);
e >>= 1;
}
return ans;
}
/**
* Computes the modular inverse, such that: ak % MOD = 1, for some k.
* See this page for details: http://rosettacode.org/wiki/Modular_inverse
*/
public static long modInverse(long a) {
return modPow(a, MOD - 2);
}
private static long multiplyInternal(long a, long b) {
if (a > b) {
return multiplyInternal(b, a);
}
if (a == 0) {
return 0;
}
long ans = 0;
while (a > 0) {
long mask = a & CHUNK_MASK;
if (mask > 0) {
ans = add(ans, (mask * b) % MOD);
}
b = (b << CHUNK_SIZE) % MOD;
a >>= CHUNK_SIZE;
}
return ans;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | bf819c75456a25c4283b7fdd4262d520 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
private static final int START_TEST_CASE = 1;
private static final int MOD = 998244353;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final int K = io.nextInt();
final int Q = io.nextInt();
int[] X = new int[Q];
int[] Y = new int[Q];
for (int q = 0; q < Q; ++q) {
X[q] = io.nextInt();
Y[q] = io.nextInt();
}
int visible = 0;
HashSet<Integer> xDone = new HashSet<>();
HashSet<Integer> yDone = new HashSet<>();
for (int q = Q - 1; q >= 0; --q) {
if (xDone.contains(X[q]) && yDone.contains(Y[q])) {
continue;
}
if (xDone.size() >= N || yDone.size() >= M) {
continue;
}
xDone.add(X[q]);
yDone.add(Y[q]);
++visible;
}
io.println(LongModMath.modPow(K, visible));
}
/**
* Computes arithmetic operations modulo some constant MOD, should be a prime.
* It is guaranteed to not overflow, as long as the following requirements are satisfied.
* - MOD must be less than or equal to Long.MAX_VALUE / 2^CHUNK_SIZE.
* - All operands must be within the range [0, MOD).
*
* NOTE: It's recommended to copy the code in this class and inline it within your other functions,
* since it's cumbersome to write `LongModMath.multiply(a, LongModMath.add(b, c)`,
* compared to simply writing `multiply(a, add(b, c))`.
*/
public static class LongModMath {
// private static final long MOD = 3113510401L;
private static final long RAW_MULTIPLY_MAX = 3037000499L;
private static final int CHUNK_SIZE = Long.SIZE - Long.numberOfLeadingZeros(Long.MAX_VALUE / (MOD + 1) + 1);
private static final long CHUNK_MASK = (1L << CHUNK_SIZE) - 1;
// static {
// System.out.println(CHUNK_SIZE);
// System.out.println(CHUNK_MASK);
// }
private static long multiply(long a, long b) {
// if (MOD <= RAW_MULTIPLY_MAX) {
// return a * b % MOD;
// }
if (a > b) {
return multiply(b, a);
}
if (a == 0) {
return 0;
}
long ans = 0;
while (a > 0) {
long mask = a & CHUNK_MASK;
if (mask > 0) {
ans = add(ans, (mask * b) % MOD);
}
b = (b << CHUNK_SIZE) % MOD;
a >>= CHUNK_SIZE;
}
return ans;
}
private static long add(long a, long b) {
long ans = a + b;
if (ans >= MOD) {
ans -= MOD;
}
return ans;
}
private static long add(long... arr) {
long ans = 0;
for (long x : arr) {
ans = add(ans, x);
}
return ans;
}
/**
* Computes the value of (b ^ e) % MOD.
*/
public static long modPow(long b, long e) {
long p = b;
long ans = 1;
while (e > 0) {
if ((e & 1) == 1) {
ans = multiply(ans, p);
}
p = multiply(p, p);
e >>= 1;
}
return ans;
}
/**
* Computes the modular inverse, such that: ak % MOD = 1, for some k.
* See this page for details: http://rosettacode.org/wiki/Modular_inverse
*/
public static long modInverse(long a) {
return modPow(a, MOD - 2);
}
}
/**
* Computes all the primes up to the specified number.
*/
public static int[] primesTo(int n) {
ArrayList<Integer> primes = new ArrayList<Integer>();
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, 2, n + 1, true);
for (int i = 2; i < prime.length; i++) {
if (prime[i]) {
primes.add(i);
if ((long) i * i <= n) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
}
int[] ans = new int[primes.size()];
for (int i = 0; i < ans.length; ++i) {
ans[i] = primes.get(i);
}
return ans;
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 8a425ea7e4fad30386a3a7b7eaf8b947 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
private static final int START_TEST_CASE = 1;
private static final int MOD = 998244353;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final int K = io.nextInt();
final int Q = io.nextInt();
int[] X = new int[Q];
int[] Y = new int[Q];
for (int q = 0; q < Q; ++q) {
X[q] = io.nextInt();
Y[q] = io.nextInt();
}
int visible = 0;
HashSet<Integer> xDone = new HashSet<>();
HashSet<Integer> yDone = new HashSet<>();
for (int q = Q - 1; q >= 0; --q) {
if (xDone.contains(X[q]) && yDone.contains(Y[q])) {
continue;
}
if (xDone.size() >= N || yDone.size() >= M) {
continue;
}
xDone.add(X[q]);
yDone.add(Y[q]);
++visible;
}
io.println(LongModMath.modPow(K, visible));
}
/**
* Computes arithmetic operations modulo some constant MOD, should be a prime.
* It is guaranteed to not overflow, as long as the following requirements are satisfied.
* - MOD must be less than or equal to Long.MAX_VALUE / 2^CHUNK_SIZE.
* - All operands must be within the range [0, MOD).
*
* NOTE: It's recommended to copy the code in this class and inline it within your other functions,
* since it's cumbersome to write `LongModMath.multiply(a, LongModMath.add(b, c)`,
* compared to simply writing `multiply(a, add(b, c))`.
*/
public static class LongModMath {
private static final long RAW_MULTIPLY_MAX = 3037000499L;
private static final int CHUNK_SIZE = 31; //Long.SIZE - Long.numberOfLeadingZeros(Long.MAX_VALUE / (MOD + 1) + 1);
private static final int CHUNK_MASK = (1 << CHUNK_SIZE) - 1;
static {
// System.out.println(CHUNK_SIZE);
}
private static long multiply(long a, long b) {
if (a > b) {
return multiply(b, a);
}
if (a == 0) {
return 0;
}
long ans = 0;
while (a > 0) {
long mask = a & CHUNK_MASK;
if (mask > 0) {
ans = add(ans, (mask * b) % MOD);
}
b = (b << CHUNK_SIZE) % MOD;
a >>= CHUNK_SIZE;
}
return ans;
}
private static long add(long a, long b) {
long ans = a + b;
if (ans >= MOD) {
ans -= MOD;
}
return ans;
}
private static long add(long... arr) {
long ans = 0;
for (long x : arr) {
ans = add(ans, x);
}
return ans;
}
/**
* Computes the value of (b ^ e) % MOD.
*/
public static long modPow(long b, long e) {
long p = b;
long ans = 1;
while (e > 0) {
if ((e & 1) == 1) {
ans = multiply(ans, p);
}
p = multiply(p, p);
e >>= 1;
}
return ans;
}
/**
* Computes the modular inverse, such that: ak % MOD = 1, for some k.
* See this page for details: http://rosettacode.org/wiki/Modular_inverse
*/
public static long modInverse(long a) {
return modPow(a, MOD - 2);
}
}
/**
* Computes all the primes up to the specified number.
*/
public static int[] primesTo(int n) {
ArrayList<Integer> primes = new ArrayList<Integer>();
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, 2, n + 1, true);
for (int i = 2; i < prime.length; i++) {
if (prime[i]) {
primes.add(i);
if ((long) i * i <= n) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
}
int[] ans = new int[primes.size()];
for (int i = 0; i < ans.length; ++i) {
ans[i] = primes.get(i);
}
return ans;
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 836506d26de4b05e143cef94596666e7 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
private static final int START_TEST_CASE = 1;
private static final int MOD = 998244353;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final int K = io.nextInt();
final int Q = io.nextInt();
int[] X = new int[Q];
int[] Y = new int[Q];
for (int q = 0; q < Q; ++q) {
X[q] = io.nextInt();
Y[q] = io.nextInt();
}
int visible = 0;
HashSet<Integer> xDone = new HashSet<>();
HashSet<Integer> yDone = new HashSet<>();
for (int q = Q - 1; q >= 0; --q) {
if (xDone.contains(X[q]) && yDone.contains(Y[q])) {
continue;
}
if (xDone.size() >= N || yDone.size() >= M) {
continue;
}
xDone.add(X[q]);
yDone.add(Y[q]);
++visible;
}
io.println(LongModMath.modPow(K, visible));
}
/**
* Computes arithmetic operations modulo some constant MOD, should be a prime.
* It is guaranteed to not overflow, as long as the following requirements are satisfied.
* - MOD must be less than or equal to Long.MAX_VALUE / 2^CHUNK_SIZE.
* - All operands must be within the range [0, MOD).
*
* NOTE: It's recommended to copy the code in this class and inline it within your other functions,
* since it's cumbersome to write `LongModMath.multiply(a, LongModMath.add(b, c)`,
* compared to simply writing `multiply(a, add(b, c))`.
*/
public static class LongModMath {
private static final int CHUNK_SIZE = 3;
private static final int CHUNK_MASK = (1 << CHUNK_SIZE) - 1;
private static long multiply(long a, long b) {
if (a > b) {
return multiply(b, a);
}
if (a == 0) {
return 0;
}
long ans = 0;
while (a > 0) {
long mask = a & CHUNK_MASK;
if (mask > 0) {
ans = add(ans, (mask * b) % MOD);
}
b = (b << CHUNK_SIZE) % MOD;
a >>= CHUNK_SIZE;
}
return ans;
}
private static long add(long a, long b) {
long ans = a + b;
if (ans >= MOD) {
ans -= MOD;
}
return ans;
}
private static long add(long... arr) {
long ans = 0;
for (long x : arr) {
ans = add(ans, x);
}
return ans;
}
/**
* Computes the value of (b ^ e) % MOD.
*/
public static long modPow(long b, long e) {
long p = b;
long ans = 1;
while (e > 0) {
if ((e & 1) == 1) {
ans = multiply(ans, p);
}
p = multiply(p, p);
e >>= 1;
}
return ans;
}
/**
* Computes the modular inverse, such that: ak % MOD = 1, for some k.
* See this page for details: http://rosettacode.org/wiki/Modular_inverse
*/
public static long modInverse(long a) {
return modPow(a, MOD - 2);
}
}
/**
* Computes all the primes up to the specified number.
*/
public static int[] primesTo(int n) {
ArrayList<Integer> primes = new ArrayList<Integer>();
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, 2, n + 1, true);
for (int i = 2; i < prime.length; i++) {
if (prime[i]) {
primes.add(i);
if ((long) i * i <= n) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
}
int[] ans = new int[primes.size()];
for (int i = 0; i < ans.length; ++i) {
ans[i] = primes.get(i);
}
return ans;
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 8a981bbf428af99debd9475fc57b7998 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.math.BigInteger;
import java.io.*;
@SuppressWarnings("unchecked")
public class Main implements Runnable {
static FastReader in;
static PrintWriter out;
static int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
static void p(Object o) {
out.print(o);
}
static void pn(Object o) {
out.println(o);
}
static void pni(Object o) {
out.println(o);
out.flush();
}
static String n() throws Exception {
return in.next();
}
static String nln() throws Exception {
return in.nextLine();
}
static int ni() throws Exception {
return Integer.parseInt(in.next());
}
static long nl() throws Exception {
return Long.parseLong(in.next());
}
static double nd() throws Exception {
return Double.parseDouble(in.next());
}
static class FastReader {
static BufferedReader br;
static StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
static long power(long a, long b) {
if (a == 0L)
return 0L;
if (b == 0)
return 1;
long val = power(a, b / 2);
val = val * val;
if ((b % 2) != 0)
val = val * a;
return val;
}
static long power(long a, long b, long mod) {
if (a == 0L)
return 0L;
if (b == 0)
return 1;
long val = power(a, b / 2L, mod) % mod;
val = (val * val) % mod;
if ((b % 2) != 0)
val = (val * a) % mod;
return val;
}
static ArrayList<Long> prime_factors(long n) {
ArrayList<Long> ans = new ArrayList<Long>();
while (n % 2 == 0) {
ans.add(2L);
n /= 2L;
}
for (long i = 3; i <= Math.sqrt(n); i++) {
while (n % i == 0) {
ans.add(i);
n /= i;
}
}
if (n > 2) {
ans.add(n);
}
return ans;
}
static void sort(ArrayList<Long> a) {
Collections.sort(a);
}
static void reverse_sort(ArrayList<Long> a) {
Collections.sort(a, Collections.reverseOrder());
}
static void swap(long[] a, int i, int j) {
long temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(List<Long> a, int i, int j) {
long temp = a.get(i);
a.set(j, a.get(i));
a.set(j, temp);
}
static void sieve(boolean[] prime) {
int n = prime.length - 1;
Arrays.fill(prime, true);
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i) {
prime[j] = false;
}
}
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
/*
* ----------------------------------------------------Sorting------------------
* ------------------------------------------------
*/
public static void sort(long[] arr, int l, int r) {
if (l >= r)
return;
int mid = (l + r) / 2;
sort(arr, l, mid);
sort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
public static void sort(int[] arr, int l, int r) {
if (l >= r)
return;
int mid = (l + r) / 2;
sort(arr, l, mid);
sort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
static void merge(int[] arr, int l, int mid, int r) {
int[] left = new int[mid - l + 1];
int[] right = new int[r - mid];
for (int i = l; i <= mid; i++) {
left[i - l] = arr[i];
}
for (int i = mid + 1; i <= r; i++) {
right[i - (mid + 1)] = arr[i];
}
int left_start = 0;
int right_start = 0;
int left_length = mid - l + 1;
int right_length = r - mid;
int temp = l;
while (left_start < left_length && right_start < right_length) {
if (left[left_start] < right[right_start]) {
arr[temp] = left[left_start++];
} else {
arr[temp] = right[right_start++];
}
temp++;
}
while (left_start < left_length) {
arr[temp++] = left[left_start++];
}
while (right_start < right_length) {
arr[temp++] = right[right_start++];
}
}
static void merge(long[] arr, int l, int mid, int r) {
long[] left = new long[mid - l + 1];
long[] right = new long[r - mid];
for (int i = l; i <= mid; i++) {
left[i - l] = arr[i];
}
for (int i = mid + 1; i <= r; i++) {
right[i - (mid + 1)] = arr[i];
}
int left_start = 0;
int right_start = 0;
int left_length = mid - l + 1;
int right_length = r - mid;
int temp = l;
while (left_start < left_length && right_start < right_length) {
if (left[left_start] < right[right_start]) {
arr[temp] = left[left_start++];
} else {
arr[temp] = right[right_start++];
}
temp++;
}
while (left_start < left_length) {
arr[temp++] = left[left_start++];
}
while (right_start < right_length) {
arr[temp++] = right[right_start++];
}
}
static HashMap<Long, Integer> map_prime_factors(long n) {
HashMap<Long, Integer> map = new HashMap<>();
while (n % 2 == 0) {
map.put(2L, map.getOrDefault(2L, 0) + 1);
n /= 2L;
}
for (long i = 3; i <= Math.sqrt(n); i++) {
while (n % i == 0) {
map.put(i, map.getOrDefault(i, 0) + 1);
n /= i;
}
}
if (n > 2) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
return map;
}
static List<Long> divisor(long n) {
List<Long> ans = new ArrayList<>();
ans.add(1L);
long count = 0;
for (long i = 2L; i * i <= n; i++) {
if (n % i == 0) {
if (i == n / i)
ans.add(i);
else {
ans.add(i);
ans.add(n / i);
}
}
}
return ans;
}
// static void smallest_prime_factor(int n) {
// smallest_prime_factor[1] = 1;
// for (int i = 2; i <= n; i++) {
// if (smallest_prime_factor[i] == 0) {
// smallest_prime_factor[i] = i;
// for (int j = i * i; j <= n; j += i) {
// if (smallest_prime_factor[j] == 0) {
// smallest_prime_factor[j] = i;
// }
// }
// }
// }
// }
// static int[] smallest_prime_factor;
// static int count = 1;
// static int[] p = new int[100002];
// static long[] flat_tree = new long[300002];
// static int[] in_time = new int[1000002];
// static int[] out_time = new int[1000002];
// static long[] subtree_gcd = new long[100002];
// static int w = 0;
// static boolean poss = true;
/*
* (a^b^c)%mod
* Using fermats Little theorem
* x^(mod-1)=1(mod)
* so b^c can be written as b^c=x*(mod-1)+y
* then (a^(x*(mod-1)+y))%mod=(a^(x*(mod-1))*a^(y))mod
* the term (a^(x*(mod-1)))%mod=a^(mod-1)*a^(mod-1)
*
*/
// ---------------------------------------------------Segment_Tree----------------------------------------------------------------//
// static class comparator implements Comparator<node> {
// public int compare(node a, node b) {
// return a.a - b.a > 0 ? 1 : -1;
// }
// }
static class Segment_Tree {
private long[] segment_tree;
public Segment_Tree(int n) {
this.segment_tree = new long[4 * n + 1];
}
void build(int index, int left, int right, int[] a) {
if (left == right) {
segment_tree[index] = a[left];
return;
}
int mid = (left + right) / 2;
build(2 * index + 1, left, mid, a);
build(2 * index + 2, mid + 1, right, a);
segment_tree[index] = segment_tree[2 * index + 1] + segment_tree[2 * index + 2];
}
long query(int index, int left, int right, int l, int r) {
if (left > right)
return 0;
if (left >= l && r >= right) {
return segment_tree[index];
}
if (l > right || left > r)
return 0;
int mid = (left + right) / 2;
return query(2 * index + 1, left, mid, l, r) + query(2 * index + 2, mid + 1, right, l, r);
}
void update(int index, int left, int right, int node, int val) {
if (left == right) {
segment_tree[index] += val;
return;
}
int mid = (left + right) / 2;
if (node <= mid)
update(2 * index + 1, left, mid, node, val);
else
update(2 * index + 2, mid + 1, right, node, val);
segment_tree[index] = segment_tree[2 * index + 1] + segment_tree[2 * index + 2];
}
}
static class min_Segment_Tree {
private long[] segment_tree;
public min_Segment_Tree(int n) {
this.segment_tree = new long[4 * n + 1];
}
void build(int index, int left, int right, int[] a) {
if (left == right) {
segment_tree[index] = a[left];
return;
}
int mid = (left + right) / 2;
build(2 * index + 1, left, mid, a);
build(2 * index + 2, mid + 1, right, a);
segment_tree[index] = Math.min(segment_tree[2 * index + 1], segment_tree[2 * index + 2]);
}
long query(int index, int left, int right, int l, int r) {
if (left > right)
return Integer.MAX_VALUE;
if (left >= l && r >= right) {
return segment_tree[index];
}
if (l > right || left > r)
return Integer.MAX_VALUE;
int mid = (left + right) / 2;
return Math.min(query(2 * index + 1, left, mid, l, r), query(2 * index + 2, mid + 1, right, l, r));
}
}
static class max_Segment_Tree {
public long[] segment_tree;
public max_Segment_Tree(int n) {
this.segment_tree = new long[4 * n + 1];
}
void build(int index, int left, int right, int[] a) {
// pn(index+" "+left+" "+right);
if (left == right) {
segment_tree[index] = a[left];
return;
}
int mid = (left + right) / 2;
build(2 * index + 1, left, mid, a);
build(2 * index + 2, mid + 1, right, a);
segment_tree[index] = Math.max(segment_tree[2 * index + 1], segment_tree[2 * index + 2]);
}
long query(int index, int left, int right, int l, int r) {
if (left >= l && r >= right) {
return segment_tree[index];
}
if (l > right || left > r)
return Integer.MIN_VALUE;
int mid = (left + right) / 2;
long max = Math.max(query(2 * index + 1, left, mid, l, r), query(2 * index + 2, mid + 1, right, l, r));
// pn(left+" "+right+" "+max);
return max;
}
}
// ------------------------------------------------------ DSU
// --------------------------------------------------------------------//
static class dsu {
private int[] parent;
private int[] rank;
private int[] size;
public dsu(int n) {
this.parent = new int[n + 1];
this.rank = new int[n + 1];
this.size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 1;
size[i] = 1;
}
}
int findParent(int a) {
if (parent[a] == a)
return a;
else
return parent[a] = findParent(parent[a]);
}
void join(int a, int b) {
int parent_a = findParent(a);
int parent_b = findParent(b);
if (parent_a == parent_b)
return;
if (rank[parent_a] > rank[parent_b]) {
parent[parent_b] = parent_a;
size[parent_a] += size[parent_b];
} else if (rank[parent_a] < rank[parent_b]) {
parent[parent_a] = parent_b;
size[parent_b] += size[parent_a];
} else {
parent[parent_a] = parent_b;
size[parent_b] += size[parent_a];
rank[parent_b]++;
}
}
}
// ------------------------------------------------Comparable---------------------------------------------------------------------//
public static class rectangle {
int x1, x3, y1, y3;// lower left and upper rigth coordinates
int x2, y2, x4, y4;// remaining coordinates
/*
* (x4,y4) (x3,y3)
* ____________
* | |
* |____________|
*
* (x1,y1) (x2,y2)
*/
public rectangle(int x1, int y1, int x3, int y3) {
this.x1 = x1;
this.y1 = y1;
this.x3 = x3;
this.y3 = y3;
this.x2 = x3;
this.y2 = y1;
this.x4 = x1;
this.y4 = y3;
}
public long area() {
if (x3 < x1 || y3 < y1)
return 0;
return (long) Math.abs(x1 - x3) * (long) Math.abs(y1 - y3);
}
}
static long intersection(rectangle a, rectangle b) {
if (a.x3 < a.x1 || a.y3 < a.y1 || b.x3 < b.x1 || b.y3 < b.y1)
return 0;
long l1 = ((long) Math.min(a.x3, b.x3) - (long) Math.max(a.x1, b.x1));
long l2 = ((long) Math.min(a.y3, b.y3) - (long) Math.max(a.y1, b.y1));
if (l1 < 0 || l2 < 0)
return 0;
long area = ((long) Math.min(a.x3, b.x3) - (long) Math.max(a.x1, b.x1))
* ((long) Math.min(a.y3, b.y3) - (long) Math.max(a.y1, b.y1));
if (area < 0)
return 0;
return area;
}
static class pair implements Comparable<pair> {
int a;
int b;
int dir;
public pair(int a, int b, int dir) {
this.a = a;
this.b = b;
this.dir = dir;
}
public int compareTo(pair p) {
// if (this.b == Integer.MIN_VALUE || p.b == Integer.MIN_VALUE)
// return (int) (this.index - p.index);
return (int) (this.a - p.a);
}
}
static class pair2 implements Comparable<pair2> {
long a;
int index;
public pair2(long a, int index) {
this.a = a;
this.index = index;
}
public int compareTo(pair2 p) {
return (int) (this.a - p.a);
}
}
static class node implements Comparable<node> {
int l;
int r;
public node(int l, int r) {
this.l = l;
this.r = r;
}
public int compareTo(node a) {
return this.l - a.l;
}
}
// static int ans = 0;
static long ans = 0;
static int leaf = 0;
static boolean poss = true;
static long mod = 998244353L;
static int[] dx = { -1, 0, 0, 1 };
static int[] dy = { 0, -1, 1, 0 };
static long[] sub = new long[300001];
static boolean cycle;
static int count = 0;
public static void main(String[] args) throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int tc = ni();
while (tc-- > 0) {
int n = ni();
int m=ni();
long k=ni();
int q=ni();
Set<Integer> row=new HashSet<>();
Set<Integer> col=new HashSet<>();
int[][] queries=new int[q][2];
for(int i=0;i<q;i++){
int x=ni()-1;
int y=ni()-1;
queries[i][0]=x;
queries[i][1]=y;
}
long count=0;
ans=1;
for(int i=q-1;i>=0;i--){
int x=queries[i][0];
int y=queries[i][1];
boolean done=false;
if(!row.contains(x) && col.size()!=m){
row.add(x);
done=true;
}
if(!col.contains(y) && row.size()!=n){
col.add(y);
done=true;
}
if(done){
count++;
}
}
// pn(set.size());
pn(power(k, count, mod));
}
out.flush();
out.close();
}
public void run() {
try {
} catch (Exception e) {
}
}
static void dfs(int i, int p, boolean[] visited, List<List<Integer>> arr) {
visited[i] = true;
// count++;
// pn(i);
for (int nei : arr.get(i)) {
if (nei == p)
continue;
if (visited[nei]) {
cycle = true;
continue;
}
dfs(nei, i, visited, arr);
}
}
static boolean inside(int i, int j, int n, int m) {
if (i >= 0 && j >= 0 && i < n && j < m)
return true;
return false;
}
static int binary_search(int[] a, int val) {
int l = 0;
int r = a.length - 1;
int ans = 0;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
return ans;
}
static int[] longest_common_prefix(String s) {
int m = s.length();
int[] lcs = new int[m];
int len = 0;
int i = 1;
lcs[0] = 0;
while (i < m) {
if (s.charAt(i) == s.charAt(len)) {
lcs[i++] = ++len;
} else {
if (len == 0) {
lcs[i] = 0;
i++;
} else
len = lcs[len - 1];
}
}
return lcs;
}
static void swap(char[] a, char[] b, int i, int j) {
char temp = a[i];
a[i] = b[j];
b[j] = temp;
}
static void factorial(long[] fact, long[] fact_inv, int n, long mod) {
fact[0] = 1;
for (int i = 1; i < n; i++) {
fact[i] = (i * fact[i - 1]) % mod;
}
for (int i = 0; i < n; i++) {
fact_inv[i] = power(fact[i], mod - 2, mod);// (1/x)%m can be calculated by fermat's little theoram which is
// (x**(m-2))%m when m is prime
}
// (a^(b^c))%m is equal to, let res=(b^c)%(m-1) then (a^res)%m
// https://www.geeksforgeeks.org/find-power-power-mod-prime/?ref=rp
}
static void find(int i, int n, int[] row, int[] col, int[] d1, int[] d2) {
if (i >= n) {
ans++;
return;
}
for (int j = 0; j < n; j++) {
if (col[j] == 0 && d1[i - j + n - 1] == 0 && d2[i + j] == 0) {
col[j] = 1;
d1[i - j + n - 1] = 1;
d2[i + j] = 1;
find(i + 1, n, row, col, d1, d2);
col[j] = 0;
d1[i - j + n - 1] = 0;
d2[i + j] = 0;
}
}
}
static int answer(int l, int r, int[][] dp) {
if (l > r)
return 0;
if (l == r) {
dp[l][r] = 1;
return 1;
}
if (dp[l][r] != -1)
return dp[l][r];
int val = Integer.MIN_VALUE;
int mid = l + (r - l) / 2;
val = 1 + Math.max(answer(l, mid - 1, dp), answer(mid + 1, r, dp));
return dp[l][r] = val;
}
// static long find(String s, int i, int n, long[] dp) {
// // pn(i);
// if (i >= n)
// return 1L;
// if (s.charAt(i) == '0')
// return 0;
// if (i == n - 1)
// return 1L;
// if (dp[i] != -1)
// return dp[i];
// if (s.substring(i, i + 2).equals("10") || s.substring(i, i + 2).equals("20"))
// {
// return dp[i] = (find(s, i + 2, n, dp)) % mod;
// }
// if ((s.charAt(i) == '1' || (s.charAt(i) == '2' && s.charAt(i + 1) - '0' <=
// 6))
// && ((i + 2 < n ? (s.charAt(i + 2) != '0' ? true : false) : (i + 2 == n ? true
// : false)))) {
// return dp[i] = (find(s, i + 1, n, dp) + find(s, i + 2, n, dp)) % mod;
// } else
// return dp[i] = (find(s, i + 1, n, dp)) % mod;
static void print(int[] a) {
for (int i = 0; i < a.length; i++)
p(a[i] + " ");
pn("");
}
static long count(long n) {
long count = 0;
while (n != 0) {
count += n % 10;
n /= 10;
}
return count;
}
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static int LcsOfPrefix(String a, String b) {
int i = 0;
int j = 0;
int count = 0;
while (i < a.length() && j < b.length()) {
if (a.charAt(i) == b.charAt(j)) {
j++;
count++;
}
i++;
}
return a.length() + b.length() - 2 * count;
}
static void reverse(int[] a, int n) {
for (int i = 0; i < n / 2; i++) {
int temp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = temp;
}
}
static char get_char(int a) {
return (char) (a + 'A');
}
static int find1(int[] a, int val) {
int ans = -1;
int l = 0;
int r = a.length - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
l = mid + 1;
ans = mid;
} else
r = mid - 1;
}
return ans;
}
static int find2(int[] a, int val) {
int l = 0;
int r = a.length - 1;
int ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
return ans;
}
// static void dfs(List<List<Integer>> arr, int node, int parent, long[] val) {
// p[node] = parent;
// in_time[node] = count;
// flat_tree[count] = val[node];
// subtree_gcd[node] = val[node];
// count++;
// for (int adj : arr.get(node)) {
// if (adj == parent)
// continue;
// dfs(arr, adj, node, val);
// subtree_gcd[node] = gcd(subtree_gcd[adj], subtree_gcd[node]);
// }
// out_time[node] = count;
// flat_tree[count] = val[node];
// count++;
// }
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 71a4a46398bd728ff4bf1ecd14e5b61e | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class p4
{
BufferedReader br;
StringTokenizer st;
BufferedWriter bw;
public static void main(String[] args)throws Exception
{
new p4().run();
}
void run()throws IOException
{
br = new BufferedReader(new InputStreamReader(System.in));
bw=new BufferedWriter(new OutputStreamWriter(System.out));
solve();
}
void solve() throws IOException
{
// for(int i=100000-1;++i<=100000;)
// {
// for(int j=0;++j<2;)
// {
// long ans=nPowerM(i, 100000);
// System.out.println(i+" power 100000 is "+ans);
// }
// }
int t=ni();
int a[]=new int[200005];
int b[]=new int[200005];
while(t-->0)
{
int n=ni();
int m=ni();
int k=ni();
int q=ni();
int d1[]=new int[q];
int d2[]=new int[q];
for(int i=-1;++i<q;)
{
d1[i]=ni()-1;
d2[i]=ni()-1;
}
int x=0;
int j=0;
for(int i=q;--i>=0;)
{
if(a[d1[i]]==0 || b[d2[i]]==0)
{
if(a[d1[i]]==0)
{
a[d1[i]]=1;
n--;
}
if(b[d2[i]]==0)
{
b[d2[i]]=1;
m--;
}
x++;
}
j=i;
if(n==0 || m==0)
break;
}
for(int i=q;--i>=j;)
{
a[d1[i]]=0;
b[d2[i]]=0;
}
long ans=nPowerM(k, x);
bw.write(ans+"\n");
}
bw.flush();
}
public long nPowerM(int n, int m)
{
if(m==0)
return 1L;
int mod=998244353;
long ans=nPowerM(n, m/2);
ans*=ans;
ans%=mod;
if(m%2==1)
{
ans*=n;
ans%=mod;
}
ans%=mod;
return ans;
}
public long mod(long a)
{
int mod=1000000007;
//int mod=998244353;
a%=mod;
if(a<0)
a+=mod;
return a;
}
public static class data
{
int a,b;
public data(int a, int b)
{
this.a=a;
this.b=b;
}
}
public data[] dataArray(int n)
{
data d[]=new data[n];
for(int i=-1;++i<n;)
d[i]=new data(ni(), ni());
return d;
}
/////////////////////////////////////// FOR INPUT ///////////////////////////////////////
int[] nai(int n) { int a[]=new int[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;}
Integer[] naI(int n) { Integer a[]=new Integer[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;}
long[] nal(int n) { long a[]=new long[n]; for(int i=-1;++i<n;)a[i]=nl(); return a;}
char[] nac() {char c[]=nextLine().toCharArray(); return c;}
char [][] nmc(int n) {char c[][]=new char[n][]; for(int i=-1;++i<n;)c[i]=nac(); return c;}
int[][] nmi(int r, int c) {int a[][]=new int[r][c]; for(int i=-1;++i<r;)a[i]=nai(c); return a;}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
byte nb() { return Byte.parseByte(next()); }
short ns() { return Short.parseShort(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String nextLine()
{
String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 12e100ddfec3beb542b444da1599077b | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes |
import java.io.*;
import java.util.*;
public final class Main {
//int 2e9 - long 9e18
static PrintWriter out = new PrintWriter(System.out);
static FastReader in = new FastReader();
static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(0, 1), new Pair(1, 0), new Pair(0, -1)};
static int mod = (int) (1e9 + 7);
static int mod2 = 998244353;
public static void main(String[] args) {
int tt = i();
while (tt-- > 0) {
solve();
}
out.flush();
}
public static void solve() {
int n = i();
int m = i();
int k = i();
int q = i();
int[][] qq = new int[q][2];
for (int i = 0; i < q; i++) {
int a = i() - 1;
int b = i() - 1;
qq[i][0] = a;
qq[i][1] = b;
}
Set<Integer> xl = new HashSet<>();
Set<Integer> yl = new HashSet<>();
int cnt = 0;
for (int i = q - 1; i >= 0; i--) {
boolean flag = false;
if (yl.size() < m && !xl.contains(qq[i][0])) {
xl.add(qq[i][0]);
flag = true;
}
if (xl.size() < n && !yl.contains(qq[i][1])) {
yl.add(qq[i][1]);
flag = true;
}
if (flag) {
cnt++;
}
}
out.println(pow(k, cnt, mod2));
}
// (10,5) = 2 ,(11,5) = 3
static long upperDiv(long a, long b) {
return (a / b) + ((a % b == 0) ? 0 : 1);
}
static long sum(int[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static int[] preint(int[] a) {
int[] pre = new int[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static long[] pre(int[] a) {
long[] pre = new long[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static long[] post(int[] a) {
long[] post = new long[a.length + 1];
post[0] = 0;
for (int i = 0; i < a.length; i++) {
post[i + 1] = post[i] + a[a.length - 1 - i];
}
return post;
}
static long[] pre(long[] a) {
long[] pre = new long[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static void print(char A[]) {
for (char c : A) {
out.print(c);
}
out.println();
}
static void print(boolean A[]) {
for (boolean c : A) {
out.print(c + " ");
}
out.println();
}
static void print(int A[]) {
for (int c : A) {
out.print(c + " ");
}
out.println();
}
static void print(long A[]) {
for (long i : A) {
out.print(i + " ");
}
out.println();
}
static void print(List<Integer> A) {
for (int a : A) {
out.print(a + " ");
}
}
static int i() {
return in.nextInt();
}
static long l() {
return in.nextLong();
}
static double d() {
return in.nextDouble();
}
static String s() {
return in.nextLine();
}
static String c() {
return in.next();
}
static int[][] inputWithIdx(int N) {
int A[][] = new int[N][2];
for (int i = 0; i < N; i++) {
A[i] = new int[]{i, in.nextInt()};
}
return A;
}
static int[] input(int N) {
int A[] = new int[N];
for (int i = 0; i < N; i++) {
A[i] = in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[] = new long[N];
for (int i = 0; i < A.length; i++) {
A[i] = in.nextLong();
}
return A;
}
static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long GCD(long a, long b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long LCM(int a, int b) {
return (long) a / GCD(a, b) * b;
}
static long LCM(long a, long b) {
return a / GCD(a, b) * b;
}
// find highest i which satisfy a[i]<=x
static int lowerbound(int[] a, int x) {
int l = 0;
int r = a.length - 1;
while (l < r) {
int m = (l + r + 1) / 2;
if (a[m] <= x) {
l = m;
} else {
r = m - 1;
}
}
return l;
}
static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
}
static void shuffleAndSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static void shuffleAndSort(int[][] arr, Comparator<? super int[]> comparator) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int[] temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr, comparator);
}
static void shuffleAndSort(long[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
long temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static boolean isPerfectSquare(double number) {
double sqrt = Math.sqrt(number);
return ((sqrt - Math.floor(sqrt)) == 0);
}
static void swap(int A[], int a, int b) {
int t = A[a];
A[a] = A[b];
A[b] = t;
}
static void swap(char A[], int a, int b) {
char t = A[a];
A[a] = A[b];
A[b] = t;
}
static long pow(long a, long b, int mod) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow = (pow * x) % mod;
}
x = (x * x) % mod;
b /= 2;
}
return pow;
}
static long pow(long a, long b) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow *= x;
}
x = x * x;
b /= 2;
}
return pow;
}
static long modInverse(long x, int mod) {
return pow(x, mod - 2, mod);
}
static boolean isPrime(long 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;
}
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
public static void reverse(int[] arr) {
for (int i = 0; i < arr.length / 2; i++) {
int tmp = arr[i];
arr[arr.length - 1 - i] = tmp;
arr[i] = arr[arr.length - 1 - i];
}
}
public static String repeat(char ch, int repeat) {
if (repeat <= 0) {
return "";
}
final char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
public static int[] manacher(String s) {
char[] chars = s.toCharArray();
int n = s.length();
int[] d1 = new int[n];
for (int i = 0, l = 0, r = -1; i < n; i++) {
int k = (i > r) ? 1 : Math.min(d1[l + r - i], r - i + 1);
while (0 <= i - k && i + k < n && chars[i - k] == chars[i + k]) {
k++;
}
d1[i] = k--;
if (i + k > r) {
l = i - k;
r = i + k;
}
}
return d1;
}
public static int[] kmp(String s) {
int n = s.length();
int[] res = new int[n];
for (int i = 1; i < n; ++i) {
int j = res[i - 1];
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = res[j - 1];
}
if (s.charAt(i) == s.charAt(j)) {
++j;
}
res[i] = j;
}
return res;
}
}
class Pair {
int i;
int j;
Pair(int i, int j) {
this.i = i;
this.j = j;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
return i == pair.i && j == pair.j;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
}
class ThreePair {
int i;
int j;
int k;
ThreePair(int i, int j, int k) {
this.i = i;
this.j = j;
this.k = k;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ThreePair pair = (ThreePair) o;
return i == pair.i && j == pair.j && k == pair.k;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
}
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;
}
}
class Node {
int val;
public Node(int val) {
this.val = val;
}
}
class ST {
int n;
Node[] st;
ST(int n) {
this.n = n;
st = new Node[4 * Integer.highestOneBit(n)];
}
void build(Node[] nodes) {
build(0, 0, n - 1, nodes);
}
private void build(int id, int l, int r, Node[] nodes) {
if (l == r) {
st[id] = nodes[l];
return;
}
int mid = (l + r) >> 1;
build((id << 1) + 1, l, mid, nodes);
build((id << 1) + 2, mid + 1, r, nodes);
st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]);
}
void update(int i, Node node) {
update(0, 0, n - 1, i, node);
}
private void update(int id, int l, int r, int i, Node node) {
if (i < l || r < i) {
return;
}
if (l == r) {
st[id] = node;
return;
}
int mid = (l + r) >> 1;
update((id << 1) + 1, l, mid, i, node);
update((id << 1) + 2, mid + 1, r, i, node);
st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]);
}
Node get(int x, int y) {
return get(0, 0, n - 1, x, y);
}
private Node get(int id, int l, int r, int x, int y) {
if (x > r || y < l) {
return new Node(0);
}
if (x <= l && r <= y) {
return st[id];
}
int mid = (l + r) >> 1;
return comb(get((id << 1) + 1, l, mid, x, y), get((id << 1) + 2, mid + 1, r, x, y));
}
Node comb(Node a, Node b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
return new Node(GCD(a.val, b.val));
}
static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 6a39c9a8924ba1582a950c805a156ff5 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class A {
public static void main(String[] args) {
new A().run();
}
BufferedReader br;
PrintWriter out;
long mod = (long) (1e9 + 7), inf = (long) (3e18);
class pair {
int F, S;
pair(int f, int s) {
F = f; S = s;
}
}
// ---------------------- solve --------------------------
void solve() {
int t = ni();
while(t-- > 0) {
//TODO:
int n= ni();
int m= ni();
int k= ni();
int q= ni();
int[][] a= new int[q][2];
for(int i=0; i<q; i++){
a[i][0]=ni();
a[i][1]=ni();
}
HashSet<Integer> row = new HashSet<>();
HashSet<Integer> col= new HashSet<>();
long count=0;
for(int i=q-1; i>=0; i--){
int x=a[i][0];
int y= a[i][1];
if ((!row.contains(x) || !col.contains(y)) && row.size() != n && col.size() != m) {
count++;
}
row.add(x);
col.add(y);
}
long md=1l*998244353;
long ans = pow(k, count, md);
out.println(ans);
}
}
// -------- I/O Template -------------
public long pow(long A, long B, long C) {
if(A==0) return 0l;
if(B==0) return 1l;
long n=pow(A, B/2, C);
if(B%2==0){
return (long)(1l*(n*n)%C + C )%C;
}
else{
return (long)(((1l*n*n)%C * A)%C +C)%C;
}
}
char nc() {
return ns().charAt(0);
}
String nLine() {
try {
return br.readLine();
} catch(IOException e) {
return "-1";
}
}
double nd() {
return Double.parseDouble(ns());
}
long nl() {
return Long.parseLong(ns());
}
int ni() {
return Integer.parseInt(ns());
}
int[] na(int n) {
int a[] = new int[n];
for(int i = 0; i < n; i++) a[i] = ni();
return a;
}
StringTokenizer ip;
String ns() {
if(ip == null || !ip.hasMoreTokens()) {
try {
ip = new StringTokenizer(br.readLine());
if(ip == null || !ip.hasMoreTokens())
ip = new StringTokenizer(br.readLine());
} catch(IOException e) {
throw new InputMismatchException();
}
}
return ip.nextToken();
}
void run() {
try {
if (System.getProperty("ONLINE_JUDGE") == null) {
br = new BufferedReader(new FileReader("/media/ankanchanda/Data1/WORKPLACE/DS and CP/Competitive Programming/VSCODE/IO/input.txt"));
out = new PrintWriter("/media/ankanchanda/Data1/WORKPLACE/DS and CP/Competitive Programming/VSCODE/IO/output.txt");
} else {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
solve();
out.flush();
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 59f68c14c6056fc988c1df4eda563976 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.math.BigInteger;
public final class A
{
static PrintWriter out = new PrintWriter(System.out);
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
static int g[][];
static long mod=(long) 998244353,INF=Long.MAX_VALUE;
static boolean set[];
static int max=0;
static int lca[][];
static int par[],col[],D[];
static long fact[];
static int size[],N;
static int dp[][],dp2[][];
static ArrayList [] seg;
public static void main(String args[])throws IOException
{
/*
* star,rope,TPST
* BS,LST,MS,MQ
*/
int T=i();
outer:while(T-->0)
{
int N=i(),M=i();
long K=l(),Q=l();
// int row[]=new int[N+1];
// int col[]=new int[M+1];
// HashSet<Integer> set=new HashSet<>();
// Arrays.fill(row, -1);
// Arrays.fill(col, -1);
int X[][]=new int[(int)(Q+1)][2];
for(int i=1; i<=Q; i++)
{
int r=i(),c=i();
X[i][0]=r;
X[i][1]=c;
}
long a=0;
boolean R[]=new boolean[N+1],C[]=new boolean[M+1];
int RR=0,CC=0;
long tot=0;
long ss=((long)N)*((long)M);
for(int i=(int)Q; i>=1; i--)
{
int r=X[i][0],c=X[i][1];
if(R[r] && C[c])continue;
boolean coloured=false;
if(R[r]==false)
{
int x=M-CC;
if(x>0)
{
coloured=true;
tot+=x;
}
R[r]=true;
RR++;
}
if(C[c]==false)
{
int x=N-RR;
if(x>0)
{
coloured=true;
tot+=x;
}
C[c]=true;
CC++;
}
// System.out.println(tot);
if(coloured)a++;
if(tot==ss)break;
}
long s=pow(K,a);
ans.append(s+"\n");
}
out.println(ans);
out.close();
}
static long kadane(long A[])
{
long lsum=A[0],gsum=0;
gsum=Math.max(gsum, lsum);
for(int i=1; i<A.length; i++)
{
lsum=Math.max(lsum+A[i],A[i]);
gsum=Math.max(gsum,lsum);
}
return gsum;
}
public static boolean pal(int i)
{
StringBuilder sb=new StringBuilder();
StringBuilder rev=new StringBuilder();
int p=1;
while(p<=i)
{
if((i&p)!=0)
{
sb.append("1");
}
else sb.append("0");
p<<=1;
}
rev=new StringBuilder(sb.toString());
rev.reverse();
if(i==8)System.out.println(sb+" "+rev);
return (sb.toString()).equals(rev.toString());
}
public static void reverse(int i,int j,int A[])
{
while(i<j)
{
int t=A[i];
A[i]=A[j];
A[j]=t;
i++;
j--;
}
}
public static int ask(int a,int b,int c)
{
System.out.println("? "+a+" "+b+" "+c);
return i();
}
static int[] reverse(int A[],int N)
{
int B[]=new int[N];
for(int i=N-1; i>=0; i--)
{
B[N-i-1]=A[i];
}
return B;
}
static boolean isPalin(char X[])
{
int i=0,j=X.length-1;
while(i<=j)
{
if(X[i]!=X[j])return false;
i++;
j--;
}
return true;
}
static int distance(int a,int b)
{
int d=D[a]+D[b];
int l=LCA(a,b);
l=2*D[l];
return d-l;
}
static int LCA(int a,int b)
{
if(D[a]<D[b])
{
int t=a;
a=b;
b=t;
}
int d=D[a]-D[b];
int p=1;
for(int i=0; i>=0 && p<=d; i++)
{
if((p&d)!=0)
{
a=lca[a][i];
}
p<<=1;
}
if(a==b)return a;
for(int i=max-1; i>=0; i--)
{
if(lca[a][i]!=-1 && lca[a][i]!=lca[b][i])
{
a=lca[a][i];
b=lca[b][i];
}
}
return lca[a][0];
}
static void dfs(int n,int p)
{
lca[n][0]=p;
if(p!=-1)D[n]=D[p]+1;
for(int c:g[n])
{
if(c!=p)
{
dfs(c,n);
}
}
}
static int[] prefix_function(char X[])//returns pi(i) array
{
int N=X.length;
int pre[]=new int[N];
for(int i=1; i<N; i++)
{
int j=pre[i-1];
while(j>0 && X[i]!=X[j])
j=pre[j-1];
if(X[i]==X[j])j++;
pre[i]=j;
}
return pre;
}
static TreeNode start;
public static void f(TreeNode root,TreeNode p,int r)
{
if(root==null)return;
if(p!=null)
{
root.par=p;
}
if(root.val==r)start=root;
f(root.left,root,r);
f(root.right,root,r);
}
static int right(int A[],int Limit,int l,int r)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]<Limit)l=m;
else r=m;
}
return l;
}
static int left(int A[],int a,int l,int r)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]<a)l=m;
else r=m;
}
return l;
}
// static void build(int v,int tl,int tr,int A[])
// {
// if(tl==tr)
// {
// seg[v]=A[tl];
// return;
// }
// int tm=(tl+tr)/2;
// build(v*2,tl,tm,A);
// build(v*2+1,tm+1,tr,A);
// if((tm+1-tl)%2==0)
// seg[v]=seg[v*2]+seg[v*2+1];
// else seg[v]=seg[v*2]-seg[v*2+1];
// }
static void update(int v,int tl,int tr,int l,int r,int a)
{
if(l>r)return;
if(l==tl && tr==tr)
{
seg[v].add(a);
}
else
{
int tm=(tl+tr)/2;
update(v*2,tl,tm,l,Math.min(r, tm),a);
update(v*2+1,tm+1,tr,Math.max(tm+1, l),r,a);
}
}
// static void ask(int v,int tl,int tr,int index)
// {
//
// //if(l>r)return 0;
// if(tl==index && tl==tr)
// {
//
// }
// int tm=(tl+tr)/2;
//
// return ask(v*2,tl,tm,l,Math.min(tm, r))+ask(v*2+1,tm+1,tr,Math.max(tm+1, l),r);
// }
static boolean f(long A[],long m,int N)
{
long B[]=new long[N];
for(int i=0; i<N; i++)
{
B[i]=A[i];
}
for(int i=N-1; i>=0; i--)
{
if(B[i]<m)return false;
if(i>=2)
{
long extra=Math.min(B[i]-m, A[i]);
long x=extra/3L;
B[i-2]+=2L*x;
B[i-1]+=x;
}
}
return true;
}
static int f(int l,int r,long A[],long x)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]>=x)l=m;
else r=m;
}
return r;
}
static boolean f(long m,long H,long A[],int N)
{
long s=m;
for(int i=0; i<N-1;i++)
{
s+=Math.min(m, A[i+1]-A[i]);
}
return s>=H;
}
static long ask(long l,long r)
{
System.out.println("? "+l+" "+r);
return l();
}
static long f(long N,long M)
{
long s=0;
if(N%3==0)
{
N/=3;
s=N*M;
}
else
{
long b=N%3;
N/=3;
N++;
s=N*M;
N--;
long a=N*M;
if(M%3==0)
{
M/=3;
a+=(b*M);
}
else
{
M/=3;
M++;
a+=(b*M);
}
s=Math.min(s, a);
}
return s;
}
static int ask(StringBuilder sb,int a)
{
System.out.println(sb+""+a);
return i();
}
static void swap(char X[],int i,int j)
{
char x=X[i];
X[i]=X[j];
X[j]=x;
}
static int min(int a,int b,int c)
{
return Math.min(Math.min(a, b), c);
}
static long and(int i,int j)
{
System.out.println("and "+i+" "+j);
return l();
}
static long or(int i,int j)
{
System.out.println("or "+i+" "+j);
return l();
}
static int len=0,number=0;
static void f(char X[],int i,int num,int l)
{
if(i==X.length)
{
if(num==0)return;
//update our num
if(isPrime(num))return;
if(l<len)
{
len=l;
number=num;
}
return;
}
int a=X[i]-'0';
f(X,i+1,num*10+a,l+1);
f(X,i+1,num,l);
}
static boolean is_Sorted(int A[])
{
int N=A.length;
for(int i=1; i<=N; i++)if(A[i-1]!=i)return false;
return true;
}
static boolean f(StringBuilder sb,String Y,String order)
{
StringBuilder res=new StringBuilder(sb.toString());
HashSet<Character> set=new HashSet<>();
for(char ch:order.toCharArray())
{
set.add(ch);
for(int i=0; i<sb.length(); i++)
{
char x=sb.charAt(i);
if(set.contains(x))continue;
res.append(x);
}
}
String str=res.toString();
return str.equals(Y);
}
static boolean all_Zero(int f[])
{
for(int a:f)if(a!=0)return false;
return true;
}
static long form(int a,int l)
{
long x=0;
while(l-->0)
{
x*=10;
x+=a;
}
return x;
}
static int count(String X)
{
HashSet<Integer> set=new HashSet<>();
for(char x:X.toCharArray())set.add(x-'0');
return set.size();
}
static int f(long K)
{
long l=0,r=K;
while(r-l>1)
{
long m=(l+r)/2;
if(m*m<K)l=m;
else r=m;
}
return (int)l;
}
// static void build(int v,int tl,int tr,long A[])
// {
// if(tl==tr)
// {
// seg[v]=A[tl];
// }
// else
// {
// int tm=(tl+tr)/2;
// build(v*2,tl,tm,A);
// build(v*2+1,tm+1,tr,A);
// seg[v]=Math.min(seg[v*2], seg[v*2+1]);
// }
// }
static int [] sub(int A[],int B[])
{
int N=A.length;
int f[]=new int[N];
for(int i=N-1; i>=0; i--)
{
if(B[i]<A[i])
{
B[i]+=26;
B[i-1]-=1;
}
f[i]=B[i]-A[i];
}
for(int i=0; i<N; i++)
{
if(f[i]%2!=0)f[i+1]+=26;
f[i]/=2;
}
return f;
}
static int[] f(int N)
{
char X[]=in.next().toCharArray();
int A[]=new int[N];
for(int i=0; i<N; i++)A[i]=X[i]-'a';
return A;
}
static int max(int a ,int b,int c,int d)
{
a=Math.max(a, b);
c=Math.max(c,d);
return Math.max(a, c);
}
static int min(int a ,int b,int c,int d)
{
a=Math.min(a, b);
c=Math.min(c,d);
return Math.min(a, c);
}
static HashMap<Integer,Integer> Hash(int A[])
{
HashMap<Integer,Integer> mp=new HashMap<>();
for(int a:A)
{
int f=mp.getOrDefault(a,0)+1;
mp.put(a, f);
}
return mp;
}
static long mul(long a, long b)
{
return ( a %mod * 1L * b%mod )%mod;
}
static void swap(int A[],int a,int b)
{
int t=A[a];
A[a]=A[b];
A[b]=t;
}
static int find(int a)
{
if(par[a]<0)return a;
return par[a]=find(par[a]);
}
static void union(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
if(par[a]>par[b]) //this means size of a is less than that of b
{
int t=b;
b=a;
a=t;
}
par[a]+=par[b];
par[b]=a;
}
}
static boolean isSorted(int A[])
{
for(int i=1; i<A.length; i++)
{
if(A[i]<A[i-1])return false;
}
return true;
}
static boolean isDivisible(StringBuilder X,int i,long num)
{
long r=0;
for(; i<X.length(); i++)
{
r=r*10+(X.charAt(i)-'0');
r=r%num;
}
return r==0;
}
static int lower_Bound(int A[],int low,int high, int x)
{
if (low > high)
if (x >= A[high])
return A[high];
int mid = (low + high) / 2;
if (A[mid] == x)
return A[mid];
if (mid > 0 && A[mid - 1] <= x && x < A[mid])
return A[mid - 1];
if (x < A[mid])
return lower_Bound( A, low, mid - 1, x);
return lower_Bound(A, mid + 1, high, x);
}
static String f(String A)
{
String X="";
for(int i=A.length()-1; i>=0; i--)
{
int c=A.charAt(i)-'0';
X+=(c+1)%2;
}
return X;
}
static void sort(long[] a) //check for long
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static String swap(String X,int i,int j)
{
char ch[]=X.toCharArray();
char a=ch[i];
ch[i]=ch[j];
ch[j]=a;
return new String(ch);
}
static int sD(long n)
{
if (n % 2 == 0 )
return 2;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0 )
return i;
}
return (int)n;
}
// static void setGraph(int N,int nodes)
// {
//// size=new int[N+1];
// par=new int[N+1];
// col=new int[N+1];
//// g=new int[N+1][];
// D=new int[N+1];
// int deg[]=new int[N+1];
// int A[][]=new int[nodes][2];
// for(int i=0; i<nodes; i++)
// {
// int a=i(),b=i();
// A[i][0]=a;
// A[i][1]=b;
// deg[a]++;
// deg[b]++;
// }
// for(int i=0; i<=N; i++)
// {
// g[i]=new int[deg[i]];
// deg[i]=0;
// }
// for(int a[]:A)
// {
// int x=a[0],y=a[1];
// g[x][deg[x]++]=y;
// g[y][deg[y]++]=x;
// }
// }
static long pow(long a,long b)
{
//long mod=1000000007;
long pow=1;
long x=a;
while(b!=0)
{
if((b&1)!=0)pow=(pow*x)%mod;
x=(x*x)%mod;
b/=2;
}
return pow;
}
static long toggleBits(long x)//one's complement || Toggle bits
{
int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1;
return ((1<<n)-1)^x;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static boolean isPrime(long 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 void print(char A[])
{
for(char c:A)System.out.print(c+" ");
System.out.println();
}
static void print(boolean A[])
{
for(boolean c:A)System.out.print(c+" ");
System.out.println();
}
static void print(int A[])
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static void print(long A[])
{
for(long i:A)System.out.print(i+ " ");
System.out.println();
}
static void print(boolean A[][])
{
for(boolean a[]:A)print(a);
}
static void print(long A[][])
{
for(long a[]:A)print(a);
}
static void print(int A[][])
{
for(int a[]:A)print(a);
}
static void print(ArrayList<Integer> A)
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
}
class segNode
{
long pref,suff,sum,max;
segNode(long a,long b,long c,long d)
{
pref=a;
suff=b;
sum=c;
max=d;
}
}
//class TreeNode
//{
// int cnt,index;
// TreeNode left,right;
// TreeNode(int c)
// {
// cnt=c;
// index=-1;
// }
// TreeNode(int c,int index)
// {
// cnt=c;
// this.index=index;
// }
//}
class post implements Comparable<post>
{
long x,y,d,t;
post(long a,long b,long c)
{
x=a;
y=b;
d=c;
}
public int compareTo(post X)
{
if(X.t==this.t)
{
return 0;
}
else
{
long xt=this.t-X.t;
if(xt>0)return 1;
return -1;
}
}
}
class TreeNode
{
int val;
TreeNode left, right,par;
TreeNode() {}
TreeNode(int item)
{
val = item;
left =null;
right = null;
par=null;
}
}
class edge
{
int a,wt;
edge(int a,int w)
{
this.a=a;
wt=w;
}
}
class pair3 implements Comparable<pair3>
{
long a;
int index;
pair3(long x,int i)
{
a=x;
index=i;
}
public int compareTo(pair3 x)
{
return this.index-x.index;
}
}
//Code For FastReader
//Code For FastReader
//Code For FastReader
//Code For FastReader
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 | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | b23044fb04423d2135fe0cf7d05f8a3b | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
//import javax.print.attribute.HashAttributeSet;
//import com.sun.tools.javac.code.Attribute.Array;
public class c731 {
public static void main(String[] args) throws IOException {
// try {
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter pt = new PrintWriter(System.out);
FastReader sc = new FastReader();
int t = sc.nextInt();
for(int o = 0; o<t;o++) {
int n = sc.nextInt();
int m = sc.nextInt();
long k = sc.nextLong();
int q = sc.nextInt();
int[][] arr = new int[q][2];
for(int i = 0 ; i<q;i++) {
arr[i][0] = sc.nextInt();
arr[i][1] = sc.nextInt();
}
HashSet<Integer> r = new HashSet<Integer>();
HashSet<Integer> cl = new HashSet<Integer>();
int ro = 0;
int co = 0;
long val = 0;
for(int i = q-1 ; i>=0;i--) {
int x = arr[i][0];
int y = arr[i][1];
if(!r.contains(x) && co< m) {
r.add(x);
ro++;
val++;
if(!cl.contains(y)) {
co++;
cl.add(y);
}
}else if(!cl.contains(y) && ro<n) {
cl.add(y);
co++;
val++;
}else {
continue;
}
}
// System.out.println(val);
// System.out.println(val);
long ans = power(k, val, 998244353);
System.out.println(ans);
}
// out.flush();
}
//
// }
//
// }catch(Exception e) {
// return;
// }
// }
//------------------------------------------------------------------------------------------------------------------------------------------------
public static boolean check(int[] arr , int n) {
for(int i = 1 ; i<n;i++) {
if(arr[i]<arr[i-1]) {
return false;
}
}
return true;
}
public static void dfs(int s , HashMap<Integer, ArrayList<Integer>> map, boolean[] vis) {
vis[s] = true;
for(int x : map.get(s)) {
if(!vis[x]) {
dfs(x, map, vis);
}
}
}
public static int lis(int[] arr) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>=x) {
al.add(arr[i]);
}else {
int v = upper_bound(al, 0, al.size(), arr[i]);
al.set(v, arr[i]);
}
}
return al.size();
}
static int cntDivisors(int n){
int cnt = 0;
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
if (n/i == i)
cnt++;
else
cnt+=2;
}
}
return cnt;
}
public static long power(long x, long y, long p){
long res = 1;
x = x % p;
if (x == 0)
return 0;
while (y > 0){
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static long ncr(long[] fac, int n , int r , long m) {
return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m;
}
public static int lower_bound(ArrayList<Integer> ar,int lo , int hi , int k)
{
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get(mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)
{
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
// -----------------------------------------------------------------------------------------------------------------------------------------------
public static int gcd(int a, int b){
if (a == 0)
return b;
return gcd(b % a, a);
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
public static long modInverse(long a, long m){
long m0 = m;
long y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
// q is quotient
long q = a / m;
long t = m;
// m is remainder now, process
// same as Euclid's algo
m = a % m;
a = t;
t = y;
// Update x and y
y = x - q * y;
x = t;
}
// Make x positive
if (x < 0)
x += m0;
return x;
}
//-----------------------------------------------------------------------------------------------------------------------------------
//segment tree
//for finding minimum in range
public static void build(long [] seg,long []arr,int idx, int lo , int hi) {
if(lo == hi) {
seg[idx] = arr[lo];
return;
}
int mid = (lo + hi)/2;
build(seg,arr,2*idx+1, lo, mid);
build(seg,arr,idx*2+2, mid +1, hi);
// seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]);
// seg[idx] = seg[idx*2+1]+ seg[idx*2+2];
seg[idx] = Math.min(seg[idx*2+1], seg[idx*2+2]);
}
//for finding minimum in range
public static long query(long[]seg,int idx , int lo , int hi , int l , int r) {
if(lo>=l && hi<=r) {
return seg[idx];
}
if(hi<l || lo>r) {
return 0;
}
int mid = (lo + hi)/2;
long left = query(seg,idx*2 +1, lo, mid, l, r);
long right = query(seg,idx*2 + 2, mid + 1, hi, l, r);
// return Math.min(left, right);
//return gcd(left, right);
return Math.min(left, right);
}
// // for sum
//
//public static void update(int[]seg,int idx, int lo , int hi , int node , int val) {
// if(lo == hi) {
// seg[idx] += val;
// }else {
//int mid = (lo + hi )/2;
//if(node<=mid && node>=lo) {
// update(seg, idx * 2 +1, lo, mid, node, val);
//}else {
// update(seg, idx*2 + 2, mid + 1, hi, node, val);
//}
//seg[idx] = seg[idx*2 + 1] + seg[idx*2 + 2];
//
//}
//}
//---------------------------------------------------------------------------------------------------------------------------------------
static void shuffleArray(long[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
long a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
}
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;
}
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------
class SegmentTree{
int n;
public SegmentTree(int[] arr,int n) {
this.arr = arr;
this.n = n;
}
int[] arr = new int[n];
// int n = arr.length;
int[] seg = new int[4*n];
void build(int idx, int lo , int hi) {
if(lo == hi) {
seg[idx] = arr[lo];
return;
}
int mid = (lo + hi)/2;
build(2*idx+1, lo, mid);
build(idx*2+2, mid +1, hi);
seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]);
}
int query(int idx , int lo , int hi , int l , int r) {
if(lo<=l && hi>=r) {
return seg[idx];
}
if(hi<l || lo>r) {
return Integer.MAX_VALUE;
}
int mid = (lo + hi)/2;
int left = query(idx*2 +1, lo, mid, l, r);
int right = query(idx*2 + 2, mid + 1, hi, l, r);
return Math.min(left, right);
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
class coup{
int a;
int b;
public coup(int a , int b) {
this.a = a;
this.b = b;
}
}
class trip{
int a , b, c;
public trip(int a , int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 42a7c9196be59d1b8cbd60a2ee96470f | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
//import java.text.DecimalFormat;
import java.util.*;
public class B {
static int mod= 998244353 ;
// static int arr[];
public static void main(String[] args) throws Exception {
PrintWriter out=new PrintWriter(System.out);
FastScanner fs=new FastScanner();
int t=fs.nextInt();
outer:while(t-->0) {
int n=fs.nextInt(), m=fs.nextInt(), k=fs.nextInt(), q=fs.nextInt();
int r=0,c=0;
Set<Integer> setx=new HashSet<>(), sety=new HashSet<>();
int arr[][]=new int[q][2];
for(int i=0;i<q;i++) {
arr[i][0]=fs.nextInt();
arr[i][1]=fs.nextInt();
}
long ans=0;
int cnt=0;
for(int i=q-1;i>=0;i--) {
boolean rc=false, cc=false;
int a=arr[i][0], b=arr[i][1];
if(setx.contains(a)||sety.size()==m) {
rc=true;
}
if(sety.contains(b)||setx.size()==n) {
cc=true;
}
if(rc&&cc) continue ;
cnt++;
setx.add(a);
sety.add(b);
}
out.println(pow(k,cnt));
}
out.close();
}
static long pow(long a,long b) {
if(b<0) return 1;
long res=1;
while(b!=0) {
if((b&1)!=0) {
res*=a;
res%=mod;
}
a*=a;
a%=mod;
b=b>>1;
}
return res;
}
static int gcd(int a,int b) {
if(b==0) return a;
return gcd(b,a%b);
}
static long nck(int n,int k) {
if(k>n) return 0;
long res=1;
res*=fact(n);
res%=mod;
res*=modInv(fact(k));
res%=mod;
res*=modInv(fact(n-k));
res%=mod;
return res;
}
static long fact(long n) {
// return fact[(int)n];
long res=1;
for(int i=2;i<=n;i++) {
res*=i;
res%=mod;
}
return res;
}
static long modInv(long n) {
return pow(n,mod-2);
}
static void sort(int[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long[] readArrayL(int n) {
long a[]=new long[n];
for(int i=0;i<n;i++) a[i]=nextLong();
return a;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 610ba4f6f4d8230d8f86c2ac049fca4c | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class D1644 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
for (int t = Integer.parseInt(br.readLine()); t-- > 0; ) {
String[] line = br.readLine().split("\\s+");
int n = Integer.parseInt(line[0]);
int m = Integer.parseInt(line[1]);
int c = Integer.parseInt(line[2]);
int q = Integer.parseInt(line[3]);
int[][] op = new int[q][2];
for (int i = 0; i < q; i++) {
line = br.readLine().split("\\s+");
op[i][0] = Integer.parseInt(line[0]) - 1;
op[i][1] = Integer.parseInt(line[1]) - 1;
}
int numRowPainted = 0;
boolean[] paintedRow = new boolean[n];
int numColPainted = 0;
boolean[] paintedCol = new boolean[m];
long ans = 1;
long mod = 998244353;
for (int i = q; --i >= 0; ) {
if (!paintedRow[op[i][0]] && !paintedCol[op[i][1]]) {
ans = (ans * c) % mod;
numRowPainted++;
paintedRow[op[i][0]] = true;
numColPainted++;
paintedCol[op[i][1]] = true;
} else if (!paintedRow[op[i][0]] && paintedCol[op[i][1]]) {
if (numColPainted < m) {
ans = (ans * c) % mod;
numRowPainted++;
paintedRow[op[i][0]] = true;
}
} else if (!paintedCol[op[i][1]] && paintedRow[op[i][0]]) {
if (numRowPainted < n) {
ans = (ans * c) % mod;
numColPainted++;
paintedCol[op[i][1]] = true;
}
}
}
out.println(ans);
}
out.close();
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | ca88df7278787602aef9d5465ad596b4 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | //package codeforces.edu123;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class D {
static InputReader in;
static PrintWriter out;
public static void main(String[] args) {
//initReaderPrinter(true);
initReaderPrinter(false);
solve(in.nextInt());
//solve(1);
}
/*
General tips
1. It is ok to fail, but it is not ok to fail for the same mistakes over and over!
2. Train smarter, not harder!
3. If you find an answer and want to return immediately, don't forget to flush before return!
*/
/*
Read before practice
1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level;
2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else;
3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked;
4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list
and re-try in the future.
5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly;
6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial.
If getting stuck, skip it and solve other similar level problems.
Wait for 1 week then try to solve again. Only read editorial after you solved a problem.
7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already.
8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you
rushed to coding!
*/
/*
Read before contests and lockout 1 v 1
Mistakes you've made in the past contests:
1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked;
2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step
by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that
you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a
thorough idea steps!
3. Forgot about possible integer overflow;
When stuck:
1. Understand problem statements? Walked through test examples?
2. Take a step back and think about other approaches?
3. Check rank board to see if you can skip to work on a possibly easier problem?
4. If none of the above works, take a guess?
*/
static void solve(int testCnt) {
for (int testNumber = 0; testNumber < testCnt; testNumber++) {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(), q = in.nextInt();
long mod = 998244353L;
int[][] op = new int[q][2];
for(int i = 0; i < q; i++) {
op[i][0] = in.nextInt() - 1;
op[i][1] = in.nextInt() - 1;
}
long ans = 1;
Set<Integer> reColor_Row = new HashSet<>(), reColor_Col = new HashSet<>();
for(int i = q - 1; i >= 0; i--) {
boolean notRecolored = false;
if(reColor_Row.add(op[i][0])) {
notRecolored = true;
}
if(reColor_Col.add(op[i][1])) {
notRecolored = true;
}
if(notRecolored) ans = ans * k % mod;
if(reColor_Row.size() == n || reColor_Col.size() == m) break;
}
out.println(ans);
}
out.close();
}
static void initReaderPrinter(boolean test) {
if (test) {
try {
in = new InputReader(new FileInputStream("src/input.in"));
out = new PrintWriter(new FileOutputStream("src/output.out"));
} catch (IOException e) {
e.printStackTrace();
}
} else {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream), 32768);
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
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;
}
Integer[] nextIntArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArrayPrimitive(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArrayPrimitiveOneIndexed(int n) {
int[] a = new int[n + 1];
for (int i = 1; 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;
}
long[] nextLongArrayPrimitive(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long[] nextLongArrayPrimitiveOneIndexed(int n) {
long[] a = new long[n + 1];
for (int i = 1; i <= n; i++) a[i] = nextLong();
return a;
}
String[] nextStringArray(int n) {
String[] g = new String[n];
for (int i = 0; i < n; i++) g[i] = next();
return g;
}
List<Integer>[] readGraphOneIndexed(int n, int m) {
List<Integer>[] adj = new List[n + 1];
for (int i = 0; i <= n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt();
int v = nextInt();
adj[u].add(v);
adj[v].add(u);
}
return adj;
}
List<Integer>[] readGraphZeroIndexed(int n, int m) {
List<Integer>[] adj = new List[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
return adj;
}
/*
A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes.
1-indexed.
*/
int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) {
int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt];
int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1];
for (int i = 0; i < edgeCnt; i++) {
int u = in.nextInt(), v = in.nextInt();
edgeCntForEachNode[u]++;
edgeCntForEachNode[v]++;
end1[i] = u;
end2[i] = v;
}
int[][] adj = new int[nodeCnt + 1][];
for (int i = 1; i <= nodeCnt; i++) {
adj[i] = new int[edgeCntForEachNode[i]];
}
for (int i = 0; i < edgeCnt; i++) {
adj[end1[i]][idxForEachNode[end1[i]]] = end2[i];
idxForEachNode[end1[i]]++;
adj[end2[i]][idxForEachNode[end2[i]]] = end1[i];
idxForEachNode[end2[i]]++;
}
return adj;
}
/*
A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes.
1-indexed.
*/
int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) {
int[] from = new int[edgeCnt], to = new int[edgeCnt];
int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1];
//from u to v: u -> v
for (int i = 0; i < edgeCnt; i++) {
int u = in.nextInt(), v = in.nextInt();
edgeCntForEachNode[u]++;
from[i] = u;
to[i] = v;
}
int[][] adj = new int[nodeCnt + 1][];
for (int i = 1; i <= nodeCnt; i++) {
adj[i] = new int[edgeCntForEachNode[i]];
}
for (int i = 0; i < edgeCnt; i++) {
adj[from[i]][idxForEachNode[from[i]]] = to[i];
idxForEachNode[from[i]]++;
}
return adj;
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 2d165f64219c4acadb0e1adab48a04cd | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
/*
*/
public class D{
static FastReader sc=null;
public static void main(String[] args) {
sc=new FastReader();
int t=sc.nextInt();
for(int tt=0;tt<t;tt++) {
int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(),q=sc.nextInt();
boolean ru[]=new boolean[n],cu[]=new boolean[m];
int r[]=new int[q],c[]=new int[q];
for(int i=0;i<q;i++){
r[i]=sc.nextInt()-1;
c[i]=sc.nextInt()-1;
}
int ways=0,rows=0,cols=0;
for(int i=q-1;i>=0;i--) {
if(ru[r[i]] && cu[c[i]])continue;
ways++;
if(!ru[r[i]]) {
ru[r[i]]=true;
rows++;
}
if(!cu[c[i]]) {
cu[c[i]]=true;
cols++;
}
if(rows==n || cols==m) {
break;
}
}
System.out.println(exp(k, ways));
}
}
static long mod=(long)998244353;
static long mul(long a ,long b) {
return (a*b)%mod;
}
static long exp(long base,long e) {
if(e==0) return 1;
long half=exp(base,e/2);
if(e%2==0)return mul(half,half);
return mul(half,mul(half,base));
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
StringTokenizer st=new StringTokenizer("");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String next() {
while(!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
}
catch(IOException e){
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | b32192e99180c8312cfbebee8cc093d4 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class Main {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(in.readLine());
while (t-- > 0) {
StringTokenizer st1 = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st1.nextToken());
int m = Integer.parseInt(st1.nextToken());
int k = Integer.parseInt(st1.nextToken());
int q = Integer.parseInt(st1.nextToken());
int[][] a = new int[q][2];
for (int i=0; i<q; i++) {
StringTokenizer st = new StringTokenizer(in.readLine());
a[i][0] = Integer.parseInt(st.nextToken()) - 1;
a[i][1] = Integer.parseInt(st.nextToken()) - 1;
}
int x = getCountOfDifferent(n, m, q, a);
long ans = getNoOfColorings(k, x);
out.println(ans);
}
in.close();
out.close();
}
private static long getNoOfColorings(int k, int x) {
long ans = 1;
for (int i=0; i<x; i++) {
ans = (ans * k) % 998244353;
ans %= 998244353;
}
return ans;
}
private static int getCountOfDifferent(int n, int m, int q, int[][] a) {
Set<Integer> visitedRows = new HashSet<>();
Set<Integer> visitedCols = new HashSet<>();
int count = 0;
for (int i=q-1; i>=0; i--) {
int row = a[i][0];
int col = a[i][1];
if (!visitedRows.contains(row) || !visitedCols.contains(col) ) {
if (visitedCols.size() < m && visitedRows.size() < n)
count += 1;
visitedRows.add(row);
visitedCols.add(col);
}
}
return count;
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 4d37cf556bec3267c741a375a1f681b3 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class CF1{
public static void main(String[] args) {
FastScanner sc=new FastScanner();
int T=sc.nextInt();
for (int tt=0; tt<T; tt++){
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int q= sc.nextInt();
boolean arr[]= new boolean [n+1];
int cntr=0;
int cntc=0;
boolean arr2[]= new boolean [m+1];
int xx=0;
Pair input[]= new Pair[q];
for (int i=0; i<q; i++){
input[q-1-i]= new Pair(sc.nextInt(), sc.nextInt());
}
for (int i=0; i<q; i++){
int x = input[i].x;
int y= input[i].y;
if (cntr==n || cntc==m) break;
if (arr[x] && arr2[y] ) continue;
else {
xx++;
if (!arr[x]) cntr++;
if (!arr2[y]) cntc++;
arr[x]=true;
arr2[y]=true;
}
}
System.out.println(power2(k, xx));
}
}
static long factorial (int x){
if (x==0) return 1;
long ans =x;
for (int i=x-1; i>=1; i--){
ans*=i;
ans%=mod;
}
return ans;
}
static long mod =998244353L;
static long power2 (long a, long b){
long res=1;
while (b>0){
if ((b&1)== 1){
res= (res * a % mod)%mod;
}
a=(a%mod * a%mod)%mod;
b=b>>1;
}
return res;
}
static boolean sieveOfEratosthenes(int n)
{
boolean prime[] = new boolean[n+1];
for(int i=0;i<=n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
if(prime[p] == true)
{
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
return prime[n];
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sortLong(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static long gcd (long n, long m){
if (m==0) return n;
else return gcd(m, n%m);
}
static class Pair implements Comparable<Pair>{
int x,y;
private static final int hashMultiplier = BigInteger.valueOf(new Random().nextInt(1000) + 100).nextProbablePrime().intValue();
public Pair(int x, int y){
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pii = (Pair) o;
if (x != pii.x) return false;
return y == pii.y;
}
public int hashCode() {
return hashMultiplier * x + y;
}
public int compareTo(Pair o){
return this.x-o.x;
}
// this.x-o.x is ascending
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | f67f879b17fc1f148759366de67e042e | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//import java.math.BigInteger;
import java.util.*;
public class CF1{
public static void main(String[] args) {
FastScanner sc=new FastScanner();
int T=sc.nextInt();
for (int tt=0; tt<T; tt++){
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int q= sc.nextInt();
boolean arr[]= new boolean [n+1];
int cntr=0;
int cntc=0;
boolean arr2[]= new boolean [m+1];
int xx=0;
Pair input[]= new Pair[q];
for (int i=0; i<q; i++){
input[q-1-i]= new Pair(sc.nextInt(), sc.nextInt());
}
for (int i=0; i<q; i++){
int x = input[i].x;
int y= input[i].y;
if (cntr==n || cntc==m) break;
if (arr[x] && arr2[y] ) continue;
else {
xx++;
if (!arr[x]) cntr++;
if (!arr2[y]) cntc++;
arr[x]=true;
arr2[y]=true;
}
}
System.out.println(power2(k, xx));
}
}
static long factorial (int x){
if (x==0) return 1;
long ans =x;
for (int i=x-1; i>=1; i--){
ans*=i;
ans%=mod;
}
return ans;
}
static int mod =998244353;
static long power2 (long a, long b){
long res=1;
while (b>0){
if ((b&1)== 1){
res= (res * a % mod)%mod;
}
a=(a%mod * a%mod)%mod;
b=b>>1;
}
return res;
}
static boolean sieveOfEratosthenes(int n)
{
boolean prime[] = new boolean[n+1];
for(int i=0;i<=n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
if(prime[p] == true)
{
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
return prime[n];
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sortLong(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static long gcd (long n, long m){
if (m==0) return n;
else return gcd(m, n%m);
}
static class Pair implements Comparable<Pair>{
int x,y;
// private static final int hashMultiplier = BigInteger.valueOf(new Random().nextInt(1000) + 100).nextProbablePrime().intValue();
public Pair(int x, int y){
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pii = (Pair) o;
if (x != pii.x) return false;
return y == pii.y;
}
// public int hashCode() {
// return hashMultiplier * x + y;
// }
public int compareTo(Pair o){
return this.x-o.x;
}
// this.x-o.x is ascending
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 38471b197edfb442718a89366518f65f | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class CF1{
public static void main(String[] args) {
FastScanner sc=new FastScanner();
int T=sc.nextInt();
for (int tt=0; tt<T; tt++){
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int q= sc.nextInt();
boolean arr[]= new boolean [n+1];
int cntr=0;
int cntc=0;
boolean arr2[]= new boolean [m+1];
int xx=0;
Pair input[]= new Pair[q];
for (int i=0; i<q; i++){
input[q-1-i]= new Pair(sc.nextInt(), sc.nextInt());
}
for (int i=0; i<q; i++){
int x = input[i].x;
int y= input[i].y;
if (arr[x] && arr2[y] || cntr==n || cntc==m) continue;
else {
xx++;
if (!arr[x]) cntr++;
if (!arr2[y]) cntc++;
arr[x]=true;
arr2[y]=true;
}
}
System.out.println(power2(k, xx));
}
}
static long factorial (int x){
if (x==0) return 1;
long ans =x;
for (int i=x-1; i>=1; i--){
ans*=i;
ans%=mod;
}
return ans;
}
static int mod =998244353;
static long power2 (long a, long b){
long res=1;
while (b>0){
if ((b&1)== 1){
res= (res * a % mod)%mod;
}
a=(a%mod * a%mod)%mod;
b=b>>1;
}
return res;
}
static boolean sieveOfEratosthenes(int n)
{
boolean prime[] = new boolean[n+1];
for(int i=0;i<=n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
if(prime[p] == true)
{
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
return prime[n];
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sortLong(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static long gcd (long n, long m){
if (m==0) return n;
else return gcd(m, n%m);
}
static class Pair implements Comparable<Pair>{
int x,y;
private static final int hashMultiplier = BigInteger.valueOf(new Random().nextInt(1000) + 100).nextProbablePrime().intValue();
public Pair(int x, int y){
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pii = (Pair) o;
if (x != pii.x) return false;
return y == pii.y;
}
public int hashCode() {
return hashMultiplier * x + y;
}
public int compareTo(Pair o){
return this.x-o.x;
}
// this.x-o.x is ascending
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | e17e538961dbcbf351f76b103ed7f926 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
long MOD = 998244353L;
int T = in.nextInt();
for(int ttt = 1; ttt <= T; ttt++) {
int n = in.nextInt();
int m = in.nextInt();
long k = in.nextLong();
int q = in.nextInt();
int[][] a = new int[q][2];
for(int i = 0; i < q; i++) {
a[i] = in.readInt(2);
}
long ans = 1;
HashSet<Integer> x = new HashSet<>();
HashSet<Integer> y = new HashSet<>();
for(int i = q-1; i >= 0; i--) {
if(!x.contains(a[i][0]) || !y.contains(a[i][1])) {
ans = (ans*k)%MOD;
}
x.add(a[i][0]);
y.add(a[i][1]);
if(x.size()==n || y.size()==m) {
break;
}
}
out.println(ans);
}
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); }
String next() {
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch(IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine() {
String str = "";
try { str = br.readLine(); }
catch(IOException e) { e.printStackTrace(); }
return str;
}
int[] readInt(int size) {
int[] arr = new int[size];
for(int i = 0; i < size; i++)
arr[i] = Integer.parseInt(next());
return arr;
}
long[] readLong(int size) {
long[] arr = new long[size];
for(int i = 0; i < size; i++)
arr[i] = Long.parseLong(next());
return arr;
}
int[][] read2dArray(int rows, int cols) {
int[][] arr = new int[rows][cols];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++)
arr[i][j] = Integer.parseInt(next());
}
return arr;
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | afe7404bff80f7fe2feeae8f8c730aa6 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes |
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class CodeChef2 {
static boolean lazy[];
static int val[];
static boolean colupd[];
static int mod = 998244353;
public static void main(String args[]) throws Exception {
FastReader fr = new FastReader();
int t = fr.nextInt();
// int t = 1;
PrintWriter out = new PrintWriter(System.out);
while (t-- > 0) {
int n = fr.nextInt();
int m = fr.nextInt();
int k = fr.nextInt();
int q = fr.nextInt();
int arr[][] = new int[q][2];
for(int i = 0; i < q; i++) {
arr[i][0] = fr.nextInt();
arr[i][1] = fr.nextInt();
}
boolean row[] = new boolean[n+1];
boolean col[] = new boolean[m+1];
int r = 0;
int c = 0;
int fq = 0;
for(int i = q-1; i >= 0; i--) {
int x = arr[i][0];
int y = arr[i][1];
if(!(col[y]&&row[x]))
fq++;
if(!col[y]) {
col[y] = true;
c++;
}
if(!row[x]) {
row[x] = true;
r++;
}
if(r == n || c == m) {
break;
}
}
int ans = modExpo(k, fq, mod);
out.println(ans);
}
out.close();
}
static void print(int arr[], PrintWriter out) {
for(int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
static int check(int x) {
StringBuilder sb = new StringBuilder();
sb.append(Integer.toBinaryString(x));
sb = sb.reverse();
int y = x ^ Integer.parseInt(sb.toString(), 2);
if(y == 0)
return 0;
return check(y) + 1;
}
static int modExpo(int a, int n, int m) {
a = a%m;
if(a <= 1 || n ==1)
return a;
else if(n == 0)
return 1;
long p = modExpo(a, n/2, m);
p = (p * p)%m;
if(n%2 == 1)
p = (p * (long)a)%m;
return (int)p;
}
static int[] buildST(int arr[]) {
int n = arr.length;
int p = (int)(Math.ceil(Math.log(n)/Math.log(2)));
n = (int)Math.pow(2, p);
int size = 2*n - 1;
int st[] = new int[size];
for(int i = 0; i < arr.length; i++) {
st[n-1 + i] = arr[i];
}
return st;
}
static long query(int col[], long val[], int l, int i, int s, int e) {
if(l > e || l < s)
return 0;
if(s == e) {
return val[i];
}
int m = (s+e)/2;
// if(val[i] != 0) {
// updateV(val, col, 2*i + 1, s, m, col[2*i + 1], val[i]);
// updateV(val, col, 2*i + 2, m+1, e, col[2*i + 2], val[i]);
// val[i] = 0;
// }
long v = 0;
if(l <= m)
v = query(col, val, l, 2*i+1, s, m);
else v = query(col, val, l, 2*i+2, m+1, e);
return val[i] + v;
}
static void updateC(int col[], int l, int r, int i, int s, int e, int c) {
if(l > r || l > e || r < s || col[i] == c)
return;
if(l <= s && e <= r) {
col[i] = c;
return;
}
int m = (s + e)/2;
if(col[i] != 0 && col[i] != c) {
updateC(col, s, m, 2*i + 1, s, m, col[i]);
updateC(col, m+1, e, 2*i + 2, m+1, e, col[i]);
col[i] = 0;
}
updateC(col, l, Math.min(m, r), 2*i + 1, s, m, c);
updateC(col, Math.max(l, m+1), r, 2*i + 2, m+1, e, c);
col[i] = (col[2*i + 1] != col[2*i + 2] || col[2*i + 1] == 0? 0 : c);
}
static void updateV(long val[], int col[], int i, int s, int e, int c, long v) {
if(col[i] != 0 && col[i] != c)
return;
if(col[i] == c) {
val[i] += v;
return;
}
int m = (s + e)/2;
// if(val[i] != 0) {
// updateV(val, col, 2*i + 1, s, m, col[2*i + 1], val[i]);
// updateV(val, col, 2*i + 2, m+1, e, col[2*i + 2], val[i]);
// val[i] = 0;
// }
updateV(val, col,2*i + 1, s, m, c, v);
updateV(val, col,2*i + 2, m+1, e, c, v);
}
static class Pair implements Comparable<Pair>{
int i;
int v;
Pair(int i, int j) {
this.i = i;
v = j;
}
public int compareTo(Pair o) {
if(this.v < o.v)
return -1;
else if(this.v > o.v)
return 1;
else if(this.i < o.i)
return -1;
return 1;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
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;
}
boolean hasMore() {
try {
return br.ready();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | d75723b3371cbdb34d725d00aea87fb2 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class D {
static class Q {
public int x, y;
public Q(int a, int b) {x = a; y = b;}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st;
int MOD = 998244353;
int t = Integer.parseInt(br.readLine());
while (t --> 0) {
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int q = Integer.parseInt(st.nextToken());
Set<Integer> x = new HashSet<>();
Set<Integer> y = new HashSet<>();
Q[] o = new Q[q];
for (int i = 0; i < q; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
o[i] = new Q(a, b);
}
int c = 0;
for (int i = q - 1; i >= 0; i--) {
if ((!x.contains(o[i].x) || !y.contains(o[i].y)) && x.size() != n && y.size() != m) c++;
x.add(o[i].x);
y.add(o[i].y);
}
long ans = 1;
for (int i = 0; i < c; i++) {
ans *= k;
ans %= MOD;
}
pw.println(ans);
}
pw.close();
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | d1e0ccc09f159170a1e6264a3b74fb72 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static long startTime = System.currentTimeMillis();
// for global initializations and methods starts here
// global initialisations and methods end here
static void run() {
boolean tc = true;
AdityaFastIO r = new AdityaFastIO();
//FastReader r = new FastReader();
try (OutputStream out = new BufferedOutputStream(System.out)) {
//long startTime = System.currentTimeMillis();
int testcases = tc ? r.ni() : 1;
int tcCounter = 1;
// Hold Here Sparky------------------->>>
// Solution Starts Here
start:
while (testcases-- > 0) {
int n = r.ni();
int m = r.ni();
long k = r.nl();
int q = r.ni();
List<Pair> al = new ArrayList<>();
for (int i = 0; i < q; i++) al.add(new Pair(r.nl(), r.nl()));
Set<Long> set1 = new HashSet<>();
Set<Long> set2 = new HashSet<>();
Set<Pair> ans = new HashSet<>();
while (!al.isEmpty() && set1.size() != n && set2.size() != m) {
int len = al.size();
if (!set1.contains(al.get(len - 1).first) || !set2.contains(al.get(len - 1).second))
ans.add(new Pair(al.get(len - 1).first, al.get(len - 1).second));
set1.add(al.get(len - 1).first);
set2.add(al.get(len - 1).second);
al.remove(len - 1);
}
out.write((modInv(k, ans.size()) + " ").getBytes());
out.write(("\n").getBytes());
}
// Solution Ends Here
} catch (IOException e) {
e.printStackTrace();
}
}
static class AdityaFastIO {
final private int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public BufferedReader br;
public StringTokenizer st;
public AdityaFastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public AdityaFastIO(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String readLine() throws IOException {
byte[] buf = new byte[100000001]; // 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 ni() 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 nl() 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 nd() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
public static void main(String[] args) throws Exception {
run();
}
static int[] readIntArr(int n, AdityaFastIO r) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = r.ni();
return arr;
}
static long[] readLongArr(int n, AdityaFastIO r) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) arr[i] = r.nl();
return arr;
}
static List<Integer> readIntList(int n, AdityaFastIO r) throws IOException {
List<Integer> al = new ArrayList<>();
for (int i = 0; i < n; i++) al.add(r.ni());
return al;
}
static List<Long> readLongList(int n, AdityaFastIO r) throws IOException {
List<Long> al = new ArrayList<>();
for (int i = 0; i < n; i++) al.add(r.nl());
return al;
}
static long mod = 998244353;
static long modInv(long base, long e) {
long result = 1;
base %= mod;
while (e > 0) {
if ((e & 1) > 0) result = result * base % mod;
base = base * base % mod;
e >>= 1;
}
return result;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int ni() {
return Integer.parseInt(word());
}
long nl() {
return Long.parseLong(word());
}
double nd() {
return Double.parseDouble(word());
}
}
static int MOD = (int) (1e9 + 7);
static long powerLL(long x, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 1) result = result * x % MOD;
n = n / 2;
x = x * x % MOD;
}
return result;
}
static long powerStrings(int i1, int i2) {
String sa = String.valueOf(i1);
String sb = String.valueOf(i2);
long a = 0, b = 0;
for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD;
for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1);
return powerLL(a, b);
}
static long gcd(long a, long b) {
if (a == 0) return b;
else return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long lower_bound(int[] arr, int x) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (arr[m] >= x) r = m;
else l = m;
}
return r;
}
static int upper_bound(int[] arr, int x) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (arr[m] <= x) l = m;
else r = m;
}
return l + 1;
}
static void addEdge(ArrayList<ArrayList<Integer>> graph, int edge1, int edge2) {
graph.get(edge1).add(edge2);
graph.get(edge2).add(edge1);
}
public static class Pair implements Comparable<Pair> {
long first;
long second;
public Pair(long first, long second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if (this.first != o.first)
return (int) (this.first - o.first);
else return (int) (this.second - o.second);
}
}
public static class PairC<X, Y> implements Comparable<PairC> {
X first;
Y second;
public PairC(X first, Y second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(PairC o) {
// TODO Auto-generated method stub
return o.compareTo((PairC) first);
}
}
static boolean isCollectionsSorted(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false;
return true;
}
static boolean isCollectionsSortedReverseOrder(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false;
return true;
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 9382e0cbba5f7fca24e40daea03d4336 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static long startTime = System.currentTimeMillis();
// for global initializations and methods starts here
// global initialisations and methods end here
static void run() {
boolean tc = true;
AdityaFastIO r = new AdityaFastIO();
//FastReader r = new FastReader();
try (OutputStream out = new BufferedOutputStream(System.out)) {
//long startTime = System.currentTimeMillis();
int testcases = tc ? r.ni() : 1;
int tcCounter = 1;
// Hold Here Sparky------------------->>>
// Solution Starts Here
start:
while (testcases-- > 0) {
int n = r.ni();
int m = r.ni();
long k = r.nl();
int q = r.ni();
List<Pair> al = new ArrayList<>();
for (int i = 0; i < q; i++) al.add(new Pair(r.nl(), r.nl()));
Set<Long> set1 = new TreeSet<>();
Set<Long> set2 = new TreeSet<>();
Set<Pair> ans = new TreeSet<>();
while (!al.isEmpty() && set1.size() != n && set2.size() != m) {
int len = al.size();
if (!set1.contains(al.get(len - 1).first) || !set2.contains(al.get(len - 1).second))
ans.add(new Pair(al.get(len - 1).first, al.get(len - 1).second));
set1.add(al.get(len - 1).first);
set2.add(al.get(len - 1).second);
al.remove(len - 1);
}
out.write((modInv(k, ans.size()) + " ").getBytes());
out.write(("\n").getBytes());
}
// Solution Ends Here
} catch (IOException e) {
e.printStackTrace();
}
}
static class AdityaFastIO {
final private int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public BufferedReader br;
public StringTokenizer st;
public AdityaFastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public AdityaFastIO(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String readLine() throws IOException {
byte[] buf = new byte[100000001]; // 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 ni() 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 nl() 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 nd() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
public static void main(String[] args) throws Exception {
run();
}
static int[] readIntArr(int n, AdityaFastIO r) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = r.ni();
return arr;
}
static long[] readLongArr(int n, AdityaFastIO r) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) arr[i] = r.nl();
return arr;
}
static List<Integer> readIntList(int n, AdityaFastIO r) throws IOException {
List<Integer> al = new ArrayList<>();
for (int i = 0; i < n; i++) al.add(r.ni());
return al;
}
static List<Long> readLongList(int n, AdityaFastIO r) throws IOException {
List<Long> al = new ArrayList<>();
for (int i = 0; i < n; i++) al.add(r.nl());
return al;
}
static long mod = 998244353;
static long modInv(long base, long e) {
long result = 1;
base %= mod;
while (e > 0) {
if ((e & 1) > 0) result = result * base % mod;
base = base * base % mod;
e >>= 1;
}
return result;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int ni() {
return Integer.parseInt(word());
}
long nl() {
return Long.parseLong(word());
}
double nd() {
return Double.parseDouble(word());
}
}
static int MOD = (int) (1e9 + 7);
static long powerLL(long x, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 1) result = result * x % MOD;
n = n / 2;
x = x * x % MOD;
}
return result;
}
static long powerStrings(int i1, int i2) {
String sa = String.valueOf(i1);
String sb = String.valueOf(i2);
long a = 0, b = 0;
for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD;
for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1);
return powerLL(a, b);
}
static long gcd(long a, long b) {
if (a == 0) return b;
else return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long lower_bound(int[] arr, int x) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (arr[m] >= x) r = m;
else l = m;
}
return r;
}
static int upper_bound(int[] arr, int x) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (arr[m] <= x) l = m;
else r = m;
}
return l + 1;
}
static void addEdge(ArrayList<ArrayList<Integer>> graph, int edge1, int edge2) {
graph.get(edge1).add(edge2);
graph.get(edge2).add(edge1);
}
public static class Pair implements Comparable<Pair> {
long first;
long second;
public Pair(long first, long second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if (this.first != o.first)
return (int) (this.first - o.first);
else return (int) (this.second - o.second);
}
}
public static class PairC<X, Y> implements Comparable<PairC> {
X first;
Y second;
public PairC(X first, Y second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(PairC o) {
// TODO Auto-generated method stub
return o.compareTo((PairC) first);
}
}
static boolean isCollectionsSorted(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false;
return true;
}
static boolean isCollectionsSortedReverseOrder(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false;
return true;
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 716e9e5e9367e7cc468cfc45ada50aef | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static int N = 100010, M = N, INF = Integer.MAX_VALUE;
static int MOD = 998244353;
static double EPS = 1e-7;
static int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
static int h[] = new int[N], to[] = new int[M], ne[] = new int[M], w[] = new int[M], idx;
static boolean st[] = new boolean[N];
static InputReader sc = new InputReader();
static int a[] = new int[N];
static int n, m;
static void add(int a, int b) {
to[idx] = b; ne[idx] = h[a]; h[a] = idx ++ ;
}
static long qmi(long a, long k) {
long res = 1;
while(k > 0) {
if((k & 1) == 1)
res = res * a % MOD;
a = a * a % MOD;
k >>= 1;
}
return res;
}
static void solve() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int q = sc.nextInt();
HashSet<Integer> r = new HashSet<>();
HashSet<Integer> c = new HashSet<>();
int cnt = 0;
int a[][] = new int[q][2];
for(int i = 0; i < q; i ++ ) {
a[i][0] = sc.nextInt();
a[i][1] = sc.nextInt();
}
for(int i = q - 1; i >= 0; i -- ) {
int x = a[i][0];
int y = a[i][1];
if(r.contains(x) && c.contains(y))
continue;
if(r.size() == n || c.size() == m)
continue;
if(r.contains(x) && c.size() == m)
continue;
if(c.contains(y) && r.size() == n)
continue;
cnt ++ ;
r.add(x); c.add(y);
}
System.out.println(qmi(k, cnt));
}
public static void main(String[] args) throws IOException {
int T = sc.nextInt();
while(T -- > 0) {
solve();
}
}
static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
static int lcm(int a, int b) { return (a * b) / gcd(a, b); }
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader() {
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());
}
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | bd8e9211b2d959b0986118bb608dec5b | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | // OM NAMAH SHIVAY
//import jdk.jshell.execution.JdiDefaultExecutionControl;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
//import java.util.logging.LogManager;
public class Vaibhav {
static long bit[];
static boolean prime[];
//static PrintWriter out = new PrintWriter(System.out);
static class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int p, int q) {
a = p;
b = q;
}
public int compareTo(Pair o){
return this.b - o.b;
}
// Pair with HashSet
/* public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair) o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
int hash = 5;
hash = 17 * hash + this.a;
return hash;
}*/
}
static long power(long x, long y, long p) {
if (y == 0) return 1;
if (x == 0) return 0;
long res = 1l;
x = x % p;
while (y > 0) {
if (y % 2 == 1) res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long power(long x, long y) {
if (y == 0) return 1;
if (x == 0) return 0;
long res = 1;
while (y > 0) {
if (y % 2 == 1) res = (res * x);
y = y >> 1;
x = (x * x);
}
return res;
}
static void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] readlongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static void sieveOfEratosthenes(int n) {
prime = new boolean[n + 1];
for (int i = 0; i <= n; i++) prime[i] = true;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i += p) prime[i] = false;
}
}
}
public static int log2(int x) {
return (int) (Math.log(x) / Math.log(2));
}
static int binomialCoeff(int n, int r)
{
if (r > n)
return 0;
long m = 1000000007;
long inv[] = new long[r + 1];
inv[0] = 1;
if(r+1>=2)
inv[1] = 1;
for (int i = 2; i <= r; i++) {
inv[i] = m - (m / i) * inv[(int) (m % i)] % m;
}
int ans = 1;
for (int i = 2; i <= r; i++) {
ans = (int) (((ans % m) * (inv[i] % m)) % m);
}
for (int i = n; i >= (n - r + 1); i--) {
ans = (int) (((ans % m) * (i % m)) % m);
}
return ans;
}
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static BigInteger bi(String str) {
return new BigInteger(str);
}
// Author - vaibhav_1710
static FastScanner fs = null;
static long mod=998244353;
static int a[];
static int p[];
static int[][] dirs = { { 0, -1 },
{ -1, 0 },
{ 0, 1 },
{ 1, 0 },
};
static int count=0;
static ArrayList<Integer> al[];
static HashSet<Pair> h;
static double len;
public static void main(String[] args) {
fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = fs.nextInt();
outer: while (t-- > 0 ) {
int n = fs.nextInt();
int m = fs.nextInt();
int k = fs.nextInt();
int q = fs.nextInt();
HashSet<Integer> hx = new HashSet<>();
HashSet<Integer> hy = new HashSet<>();
ArrayList<Pair> al = new ArrayList<>();
for(int i=0;i<q;i++){
int r = fs.nextInt();
int c = fs.nextInt();
al.add(new Pair(r,c));
}
long ans=1l;
long mod = 998244353;
for(int i=q-1;i>=0;i--){
Pair r = al.get(i);
if((hx.contains(r.a)&&(hy.contains(r.b))) || (hx.size()==(n)) || (hy.size()==m)){
continue;
}else{
ans *= k;
ans %= mod;
hx.add(r.a);
hy.add(r.b);
}
}
out.println(ans);
}
out.close();
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 6747451701ddf457a86e896b349c4c36 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring{
static long mod = 1000000007L;
static MyScanner sc = new MyScanner();
static void solve() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int q = sc.nextInt();
long mod = 998244353;
long ans = 1;
HashSet<Integer> a = new HashSet<>();
HashSet<Integer> b = new HashSet<>();
int aa[] = new int[q];
int bb[] = new int[q];
for(int i = 0;i<q;i++){
aa[i] = sc.nextInt();
bb[i] = sc.nextInt();
}
for(int i = q-1;i>=0;i--){
boolean flag = false;
if(!a.contains(aa[i])){
flag = true;
a.add(aa[i]);
}
if(!b.contains(bb[i])){
flag = true;
b.add(bb[i]);
}
if(flag){
ans *= k;
ans%=mod;
}
if(a.size()==n || b.size()==m) break;
}
out.println(ans);
}
static long lcm(long a,long b){
return (a*b)/gcd(a,b);
}
static long comb(long n,long k,long mod){
return factorial(n,mod) * pow(factorial(k,mod), mod-2) % mod * pow(factorial(n-k,mod), mod-2) % mod;
}
static long factorial(long n,long mod){
long ret = 1;
while(n > 0){
ret = ret * n % mod;
n--;
}
return ret;
}
static class Pair implements Comparable<Pair>{
long a;
long b;
Pair(long aa,long bb){
a = aa;
b = bb;
}
public int compareTo(Pair p){
return Long.compare(this.b,p.b);
}
}
static void reverse(int arr[]){
int i = 0;int j = arr.length-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long pow(long a, long b) {
if (b == 0) return 1;
long res = pow(a, b / 2);
res = (res * res) % 1_000_000_007;
if (b % 2 == 1) {
res = (res * a) % 1_000_000_007;
}
return res;
}
static int lis(int arr[],int n){
int lis[] = new int[n];
lis[0] = 1;
for(int i = 1;i<n;i++){
lis[i] = 1;
for(int j = 0;j<i;j++){
if(arr[i]>arr[j]){
lis[i] = Math.max(lis[i],lis[j]+1);
}
}
}
int max = Integer.MIN_VALUE;
for(int i = 0;i<n;i++){
max = Math.max(lis[i],max);
}
return max;
}
static boolean isPali(String str){
int i = 0;
int j = str.length()-1;
while(i<j){
if(str.charAt(i)!=str.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
static long gcd(long a,long b){
if(b==0) return a;
return gcd(b,a%b);
}
static String reverse(String str){
char arr[] = str.toCharArray();
int i = 0;
int j = arr.length-1;
while(i<j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
String st = new String(arr);
return st;
}
static boolean isprime(int n){
if(n==1) return false;
if(n==3 || n==2) return true;
if(n%2==0 || n%3==0) return false;
for(int i = 5;i*i<=n;i+= 6){
if(n%i== 0 || n%(i+2)==0){
return false;
}
}
return true;
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
// int t= 1;
while(t-- >0){
solve();
// solve2();
// solve3();
}
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int[] readIntArray(int n){
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = Integer.parseInt(next());
}
return arr;
}
int[] reverse(int arr[]){
int n= arr.length;
int i = 0;
int j = n-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;i++;
}
return arr;
}
long[] readLongArray(int n){
long arr[] = new long[n];
for(int i = 0;i<n;i++){
arr[i] = Long.parseLong(next());
}
return arr;
}
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;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 6735a6ad50799c3e74e59eac9b7fbd86 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
public class CrossColoring {
static MScanner mScanner = new MScanner();
static int mod = 998244353;
public static void main(String[] args) {
int T = mScanner.nextInt();
while (T -- > 0) {
int n = mScanner.nextInt();
int m = mScanner.nextInt();
int k = mScanner.nextInt();
int q = mScanner.nextInt();
int[][] op = new int[q][2];
for (int i = 0; i < q; ++i) {
op[i][0] = mScanner.nextInt();
op[i][1] = mScanner.nextInt();
}
System.out.println(solve(n, m, k, op));
}
}
static int solve(int n, int m, int k, int[][] op) {
Map<Integer, Integer> row = new HashMap<>();
Map<Integer, Integer> col = new HashMap<>();
for (int i = op.length - 1; i >= 0; --i) {
if (row.size() == n || col.size() == m) {
break;
}
if (!row.containsKey(op[i][0])) {
row.put(op[i][0], i);
}
if (!col.containsKey(op[i][1])) {
col.put(op[i][1], i);
}
}
Set<Integer> total = new HashSet<>();
total.addAll(row.values());
total.addAll(col.values());
long ret = mi(k, total.size());
return (int) ret;
}
static long mi(long a, long p) {
long ret = 1;
while (p > 0) {
if ((p & 1) > 0) {
ret = (ret * a) % mod;
}
a = a * a % mod;
p = p >> 1;
}
return ret;
}
static class MScanner {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String nextLine = innerNextLine();
if (nextLine == null) {
return false;
}
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public String nextLine() {
tokenizer = new StringTokenizer("");
return innerNextLine();
}
public String next() {
hasNext();
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 | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | c452ed2899147480dee7a49f2f4eb687 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.io.*;
//import java.math.BigInteger;
public class code{
public static class Pair{
int a;
int b;
Pair(int i,int j){
a=i;
b=j;
}
}
public static int GCD(int a, int b)
{
if (b == 0)
return a;
return GCD(b, a % b);
}
public static void shuffle(int a[], int n)
{
for (int i = 0; i < n; i++) {
// getting the random index
int t = (int)Math.random() * a.length;
// and swapping values a random index
// with the current index
int x = a[t];
a[t] = a[i];
a[i] = x;
}
}
public static PrintWriter out = new PrintWriter(System.out);
//public static long mod=(long)(1e9+7);
@SuppressWarnings("unchecked")
public static void main(String[] arg) throws IOException{
//Reader in=new Reader();
//PrintWriter out = new PrintWriter(System.out);
//Scanner in = new Scanner(System.in);
FastScanner in=new FastScanner();
int t=in.nextInt();
long mod=(long)998244353;
while(t-- > 0){
int n=in.nextInt();
int m=in.nextInt();
long k=in.nextLong();
int q=in.nextInt();
Set<Integer> row=new HashSet<Integer>();
Set<Integer> col=new HashSet<Integer>();
long res=1;
int[][] query=new int[q][2];
for(int i=0;i<q;i++){
query[i][0]=in.nextInt();
query[i][1]=in.nextInt();
}
for(int i=q-1;i>=0;i--){
int x=query[i][0];
int y=query[i][1];
if(row.contains(x) && col.contains(y)) continue;
else res=(res*k)%mod;
row.add(x);
col.add(y);
if(row.size()==n || col.size()==m) break;
}
out.println(res);
}
out.flush();
}
}
class Fenwick{
int[] bit;
public Fenwick(int n){
bit=new int[n];
//int sum=0;
}
public void update(int index,int val){
index++;
for(;index<bit.length;index += index&(-index)) bit[index]+=val;
}
public int presum(int index){
int sum=0;
for(;index>0;index-=index&(-index)) sum+=bit[index];
return sum;
}
public int sum(int l,int r){
return presum(r+1)-presum(l);
}
}
class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | f93cee835536bc75ebc402dd4691a9ec | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
int T = in.nextInt();
int mod = 998244353;
StringBuilder sb = new StringBuilder();
for(int t=0; t<T; t++ ){
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int q = in.nextInt();
long ans = 1;
int[][] query = new int[q][2];
HashSet<Integer> x = new HashSet<Integer>();
HashSet<Integer> y = new HashSet<Integer>();
for(int i=0; i<q; i++){
query[i][0] = in.nextInt();
query[i][1] = in.nextInt();
}
for(int i=q-1; i>=0; i--){
if(!x.contains(query[i][0]) || !y.contains(query[i][1]))
ans = ans * k % mod;
x.add(query[i][0]);
y.add(query[i][1]);
if(x.size()==n || y.size()==m)
break;
}
sb.append(ans);
sb.append("\n");
}
System.out.println(sb);
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 5f801d5bcbc50dc62309d2a32cfd66b0 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef {
static long fans[] = new long[200001];
static long inv[] = new long[200001];
static long mod = 998244353;
static void init() {
fans[0] = 1;
inv[0] = 1;
fans[1] = 1;
inv[1] = 1;
for (int i = 2; i < 200001; i++) {
fans[i] = ((long) i * fans[i - 1]) % mod;
inv[i] = power(fans[i], mod - 2);
}
}
static long ncr(int n, int r) {
return (((fans[n] * inv[n - r]) % mod) * (inv[r])) % mod;
}
public static void main(String[] args) throws java.lang.Exception {
FastReader in = new FastReader(System.in);
StringBuilder sb = new StringBuilder();
int t = 1;
t = in.nextInt();
while (t > 0) {
--t;
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int q = in.nextInt();
int arr[][] = new int[q][2];
for(int i = 0;i<q;i++)
{
arr[i][0] = in.nextInt();
arr[i][1] = in.nextInt();
}
HashSet<Integer> x = new HashSet<>();
HashSet<Integer> y = new HashSet<>();
int cnt = 0;
for(int i = q-1;i>=0;i--)
{
int ri = arr[i][0];
int ci = arr[i][1];
boolean r = false;
boolean c = false;
if(x.size() == n || y.contains(ci))
c = true;
if(y.size() == m || x.contains(ri))
r = true;
if(c && r)
continue;
++cnt;
x.add(ri);
y.add(ci);
}
long ans = power(k,cnt);
sb.append(ans+"\n");
}
System.out.print(sb);
}
static long power(long x, long y) {
long res = 1; // Initialize result
while (y > 0) {
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = ((res % mod) * (x % mod)) % mod;
// y must be even now
y = y >> 1; // y = y/2
x = ((x % mod) * (x % mod)) % mod; // Change x to x^2
}
return res;
}
static long[] generateArray(FastReader in, int n) throws IOException {
long arr[] = new long[n];
for (int i = 0; i < n; i++)
arr[i] = in.nextLong();
return arr;
}
static long[][] generatematrix(FastReader in, int n, int m) throws IOException {
long arr[][] = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = in.nextLong();
}
}
return arr;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
else
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
}
}
class FastReader {
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
return (char) c;
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | b1947ecfc564b4b6d19bf5c4c593f918 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class D1644 {
static int mod = 998244353;
public static long modPow(long a, long e) {
if (e == 0)
return 1;
long prev = modPow(a, e / 2);
if (e % 2 == 1) {
return a * prev % mod * prev % mod;
}
return prev * prev % mod;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int q = sc.nextInt();
int[][] a = new int[q][2];
for (int i = 0; i < q; i++) {
a[i][0] = sc.nextInt();
a[i][1] = sc.nextInt();
}
HashSet<Integer> rows = new HashSet<>();
HashSet<Integer> cols = new HashSet<>();
int cnt = 0;
for (int i = q - 1; i >= 0; i--) {
if (rows.contains(a[i][0]) && cols.contains(a[i][1]))
continue;
if (rows.size() == n || cols.size() == m)
continue;
cnt++;
rows.add(a[i][0]);
cols.add(a[i][1]);
}
pw.println(modPow(k, cnt));
}
pw.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader f) {
br = new BufferedReader(f);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(next());
}
return arr;
}
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 3373d30e98f266bba5154b4e3f3bf807 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
/**
* @author Naitik
*
*/
public class Main
{
static FastReader sc=new FastReader();
static long dp[];
// static boolean v[][][];
static int mod=998244353;;
// static int mod=1000000007;
static int max;
static int bit[];
//static long fact[];
// static long A[];
static HashMap<Integer,Integer> map;
//static StringBuffer sb=new StringBuffer("");
//static HashMap<Integer,Integer> map;
static long fac[];
static PrintWriter out=new PrintWriter(System.out);
public static void main(String[] args)
{
// StringBuffer sb=new StringBuffer("");
int ttt=1;
ttt =i();
outer :while (ttt-- > 0)
{
long n=i(),m=i();
long k=i();
int q=i();
int A[]=new int[q];
int B[]=new int[q];
input(A, B);
long ans=1;
HashMap<Integer,Integer> r=hash(A);
HashMap<Integer,Integer> c=hash(B);
for(int i=0;i<q;i++) {
int a=r.get(A[i]);
int b=c.get(B[i]);
r.put(A[i], a-1);
c.put(B[i], b-1);
if(r.get(A[i])==0)
r.remove(A[i]);
if(c.get(B[i])==0)
c.remove(B[i]);
if(a>1 && b>1)
continue;
if(a==1) {
if(c.size()==m)
continue;
}
else if(b==1) {
if(r.size()==n)
continue;
}
ans*=k;
ans%=mod;
}
System.out.println(ans);
}
//System.out.println(sb.toString());
out.close();
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1
}
static class Pair implements Comparable<Pair>
{
int x;
int y;
int z;
Pair(int x,int y){
this.x=x;
this.y=y;
// this.z=z;
}
@Override
public int compareTo(Pair o) {
if(this.x>o.x)
return 1;
else if(this.x<o.x)
return -1;
else {
if(this.y>o.y)
return 1;
else if(this.y<o.y)
return -1;
else
return 0;
}
}
public int hashCode()
{
final int temp = 14;
int ans = 1;
ans =x*31+y*13;
return ans;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (this.getClass() != o.getClass()) {
return false;
}
Pair other = (Pair)o;
if (this.x != other.x || this.y!=other.y) {
return false;
}
return true;
}
//
/* FOR TREE MAP PAIR USE */
// public int compareTo(Pair o) {
// if (x > o.x) {
// return 1;
// }
// if (x < o.x) {
// return -1;
// }
// if (y > o.y) {
// return 1;
// }
// if (y < o.y) {
// return -1;
// }
// return 0;
// }
}
static int find(int A[],int a) {
if(A[a]==a)
return a;
return A[a]=find(A, A[a]);
}
//static int find(int A[],int a) {
// if(A[a]==a)
// return a;
// return find(A, A[a]);
//}
//FENWICK TREE
static void update(int i, int x){
for(; i < bit.length; i += (i&-i))
bit[i] += x;
}
static int sum(int i){
int ans = 0;
for(; i > 0; i -= (i&-i))
ans += bit[i];
return ans;
}
//END
static void add(int v) {
if(!map.containsKey(v)) {
map.put(v, 1);
}
else {
map.put(v, map.get(v)+1);
}
}
static void remove(int v) {
if(map.containsKey(v)) {
map.put(v, map.get(v)-1);
if(map.get(v)==0)
map.remove(v);
}
}
public static int upper(int A[],int k,int si,int ei)
{
int l=si;
int u=ei;
int ans=-1;
while(l<=u) {
int mid=(l+u)/2;
if(A[mid]<=k) {
ans=mid;
l=mid+1;
}
else {
u=mid-1;
}
}
return ans;
}
public static int lower(int A[],int k,int si,int ei)
{
int l=si;
int u=ei;
int ans=-1;
while(l<=u) {
int mid=(l+u)/2;
if(A[mid]<=k) {
l=mid+1;
}
else {
ans=mid;
u=mid-1;
}
}
return ans;
}
static int[] copy(int A[]) {
int B[]=new int[A.length];
for(int i=0;i<A.length;i++) {
B[i]=A[i];
}
return B;
}
static long[] copy(long A[]) {
long B[]=new long[A.length];
for(int i=0;i<A.length;i++) {
B[i]=A[i];
}
return B;
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void reverse(long A[]) {
int n=A.length;
long B[]=new long[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void reverse(int A[]) {
int n=A.length;
int B[]=new int[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void input(int A[],int B[]) {
for(int i=0;i<A.length;i++) {
A[i]=sc.nextInt();
B[i]=sc.nextInt();
}
}
static int[][] input(int n,int m){
int A[][]=new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
A[i][j]=i();
}
}
return A;
}
static char[][] charinput(int n,int m){
char A[][]=new char[n][m];
for(int i=0;i<n;i++) {
String s=s();
for(int j=0;j<m;j++) {
A[i][j]=s.charAt(j);
}
}
return A;
}
static int nextPowerOf2(int n)
{
if(n==0)
return 1;
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
static int highestPowerof2(int x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
static long highestPowerof2(long x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
static int max(int A[]) {
int max=Integer.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static int min(int A[]) {
int min=Integer.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long max(long A[]) {
long max=Long.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static long min(long A[]) {
long min=Long.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long [] prefix(long A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] prefix(int A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] suffix(long A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static long [] suffix(int A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static void fill(int dp[]) {
Arrays.fill(dp, -1);
}
static void fill(int dp[][]) {
for(int i=0;i<dp.length;i++)
Arrays.fill(dp[i], -1);
}
static void fill(int dp[][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
Arrays.fill(dp[i][j],-1);
}
}
}
static void fill(int dp[][][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
for(int k=0;k<dp[0][0].length;k++) {
Arrays.fill(dp[i][j][k],-1);
}
}
}
}
static void fill(long dp[]) {
Arrays.fill(dp, -1);
}
static void fill(long dp[][]) {
for(int i=0;i<dp.length;i++)
Arrays.fill(dp[i], -1);
}
static void fill(long dp[][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
Arrays.fill(dp[i][j],-1);
}
}
}
static void fill(long dp[][][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
for(int k=0;k<dp[0][0].length;k++) {
Arrays.fill(dp[i][j][k],-1);
}
}
}
}
static int min(int a,int b) {
return Math.min(a, b);
}
static int min(int a,int b,int c) {
return Math.min(a, Math.min(b, c));
}
static int min(int a,int b,int c,int d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static int max(int a,int b) {
return Math.max(a, b);
}
static int max(int a,int b,int c) {
return Math.max(a, Math.max(b, c));
}
static int max(int a,int b,int c,int d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long min(long a,long b) {
return Math.min(a, b);
}
static long min(long a,long b,long c) {
return Math.min(a, Math.min(b, c));
}
static long min(long a,long b,long c,long d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static long max(long a,long b) {
return Math.max(a, b);
}
static long max(long a,long b,long c) {
return Math.max(a, Math.max(b, c));
}
static long max(long a,long b,long c,long d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long power(long x, long y, long p)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long power(long x, long y)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y = y >> 1;
x = (x * x);
}
return res;
}
static void print(int A[]) {
for(int i : A) {
out.print(i+" ");
}
out.println();
}
static void print(long A[]) {
for(long i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static long mod(long x) {
return ((x%mod + mod)%mod);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static void sort(int[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[]=new Character[s.length()];
for(int i=0;i<s.length();i++) {
ch[i]=s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st=new StringBuffer("");
for(int i=0;i<s.length();i++) {
st.append(ch[i]);
}
return st.toString();
}
static HashMap<Integer,Integer> hash(int A[]){
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static HashMap<Long,Integer> hash(long A[]){
HashMap<Long,Integer> map=new HashMap<Long, Integer>();
for(long i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Integer,Integer> tree(int A[]){
TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Long,Integer> tree(long A[]){
TreeMap<Long,Integer> map=new TreeMap<Long, Integer>();
for(long i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | c2cde8e626b0894860098029e850e24a | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | /*
* Created by cravuri on 2/22/22
*/
import java.util.Scanner;
public class D {
static final long MOD = 998244353;
static long pow(long a, long b) {
if (b == 0) return 1;
if (b == 1) return a;
long p = pow(a, b / 2);
long p2 = (p * p) % MOD;
if (b % 2 == 0) {
return p2;
} else {
return (p2 * a) % MOD;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 1; t <= T; t++) {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int q = sc.nextInt();
int[][] colorings = new int[q][2];
for (int i = 0; i < q; i++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
colorings[i] = new int[]{x, y};
}
int numValid = 0;
boolean[] seenX = new boolean[n];
int numX = 0;
boolean[] seenY = new boolean[m];
int numY = 0;
for (int i = q - 1; i >= 0; i--) {
if (seenX[colorings[i][0]] && seenY[colorings[i][1]]) {
continue;
}
numValid++;
if (!seenX[colorings[i][0]]) {
seenX[colorings[i][0]] = true;
numX++;
if (numX == n) break;
}
if (!seenY[colorings[i][1]]) {
seenY[colorings[i][1]] = true;
numY++;
if (numY == m) break;
}
}
System.out.println(pow(k, numValid));
}
}
}
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | ed3c38d60641a69b03f3628432364826 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static PrintWriter pw;
static Scanner sc;
static final int inf = (int) 1e9, mod = inf + 7;
static final long infL = inf * 1l * inf;
static final double eps = 1e-9;
public static void main(String[] args) throws Exception {
sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0)
testCase();
pw.close();
}
static void testCase() throws Exception {
int n = sc.nextInt(), m = sc.nextInt();
int k = sc.nextInt(), q = sc.nextInt();
HashMap<Integer, Integer> xs = new HashMap<>();
HashMap<Integer, Integer> ys = new HashMap<>();
for (int i = 0; i < q; i++) {
int x = sc.nextInt(), y = sc.nextInt();
if(!xs.containsKey(x))
xs.put(x, -1);
xs.replace(x, i);
if(!ys.containsKey(y))
ys.put(y, -1);
ys.replace(y, i);
}
int minX = q, minY = q;
for (int x : xs.values())
minX = Math.min(x, minX);
for (int y : ys.values())
minY = Math.min(y, minY);
if(xs.size() != n)
minX = 0;
if(ys.size() != m)
minY = 0;
HashSet<Integer> deleteX = new HashSet<>(), deleteY = new HashSet<>();
for (Map.Entry<Integer, Integer> a : xs.entrySet()){
if(a.getValue() < minY)
deleteX.add(a.getKey());
}
for (int x : deleteX)
xs.remove(x);
for (Map.Entry<Integer, Integer> a : ys.entrySet()){
if(a.getValue() < minX)
deleteY.add(a.getKey());
}
for (int y : deleteY)
ys.remove(y);
HashSet<Integer> time = new HashSet<>();
time.addAll(xs.values());
int ans = xs.size() + ys.size();
for (int x : ys.values()) {
if(time.contains(x))
ans--;
}
pw.println(modPow(k, ans, 998244353));
}
static long modPow(long a, int e, int mod) {
a %= mod;
long res = 1;
while (e > 0) {
if ((e & 1) == 1)
res = (res * a) % mod;
a = (a * a) % mod;
e >>= 1;
}
return res;
}
static long ceildiv(long x, long y) {
return (x + y - 1) / y;
}
static int mod(long x, int m) {
return (int) ((x % m + m) % m);
}
static void add(Map<Integer, Integer> map, Integer p) {
if (map.containsKey(p)) map.replace(p, map.get(p) + 1);
else map.put(p, 1);
}
static void rem(Map<Integer, Integer> map, Integer p) {
if (map.get(p) == 1) map.remove(p);
else map.replace(p, map.get(p) - 1);
}
static int Int(boolean x) {
return x ? 1 : 0;
}
public static long gcd(long x, long y) {
return y == 0 ? x : gcd(y, x % y);
}
static void printArr(int[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(long[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(double[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(boolean[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] ? 1 : 0);
pw.println();
}
static void printArr(Integer[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printIter(Iterable list) {
for (Object o : list)
pw.print(o + " ");
pw.println();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextDigits() throws IOException {
String s = nextLine();
int[] arr = new int[s.length()];
for (int i = 0; i < arr.length; i++)
arr[i] = s.charAt(i) - '0';
return arr;
}
public int[] nextArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt();
return arr;
}
public Integer[] nextsort(int n) throws IOException {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public int[] nextArrMinus1(int n) throws IOException{
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt() - 1;
return arr;
}
public Pair nextPair() throws IOException {
return new Pair(nextInt(), nextInt());
}
public long[] nextLongArr(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public Pair[] nextPairArr(int n) throws IOException {
Pair[] arr = new Pair[n];
for (int i = 0; i < n; i++)
arr[i] = nextPair();
return arr;
}
public boolean hasNext() throws IOException {
return (st != null && st.hasMoreTokens()) || br.ready();
}
}
static class Pair implements Comparable<Pair> {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public Pair(Map.Entry<Integer, Integer> a) {
x = a.getKey();
y = a.getValue();
}
public int hashCode() {
return (int) ((this.x * 1l * 100003 + this.y) % mod);
}
public int compareTo(Pair p) {
if (x != p.x)
return x - p.x;
return y - p.y;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Pair p = (Pair) obj;
return this.x == p.x && this.y == p.y;
}
public Pair clone() {
return new Pair(x, y);
}
public String toString() {
return this.x + " " + this.y;
}
public void subtract(Pair p) {
x -= p.x;
y -= p.y;
}
public void add(Pair p) {
x += p.x;
y += p.y;
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 138d878f1f4a76b91ad22b897c9203fb | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static BufferedReader bf;
static PrintWriter out;
static Scanner sc;
static StringTokenizer st;
// static long mod = (long)(1e9+7);
static long mod = 998244353;
static long fact[];
static long inverse[];
public static void main (String[] args)throws IOException {
bf = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new Scanner(System.in);
// fact = new long[1000000];
// inverse = new long[1000000];
// fact[0] = 1;
// inverse[0] = 1;
// for(int i = 1;i<fact.length;i++){
// fact[i] = (fact[i-1] * i)%mod;
// inverse[i] = binaryExpo(fact[i], mod-2);
// }
int t = nextInt();
while(t-->0){
solve();
}
out.flush();
}
public static void solve()throws IOException{
int n = nextInt();
int m = nextInt();
long k = nextLong();
int q = nextInt();
int[][]query = new int[q][2];
for(int i = 0 ;i<q;i++){
query[i][0] = nextInt();
query[i][1] = nextInt();
}
long ans = 1;
Set<Integer>cols = new HashSet<>();
Set<Integer>rows = new HashSet<>();
for(int i = q-1;i>=0;i--){
int row = query[i][0];
int col = query[i][1];
if(cols.size() == m || rows.size() == n || (cols.contains(col) && rows.contains(row)))continue;
cols.add(col);
rows.add(row);
ans = (ans * k)%mod;
}
out.println(ans);
}
public static int summer(int node , int l,int r,int tl,int tr,int[][]tree){
if(l>=tl && r <= tr)return tree[node][1];
if(r < tl || l > tr)return 0;
int mid = (l + r)/2;
return summer(node * 2 , l , mid , tl,tr,tree) + summer(node * 2 + 1 , mid + 1 , r, tl , tr, tree);
}
public static int oner(int node , int l,int r,int tl,int tr,int[][]tree){
if(l>=tl && r <= tr)return tree[node][0];
if(r < tl || l > tr)return 0;
int mid = (l + r)/2;
return oner(node * 2 , l , mid , tl,tr,tree) + oner(node * 2 + 1 , mid + 1 , r, tl , tr, tree);
}
public static int compare(String a , String b){
if(a.compareTo(b) < 0)return -1;
if(a.compareTo(b) > 0)return 1;
return 0;
}
public static void req(long l,long r){
out.println("? " + l + " " + r);
out.flush();
}
public static long nck(int n,int k){
return ((fact[n] * (inverse[n-k])%mod) * inverse[k])%mod;
}
public static long binaryExpo(long base,long expo){
if(expo == 0)return 1;
long val;
if(expo%2 == 1){
val = (binaryExpo(base, expo/2));
val = (val * val)%mod;
val = (val * base)%mod;
}
else{
val = binaryExpo(base, expo/2);
val = (val*val)%mod;
}
return (val%mod);
}
public static boolean isSorted(int[]arr){
for(int i =1;i<arr.length;i++){
if(arr[i] < arr[i-1]){
return false;
}
}
return true;
}
//function to find the topological sort of the a DAG
public static boolean hasCycle(int[]indegree,List<List<Integer>>list,int n,List<Integer>topo){
Queue<Integer>q = new LinkedList<>();
for(int i =1;i<indegree.length;i++){
if(indegree[i] == 0){
q.add(i);
topo.add(i);
}
}
while(!q.isEmpty()){
int cur = q.poll();
List<Integer>l = list.get(cur);
for(int i = 0;i<l.size();i++){
indegree[l.get(i)]--;
if(indegree[l.get(i)] == 0){
q.add(l.get(i));
topo.add(l.get(i));
}
}
}
if(topo.size() == n)return false;
return true;
}
// function to find the parent of any given node with path compression in DSU
public static int find(int val,int[]parent){
if(val == parent[val])return val;
return parent[val] = find(parent[val],parent);
}
// function to connect two components
public static void union(int[]rank,int[]parent,int u,int v){
int a = find(u,parent);
int b= find(v,parent);
if(a == b)return;
if(rank[a] == rank[b]){
parent[b] = a;
rank[a]++;
}
else{
if(rank[a] > rank[b]){
parent[b] = a;
}
else{
parent[a] = b;
}
}
}
//
public static int findN(int n){
int num = 1;
while(num < n){
num *=2;
}
return num;
}
// code for input
public static void print(String s ){
System.out.print(s);
}
public static void print(int num ){
System.out.print(num);
}
public static void print(long num ){
System.out.print(num);
}
public static void println(String s){
System.out.println(s);
}
public static void println(int num){
System.out.println(num);
}
public static void println(long num){
System.out.println(num);
}
public static void println(){
System.out.println();
}
public static int Int(String s){
return Integer.parseInt(s);
}
public static long Long(String s){
return Long.parseLong(s);
}
public static String[] nextStringArray()throws IOException{
return bf.readLine().split(" ");
}
public static String nextString()throws IOException{
return bf.readLine();
}
public static long[] nextLongArray(int n)throws IOException{
String[]str = bf.readLine().split(" ");
long[]arr = new long[n];
for(int i =0;i<n;i++){
arr[i] = Long.parseLong(str[i]);
}
return arr;
}
public static int[][] newIntMatrix(int r,int c)throws IOException{
int[][]arr = new int[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Integer.parseInt(str[j]);
}
}
return arr;
}
public static long[][] newLongMatrix(int r,int c)throws IOException{
long[][]arr = new long[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Long.parseLong(str[j]);
}
}
return arr;
}
static class pair{
int one;
int two;
pair(int one,int two){
this.one = one ;
this.two =two;
}
}
public static long gcd(long a,long b){
if(b == 0)return a;
return gcd(b,a%b);
}
public static long lcm(long a,long b){
return (a*b)/(gcd(a,b));
}
public static boolean isPalindrome(String s){
int i = 0;
int j = s.length()-1;
while(i<=j){
if(s.charAt(i) != s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
// these functions are to calculate the number of smaller elements after self
public static void sort(int[]arr,int l,int r){
if(l < r){
int mid = (l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
smallerNumberAfterSelf(arr, l, mid, r);
}
}
public static void smallerNumberAfterSelf(int[]arr,int l,int mid,int r){
int n1 = mid - l +1;
int n2 = r - mid;
int []a = new int[n1];
int[]b = new int[n2];
for(int i = 0;i<n1;i++){
a[i] = arr[l+i];
}
for(int i =0;i<n2;i++){
b[i] = arr[mid+i+1];
}
int i = 0;
int j =0;
int k = l;
while(i<n1 && j < n2){
if(a[i] < b[j]){
arr[k++] = a[i++];
}
else{
arr[k++] = b[j++];
}
}
while(i<n1){
arr[k++] = a[i++];
}
while(j<n2){
arr[k++] = b[j++];
}
}
public static String next(){
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bf.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
static int nextInt() {
return Integer.parseInt(next());
}
static long nextLong() {
return Long.parseLong(next());
}
static double nextDouble() {
return Double.parseDouble(next());
}
static String nextLine(){
String str = "";
try {
str = bf.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// use some math tricks it might help
// sometimes just try to think in straightforward plan in A and B problems don't always complecate the questions with thinking too much differently
// always use long number to do 10^9+7 modulo
// if a problem is related to binary string it could also be related to parenthesis
// *****try to use binary search(it is a very beautiful thing it can work in some of the very unexpected problems ) in the question it might work******
// try sorting
// try to think in opposite direction of question it might work in your way
// if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+d or a,b,c,d in general
// if the question is to much related to left and/or right side of any element in an array then try monotonic stack it could work.
// in range query sums try to do binary search it could work
// analyse the time complexity of program thoroughly
// anylyse the test cases properly
// if we divide any number by 2 till it gets 1 then there will be (number - 1) operation required
// try to do the opposite operation of what is given in the problem
//think about the base cases properly
//If a question is related to numbers try prime factorisation or something related to number theory
// keep in mind unique strings
//you can calculate the number of inversion in O(n log n)
// in a matrix you could sometimes think about row and cols indenpendentaly.
// Try to think in more constructive(means a way to look through various cases of a problem) way.
// observe the problem carefully the answer could be hidden in the given test cases itself. (A, B , C);
// when we have equations like (a+b = N) and we have to find the max of (a*b) then the values near to the N/2 must be chosen as (a and b);
// give emphasis to the number of occurences of elements it might help.
// if a number is even then we can find the pair for each and every number in that range whose bitwise AND is zero.
// if a you find a problem related to the graph make a graph
// There is atleast one prime number between the interval [n , 3n/2];
// If a problem is related to maths then try to form an mathematical equation.
// you can create any sum between (n * (n + 1)/2) with first n natural numbers.
| Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 7594f139447ff850ea626c6e2f9822c1 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CrossColoring {
public static PrintWriter out;
static ArrayList<ArrayList<Integer>>al;
static int ans;
static int min[];
static int max[];
static int MOD=998244353;
public static void main(String[] args)throws IOException {
JS sc=new JS();
out = new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int m=sc.nextInt();
int k=sc.nextInt();
int q=sc.nextInt();
int x[]=new int[q];
int y[]=new int[q];
for(int i=0;i<q;i++) {
x[i]=sc.nextInt();
y[i]=sc.nextInt();
}
long ans=1;
HashSet<Integer>hs1=new HashSet<>();
HashSet<Integer>hs2=new HashSet<>();
for(int i=q-1;i>=0;i--) {
boolean ok=false;
if(!hs1.contains(x[i])) {
ok=true;
hs1.add(x[i]);
}
if(!hs2.contains(y[i])) {
ok=true;
hs2.add(y[i]);
}
if(ok) {
ans=(ans*k)%MOD;
}
if(hs1.size()==n||hs2.size()==m) {
break;
}
}
out.println(ans);
}
out.close();
}
static class JS {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 008f71cb429e3cd4d4761cd99c4844a0 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | /*
I am dead inside
Do you like NCT, sKz, BTS?
5 4 3 2 1 Moonwalk
Imma knock it down like domino
Is this what you want? Is this what you want?
Let's ttalkbocky about that :()
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
public class x1644D
{
static final long MOD = 998244353L;
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
while(T-->0)
{
st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int Q = Integer.parseInt(st.nextToken());
int[] rows = new int[Q];
int[] cols = new int[Q];
for(int i=0; i < Q; i++)
{
st = new StringTokenizer(infile.readLine());
rows[i] = Integer.parseInt(st.nextToken());
cols[i] = Integer.parseInt(st.nextToken());
}
long res = 1L;
HashSet<Integer> rowSet = new HashSet<Integer>();
HashSet<Integer> colSet = new HashSet<Integer>();
for(int i=Q-1; i >= 0; i--)
{
if(rowSet.size() == N || colSet.size() == M)
break;
boolean important = rowSet.add(rows[i])|colSet.add(cols[i]);
if(important)
res = (res*K)%MOD;
}
sb.append(res+"\n");
}
System.out.print(sb);
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 9191937ad872f0c9be6e5fc5c96762b3 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
*
* @author pttrung
*/
public class D_Edu_Round_123 {
public static long MOD = 998244353;
static int[][] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int T = in.nextInt();
for (int z = 0; z < T; z++) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int q = in.nextInt();
int[][] data = new int[q][2];
for (int i = 0; i < q; i++) {
for (int j = 0; j < 2; j++) {
data[i][j] = in.nextInt() - 1;
}
}
HashSet<Integer> row = new HashSet<>();
HashSet<Integer> col = new HashSet<>();
int rowLeft = n;
int colLeft = m;
int total = 0;
for (int i = q - 1; i >= 0; i--) {
int r = data[i][0];
int c = data[i][1];
boolean add = false;
if (!row.contains(r) && colLeft != 0) {
row.add(r);
rowLeft--;
add = true;
}
if (!col.contains(c) && rowLeft != 0) {
col.add(c);
colLeft--;
add = true;
}
total += add ? 1 : 0;
}
out.println(pow(k, total));
}
out.close();
}
static int abs(int v) {
return v < 0 ? -v : v;
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x;
String y;
public Point(int start, String end) {
this.x = start;
this.y = end;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return (val * val) % MOD;
} else {
return (val * ((val * a) % MOD)) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 58caa3975344670693029e9d2fad8c79 | train_108.jsonl | 1645540500 | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.util.concurrent.TimeUnit;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class D_Cross_Coloring{
public static void main(String args[])throws IOException, ParseException{
Reader sc=new Reader();
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int m=sc.nextInt();
long k=sc.nextInt();
int qc=sc.nextInt();
int q[][]=new int[qc][2];
for(int i=0;i<qc;i++){
q[i][0]=sc.nextInt();
q[i][1]=sc.nextInt();
}
solve(n,m,k,q,qc);
}
}
private static void solve(int n, int m, long k, int[][] q, int qc) {
HashSet<Integer> setrow=new HashSet<Integer>();
HashSet<Integer> setcol=new HashSet<Integer>();
long res=1;
long mod=998244353;
for(int i=qc-1;i>=0;i--){
boolean flag=false;
if(!setrow.contains(q[i][0])){
flag=true;
setrow.add(q[i][0]);
}
if(!setcol.contains(q[i][1])){
flag=true;
setcol.add(q[i][1]);
}
if(flag)
res=(res%mod*k%mod)%mod;
if(setrow.size()==n||setcol.size()==m)
break;
}
System.out.println(res);
}
public static <K,V> Map<K,V> getLimitedSizedCache(int size){
/*Returns an unlimited sized map*/
if(size==0){
return (LinkedHashMap<K, V>) Collections.synchronizedMap(new LinkedHashMap<K, V>());
}
/*Returns the map with the limited size*/
Map<K, V> linkedHashMap = Collections.synchronizedMap(new LinkedHashMap<K, V>() {
protected boolean removeEldestEntry(Map.Entry<K, V> eldest)
{
return size() > size;
}
});
return linkedHashMap;
}
}
class BinarySearch<T extends Comparable<T>> {
T ele[];
int n;
public BinarySearch(T ele[],int n){
this.ele=(T[]) ele;
Arrays.sort(this.ele);
this.n=n;
}
public int lower_bound(T x){
//Return next smallest element greater than ewqual to the current element
int left=0;
int right=n-1;
while(left<=right){
int mid=left+(right-left)/2;
if(x.compareTo(ele[mid])==0)return mid;
if(x.compareTo(ele[mid])>0)left=mid+1;
else right=mid-1;
}
if(left ==n)return -1;
return left;
}
public int upper_bound(T x){
//Returns the highest element lss than equal to the current element
int left=0;
int right=n-1;
while(left<=right){
int mid=left+(right-left)/2;
if(x.compareTo(ele[mid])==0)return mid;
if(x.compareTo(ele[mid])>0)left=mid+1;
else right=mid-1;
}
return right;
}
}
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[1000000]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
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();
}
}
class Data implements Comparable<Data>{
int num;
public Data(int num){
this.num=num;
}
public int compareTo(Data o){
return -o.num+num;
}
public String toString(){
return num+" ";
}
}
class Binary{
public String convertToBinaryString(long ele){
StringBuffer res=new StringBuffer();
while(ele>0){
if(ele%2==0)res.append(0+"");
else res.append(1+"");
ele=ele/2;
}
return res.reverse().toString();
}
}
class FenwickTree{
int bit[];
int size;
FenwickTree(int n){
this.size=n;
bit=new int[size];
}
public void modify(int index,int value){
while(index<size){
bit[index]+=value;
index=(index|(index+1));
}
}
public int get(int index){
int ans=0;
while(index>=0){
ans+=bit[index];
index=(index&(index+1))-1;
}
return ans;
}
}
class PAndC{
long c[][];
long mod;
public PAndC(int n,long mod){
c=new long[n+1][n+1];
this.mod=mod;
build(n);
}
public void build(int n){
for(int i=0;i<=n;i++){
c[i][0]=1;
c[i][i]=1;
for(int j=1;j<i;j++){
c[i][j]=(c[i-1][j]+c[i-1][j-1])%mod;
}
}
}
}
class Trie{
int trie[][];
int revind[];
int root[];
int tind,n;
int sz[];
int drev[];
public Trie(){
trie=new int[1000000][2];
root=new int[600000];
sz=new int[1000000];
tind=0;
n=0;
revind=new int[1000000];
drev=new int[20];
}
public void add(int ele){
// System.out.println(root[n]+" ");
n++;
tind++;
revind[tind]=n;
root[n]=tind;
addimpl(root[n-1],root[n],ele);
}
public void addimpl(int prev_root,int cur_root,int ele){
for(int i=18;i>=0;i--){
int edge=(ele&(1<<i))>0?1:0;
trie[cur_root][1-edge]=trie[prev_root][1-edge];
sz[cur_root]=sz[trie[cur_root][1-edge]];
tind++;
drev[i]=cur_root;
revind[tind]=n;
trie[cur_root][edge]=tind;
cur_root=tind;
prev_root=trie[prev_root][edge];
}
sz[cur_root]+=sz[prev_root]+1;
for(int i=0;i<=18;i++){
sz[drev[i]]=sz[trie[drev[i]][0]]+sz[trie[drev[i]][1]];
}
}
public void findmaxxor(int l,int r,int x){
int ans=0;
int cur_root=root[r];
for(int i=18;i>=0;i--){
int edge=(x&(1<<i))>0?1:0;
if(revind[trie[cur_root][1-edge]]>=l){
cur_root=trie[cur_root][1-edge];
ans+=(1-edge)*(1<<i);
}else{
cur_root=trie[cur_root][edge];
ans+=(edge)*(1<<i);
}
}
System.out.println(ans);
}
public void findKthStatistic(int l,int r,int k){
//System.out.println("In 3");
int curr=root[r];
int curl=root[l-1];
int ans=0;
for(int i=18;i>=0;i--){
for(int j=0;j<2;j++){
if(sz[trie[curr][j]]-sz[trie[curl][j]]<k)
k-=sz[trie[curr][j]]-sz[trie[curl][j]];
else{
curr=trie[curr][j];
curl=trie[curl][j];
ans+=(j)*(1<<i);
break;
}
}
}
System.out.println(ans);
}
public void findSmallest(int l,int r,int x){
//System.out.println("In 4");
int curr=root[r];
int curl=root[l-1];
int countl=0,countr=0;
// System.out.println(curl+" "+curr);
for(int i=18;i>=0;i--){
int edge=(x&(1<<i))>0?1:0;
// System.out.println(trie[curl][edge]+" "+trie[curr][edge]+" "+sz[curl]+" "+sz[curr]);
if(edge==1){
countr+=sz[trie[curr][0]];
countl+=sz[trie[curl][0]];
}
curr=trie[curr][edge];
curl=trie[curl][edge];
}
countl+=sz[curl];
countr+=sz[curr];
System.out.println(countr-countl);
}
}
class Printer{
public <T> T printArray(T obj[] ,String details){
System.out.println(details);
for(int i=0;i<obj.length;i++)
System.out.print(obj[i]+" ");
System.out.println();
return obj[0];
}
public <T> void print(T obj,String details){
System.out.println(details+" "+obj);
}
}
class Node{
long weight;
int vertex;
public Node(int vertex,long weight){
this.vertex=vertex;
this.weight=weight;
}
public String toString(){
return vertex+" "+weight;
}
}
class Graph{
int nv; //0 indexing i.e vertices starts from 0 input as 1 indexed for add Edge
List<List<Node>> adj;
boolean visited[];
public Graph(int n){
adj=new ArrayList<>();
this.nv=n;
// visited=new boolean[nv];
for(int i=0;i<n;i++)
adj.add(new ArrayList<Node>());
}
public void addEdge(int u,int v,long weight){
u--;v--;
Node first=new Node(v,weight);
Node second=new Node(u,weight);
adj.get(v).add(second);
adj.get(u).add(first);
}
public void dfscheck(int u,long curweight){
visited[u]=true;
for(Node i:adj.get(u)){
if(visited[i.vertex]==false&&(i.weight|curweight)==curweight)
dfscheck(i.vertex,curweight);
}
}
long maxweight;
public void clear(){
this.adj=null;
this.nv=0;
}
public void solve() {
maxweight=(1l<<32)-1;
dfsutil(31);
System.out.println(maxweight);
}
public void dfsutil(int msb){
if(msb<0)return;
maxweight-=(1l<<msb);
visited=new boolean[nv];
dfscheck(0,maxweight);
for(int i=0;i<nv;i++)
{
if(visited[i]==false)
{maxweight+=(1<<msb);
break;}
}
dfsutil(msb-1);
}
// public boolean TopologicalSort() {
// top=new int[nv];
// int cnt=0;
// int indegree[]=new int[nv];
// for(int i=0;i<nv;i++){
// for(int j:adj.get(i)){
// indegree[j]++;
// }
// }
// Deque<Integer> q=new LinkedList<Integer>();
// for(int i=0;i<nv;i++){
// if(indegree[i]==0){
// q.addLast(i);
// }
// }
// while(q.size()>0){
// int tele=q.pop();
// top[tele]=cnt++;
// for(int j:adj.get(tele)){
// indegree[j]--;
// if(indegree[j]==0)
// q.addLast(j);
// }
// }
// return cnt==nv;
// }
// public boolean isBipartiteGraph(){
// col=new Integer[nv];
// visited=new boolean[nv];
// for(int i=0;i<nv;i++){
// if(visited[i]==false){
// col[i]=0;
// dfs(i);
// }
// }
}
class DSU{
int []parent;
int rank[];
int n;
public DSU(int n){
this.n=n;
parent=new int[n];
rank=new int[n];
for(int i=0;i<n;i++)
{ parent[i]=i;
rank[i]=1;
}
}
public int find(int i){
if(parent[i]==i)return i;
return parent[i]=find(parent[i]);
}
public boolean union(int a,int b){
int pa=find(a);
int pb=find(b);
if(pa==pb)return false;
if(rank[pa]>rank[pb]){
parent[pb]=pa;
rank[pa]+=rank[pb];
}
else{
parent[pa]=pb;
rank[pb]+=rank[pa];
}
return true;
}
} | Java | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | 2 seconds | ["3\n4"] | null | Java 8 | standard input | [
"data structures",
"implementation",
"math"
] | 623a373709e4c4223fbbb9a320f307b1 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 1,700 | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.