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
0d695a20a0fbae12a6b0a8312d8827ec
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 { //--------------------------INPUT READER---------------------------------// static class fs { public BufferedReader br; StringTokenizer st = new StringTokenizer(""); public fs() { this(System.in); } public fs(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long nn) { int n = (int) nn; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(long nn) { int n = (int) nn; long[] l = new long[n]; for(int i = 0; i < n; i++) l[i] = nl(); return l; } } //-----------------------------------------------------------------------// //---------------------------PRINTER-------------------------------------// static class Printer { static PrintWriter w; public Printer() {this(System.out);} public Printer(OutputStream os) { w = new PrintWriter(os); } public void p(int i) {w.println(i);} public void p(long l) {w.println(l);} public void p(double d) {w.println(d);} public void p(String s) { w.println(s);} public void pr(int i) {w.print(i);} public void pr(long l) {w.print(l);} public void pr(double d) {w.print(d);} public void pr(String s) { w.print(s);} public void pl() {w.println();} public void close() {w.close();} } //-----------------------------------------------------------------------// //--------------------------VARIABLES------------------------------------// static fs sc = new fs(); static OutputStream outputStream = System.out; static Printer w = new Printer(outputStream); static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static long mod = 998244353L; //-----------------------------------------------------------------------// //--------------------------ADMIN_MODE-----------------------------------// private static void ADMIN_MODE() throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { w = new Printer(new FileOutputStream("output.txt")); sc = new fs(new FileInputStream("input.txt")); } } //-----------------------------------------------------------------------// //----------------------------START--------------------------------------// public static void main(String[] args) throws IOException { ADMIN_MODE(); int t = sc.ni();while(t-->0) solve(); w.close(); } static void solve() throws IOException { int n = sc.ni(), m = sc.ni(), k = sc.ni(), q = sc.ni(); HashSet<Integer> col = new HashSet<>(), row = new HashSet<>(); List<pr> qs = new ArrayList<>(); for(int i = 0; i < q; i++) { qs.add(new pr(sc.ni(), sc.ni())); } long ans = 1; for(int i = q-1; i >= 0; i--) { pr curr = qs.get(i); if(!col.contains(curr.y) || !row.contains(curr.x)) { ans *= k; ans %= mod; col.add(curr.y); row.add(curr.x); if(col.size() == m || row.size() == n) break; } } w.p(ans); } static class pr { int x, y; public pr(int x, int y) { this.x = x; this.y = 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
3d071832d9e9a1bc0e3ad150c19b9b45
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 Solution { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuffer out = new StringBuffer(); int T = in.nextInt(); OUTER: while (T-->0) { int n = in.nextInt(), m = in.nextInt(); int k = in.nextInt(), q = in.nextInt(); int[][] a = new int[q][2]; for(int i=q-1; i>=0; i--) { for(int j=0; j<2; j++) { a[i][j] = in.nextInt(); } } HashSet<Integer> setX = new HashSet<>(), setY = new HashSet<>(); long ans = 1L; for(int i=0; i<q; i++) { boolean flag = false; if(!setX.contains(a[i][0])) { setX.add(a[i][0]); flag = true; } if(!setY.contains(a[i][1])) { setY.add(a[i][1]); flag = true; } if(flag) { ans = (ans*k)%998244353; } if(setX.size()==n || setY.size()==m) { break; } } out.append(ans+"\n"); } System.out.print(out); } private static long gcd(long a, long b) { if (a==0) return b; return gcd(b%a, a); } private static int toInt(String s) { return Integer.parseInt(s); } private static long toLong(String s) { return Long.parseLong(s); } private static void print(String s) { System.out.print(s); } private static void println(String s) { System.out.println(s); } }
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
2cdcee0cad491217d1fda038006ccf2f
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.IOException; import java.io.*; import java.util.*; public class CrossColoring { static long mod=998244353; static InputReader inputReader=new InputReader(System.in); static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static void solve() throws IOException { int n=inputReader.nextInt(); int m=inputReader. nextInt(); int k=inputReader.nextInt(); int q=inputReader.nextInt(); HashSet<Integer>row=new HashSet<>(); HashSet<Integer>col=new HashSet<>(); int [][]queries=new int[q][2]; for (int i=0;i<q;i++) { int x=inputReader.nextInt(); int y=inputReader.nextInt(); queries[i][0]=x; queries[i][1]=y; } long ans=1; for (int i=q-1;i>=0;i--) { int r=queries[i][0]; int c=queries[i][1]; boolean cantake=false; if (!row.contains(r)) { cantake=true; row.add(r); } if (!col.contains(c)) { col.add(c); cantake=true; } if(cantake==true) { ans=ans*k; ans=ans%mod; } if (row.size()==n||col.size()==m) { break; } } out.println(ans); } static PrintWriter out=new PrintWriter((System.out)); static void SortDec(long arr[]) { List<Long>list=new ArrayList<>(); for(long ele:arr) { list.add(ele); } Collections.sort(list,Collections.reverseOrder()); for (int i=0;i<list.size();i++) { arr[i]=list.get(i); } } static void Sort(long arr[]) { List<Long>list=new ArrayList<>(); for(long ele:arr) { list.add(ele); } Collections.sort(list); for (int i=0;i<list.size();i++) { arr[i]=list.get(i); } } public static void main(String args[])throws IOException { int t=inputReader.nextInt(); while (t-->0) { solve();} long s = System.currentTimeMillis(); // out.println(System.currentTimeMillis()-s+"ms"); out.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public 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
["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
0b56c354c40509d8475a2a2ae3f8e38a
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.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; 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.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.text.DecimalFormat; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static int _gcd(int a, int b) { if (b == 0) return a; return _gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } public static void solve(InputReader sc, PrintWriter pw) { int t=sc.nextInt(); for(int k=1;k<=t;k++) { int n=sc.nextInt(); int m=sc.nextInt(); int kk=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();} Set<Integer> row=new HashSet<>(); Set<Integer> col=new HashSet<>(); int 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 mod=998244353; long ans=fast_pow(kk, count,mod); pw.print(ans+"\n"); } pw.print("\n"); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String nextLine() { return 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
4497f46100c878dc82c9c5d6ff58fd7b
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); // int a = 1; int t; t = in.nextInt(); //t = 1; while (t > 0) { // out.print("Case #"+(a++)+": "); solver.call(in,out); t--; } out.close(); } static class TaskA { public void call(InputReader in, PrintWriter out) { int n, m, k, q, x, y; n = in.nextInt(); m = in.nextInt(); k = in.nextInt(); q = in.nextInt(); int a = 0; answer[] array = new answer[q]; for (int i = 0; i < q; i++) { x = in.nextInt() - 1; y = in.nextInt() - 1; array[i] = new answer(x, y); } Set<Integer> set = new HashSet<>(); Set<Integer> set1 = new HashSet<>(); for (int i = q - 1; i >= 0; i--) { if(set.size()==n || set1.size() == m){ break; } if(set.contains(array[i].a) && set1.contains(array[i].b)){ continue; } set.add(array[i].a); set1.add(array[i].b); a++; } long ans = exp(k, a) %mod; out.println(ans); } static long mod = 998244353; static long mul(long a, long b) { return a * b % mod; } static long exp(long base, long pow) { if (pow == 0) return 1; long half = exp(base, pow / 2); if (pow % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } } static int gcd(int a, int b ) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static class answer implements Comparable<answer>{ int a, b; public answer(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(answer o) { return Integer.compare(this.b, o.b); } } static class answer1 implements Comparable<answer1>{ int a, b, c; public answer1(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public int compareTo(answer1 o) { return (o.a - this.a); } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (Long i:a) l.add(i); l.sort(Collections.reverseOrder()); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static final Random random=new Random(); static void shuffleSort(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 class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
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
7a3ad2a7b98a8b027cbff5bc41031e22
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.Closeable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.*; public class CrossColoring implements Closeable { private final InputReader in; private final PrintWriter out; public CrossColoring() { in = new InputReader(System.in); out = new PrintWriter(System.out); } public void solve() { int t = in.ni(); final long MOD = 998244353; while (t-- > 0) { int n = in.ni(), m = in.ni(), k = in.ni(), q = in.ni(); List<int[]> queries = new ArrayList<>(); for (int i = 0; i < q; i++) { queries.add(new int[]{in.ni(), in.ni()}); } Set<Integer> row = new HashSet<>(), col = new HashSet<>(); long result = 1L; for (int i = q - 1; i >= 0; i--) { int[] query = queries.get(i); if (!(row.contains(query[0]) || col.size() == m) || !(col.contains(query[1]) || row.size() == n)) { result = (result * k) % MOD; row.add(query[0]); col.add(query[1]); } } out.println(result); } } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (CrossColoring instance = new CrossColoring()) { instance.solve(); } } }
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
799aac65d8efedb154f472a3ee65bf34
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.lang.reflect.Array; import java.util.*; public final class D { static int MOD; public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int T = fs.nextInt(); for(int tt = 0; tt < T; ++tt){ int n = fs.nextInt(); int m =fs.nextInt(); int k =fs.nextInt(); int q = fs.nextInt(); MOD = (int)998244353; HashSet<Integer> row = new HashSet<>(); HashSet<Integer> col= new HashSet<>(); long ans = 1; int[][] queries = new int[q][2]; for(int i = 0; i < q; ++i){ queries[i] = fs.readArray(2); } int rows = 0; int cols = 0; for(int i = q - 1; i >= 0; --i){ int r = queries[i][0]; int c = queries[i][1]; if((!row.contains(r) || !col.contains(c)) && (rows < n && cols < m)){ ans *= k; ans %= MOD; } if(!row.contains(r)) rows++; if(!col.contains(c)) cols++; row.add(r); col.add(c); } System.out.println(ans); } } static final Random random = new Random(); static final int mod = 1_000_000_007; static long add(long a, long b) { return (a + b) % mod; } static long sub(long a, long b) { return ((a - b) % mod + mod) % mod; } 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 long mul(long a, long b) { return (a * b) % mod; } static long exp(long base, long exp) { if (exp == 0) return 1; long half = exp(base, exp / 2); if (exp % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials = new long[2_000_001]; static long[] invFactorials = new long[2_000_001]; static void precompFacts() { factorials[0] = invFactorials[0] = 1; for (int i = 1; i < factorials.length; i++) factorials[i] = mul(factorials[i - 1], i); invFactorials[factorials.length - 1] = exp(factorials[factorials.length - 1], mod - 2); for (int i = invFactorials.length - 2; i >= 0; i--) invFactorials[i] = mul(invFactorials[i + 1], i + 1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n - k])); } 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
8daa0318022a04f6eeaf9fccbbcecaa2
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
/* Rating: 1367 Date: 22-02-2022 Time: 21-08-36 Author: Kartik Papney Linkedin: https://www.linkedin.com/in/kartik-papney-4951161a6/ Leetcode: https://leetcode.com/kartikpapney/ Codechef: https://www.codechef.com/users/kartikpapney */ import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class D_Cross_Coloring { public static boolean debug = false; static void debug(String st) { if(debug) p.writeln(st); } public static void s() { long n = sc.nextLong(); long m = sc.nextLong(); long k = sc.nextLong(); long q = sc.nextLong(); int[][] arr = new int[(int)q][2]; for(int i=0; i<q; i++) { arr[i][0] = sc.nextInt(); arr[i][1] = sc.nextInt(); } HashSet<Integer> row = new HashSet<>(), col = new HashSet<>(); long ans = 1; for(int i=arr.length-1; i>=0; i--) { if((row.contains(arr[i][0]) && col.contains(arr[i][1])) || row.size() == n || col.size() == m) { } else { ans = Functions.mod_mul(ans, k); } row.add(arr[i][0]); col.add(arr[i][1]); } p.writeln(ans); } public static void main(String[] args) { int t = 1; t = sc.nextInt(); while (t-- != 0) { s(); } p.print(); } static final Integer MOD = (int) 998244353; static final FastReader sc = new FastReader(); static final Print p = new Print(); static class Functions { 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 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 int max(int[] a) { int max = Integer.MIN_VALUE; for (int val : a) max = Math.max(val, max); return max; } static int min(int[] a) { int min = Integer.MAX_VALUE; for (int val : a) min = Math.min(val, min); return min; } static long min(long[] a) { long min = Long.MAX_VALUE; for (long val : a) min = Math.min(val, min); return min; } static long max(long[] a) { long max = Long.MIN_VALUE; for (long val : a) max = Math.max(val, max); return max; } static long sum(long[] a) { long sum = 0; for (long val : a) sum += val; return sum; } static int sum(int[] a) { int sum = 0; for (int val : a) sum += val; return sum; } public static long mod_add(long a, long b) { return (a % MOD + b % MOD + MOD) % MOD; } public static long pow(long a, long b) { long res = 1; while (b > 0) { if ((b & 1) != 0) res = mod_mul(res, a); a = mod_mul(a, a); b >>= 1; } return res; } public static long mod_mul(long a, long b) { long res = 0; a %= MOD; while (b > 0) { if ((b & 1) > 0) { res = mod_add(res, a); } a = (2 * a) % MOD; b >>= 1; } return res; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static long factorial(long n) { long res = 1; for (int i = 1; i <= n; i++) { res = (i % MOD * res % MOD) % MOD; } return res; } public static int count(int[] arr, int x) { int count = 0; for (int val : arr) if (val == x) count++; return count; } public static ArrayList<Integer> generatePrimes(int n) { boolean[] primes = new boolean[n]; for (int i = 2; i < primes.length; i++) primes[i] = true; for (int i = 2; i < primes.length; i++) { if (primes[i]) { for (int j = i * i; j < primes.length; j += i) { primes[j] = false; } } } ArrayList<Integer> arr = new ArrayList<>(); for (int i = 0; i < primes.length; i++) { if (primes[i]) arr.add(i); } return arr; } } static class Print { StringBuffer strb = new StringBuffer(); public void write(Object str) { strb.append(str); } public void writes(Object str) { char c = ' '; strb.append(str).append(c); } public void writeln(Object str) { char c = '\n'; strb.append(str).append(c); } public void writeln() { char c = '\n'; strb.append(c); } public void yes() { char c = '\n'; writeln("YES"); } public void no() { writeln("NO"); } public void writes(int[] arr) { for (int val : arr) { write(val); write(' '); } } public void writes(long[] arr) { for (long val : arr) { write(val); write(' '); } } public void writeln(int[] arr) { for (int val : arr) { writeln(val); } } public void print() { System.out.print(strb); } public void println() { System.out.println(strb); } } 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()); } 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; } double[] readArrayDouble(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } String nextLine() { String str = new String(); 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
4b640c3024c57b84bf928723f5e79e28
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.math.BigInteger; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int t = cin.nextInt(); Solution solution = new Solution(); for (int i = 0; i < t; i++) { int n = cin.nextInt(); int m = cin.nextInt(); int k = cin.nextInt(); int q = cin.nextInt(); int[][] sheet = new int[q][2]; for (int j = 0; j < q; j++) { sheet[j] = new int[]{cin.nextInt(), cin.nextInt()}; } System.out.println(solution.func(n, m, k, sheet)); } } } class Solution { public long func(int n, int m, int k, int[][] sheet) { long mod = 998244353; int cnt = 0; Set<Integer> row = new HashSet<>(); Set<Integer> col = new HashSet<>(); for (int i = sheet.length - 1; i >= 0; i--) { if ((!row.contains(sheet[i][0]) || !col.contains(sheet[i][1])) && row.size() != n && col.size() != m) { cnt++; } row.add(sheet[i][0]); col.add(sheet[i][1]); } return BigInteger.valueOf(k).modPow(BigInteger.valueOf(cnt), BigInteger.valueOf(mod)).longValue(); } }
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
aff057dcdee5ebd7ba10669d6256c69a
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 { public static void main(String[] args) throws Exception { mod=998244353; int t=sc.nextInt(); while(t-->0){ long n=sc.nextInt(); long m=sc.nextInt(); long k=sc.nextInt(); long q=sc.nextInt(); int[][]a=new int[(int)q][2]; for(int i=0;i<q;i++){ a[i][0]=sc.nextInt(); a[i][1]=sc.nextInt(); } long cnt=0; HashSet<Integer> row=new HashSet<>(); HashSet<Integer> column=new HashSet<>(); for(int i=(int)q-1;i>-1;i--){ boolean r=true; boolean c=true; if(row.contains(a[i][0])||(column.size()==m)){ r=false; } if(column.contains(a[i][1])||(row.size()==n)){ c=false; } if(c||r){ cnt++; row.add(a[i][0]); column.add(a[i][1]); } } pw.println(Pow(k,cnt,mod)); } pw.close(); } static long Pow(long a, long e, long mod) // O(log e) { a %= mod; long res = 1l; while (e > 0) { if ((e & 1) == 1) res = (res * a) % mod; a = (a * a) % mod; e >>= 1l; } return res; } 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(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
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
95d84a14bd2f6e23ae9ebbe1fd18fed7
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 static java.lang.Math.*; import static java.util.Map.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.lang.System.*; public class Main { public void tq() throws Exception { st=new StringTokenizer(bq.readLine()); int tq=i(); sb=new StringBuilder(2000000); o: while(tq-->0) { int n=i(); int m=i(); int k=i(); int q=i(); int qq[][]=ari(q,2); int cc=0; HashSet<Integer> r=new HashSet<>(); HashSet<Integer> c=new HashSet<>(); for(int e=q-1;e>=0;e--) { int x=qq[e][0]-1; int y=qq[e][1]-1; if(r.contains(x)&&c.contains(y))continue; r.add(x); c.add(y); cc++; if(r.size()==n||c.size()==m)break; } sl(mul(1l*k,1l*cc,mod)); } p(sb); } long mod=998244353l; int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE;long maxl=Long.MAX_VALUE,minl=Long.MIN_VALUE; BufferedReader bq = new BufferedReader(new InputStreamReader(in));StringTokenizer st;StringBuilder sb; public static void main(String[] a)throws Exception{new Main().tq();} int di[][]={{-1,0},{1,0},{0,-1},{0,1}}; int de[][]={{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{1,1},{-1,1},{1,-1}}; void f(){out.flush();} int p(int i,int p[]){return p[i]<0?i:(p[i]=p(p[i],p));} boolean c(int x,int y,int n,int m){return x>=0&&x<n&&y>=0&&y<m;} int[] so(int ar[]) { Integer r[] = new Integer[ar.length]; for (int x = 0; x < ar.length; x++) r[x] = ar[x]; sort(r); for (int x = 0; x < ar.length; x++) ar[x] = r[x]; return ar; } long[] so(long ar[]) { Long r[] = new Long[ar.length]; for (int x = 0; x < ar.length; x++) r[x] = ar[x]; sort(r); for (int x = 0; x < ar.length; x++) ar[x] = r[x]; return ar; } char[] so(char ar[]) { Character r[] = new Character[ar.length]; for (int x = 0; x < ar.length; x++) r[x] = ar[x]; sort(r); for (int x = 0; x < ar.length; x++) ar[x] = r[x]; return ar; } void p(Object p) {out.print(p);}void pl(Object p) {out.println(p);}void pl() {out.println();} void s(String s) {sb.append(s);} void s(int s) {sb.append(s);} void s(long s) {sb.append(s);} void s(char s) {sb.append(s);} void s(double s) {sb.append(s);} void ss() {sb.append(' ');} void sl(String s) {s(s);sb.append("\n");} void sl(int s) {s(s);sb.append("\n");} void sl(long s) {s(s);sb.append("\n");} void sl(char s) {s(s);sb.append("\n");} void sl(double s) {s(s);sb.append("\n");} void sl() {sb.append("\n");} int l(int v) {return 31 - Integer.numberOfLeadingZeros(v);} long l(long v) {return 63 - Long.numberOfLeadingZeros(v);} int sq(int a) {return (int) sqrt(a);} long sq(long a) {return (long) sqrt(a);} int gcd(int a, int b) { while (b > 0) { int c = a % b; a = b; b = c; } return a; } long gcd(long a, long b) { while (b > 0l) { long c = a % b; a = b; b = c; } return a; } boolean p(String s, int i, int j) { while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false; return true; } boolean[] si(int n) { boolean bo[] = new boolean[n + 1]; bo[0] = bo[1] = true; for (int x = 4; x <= n; x += 2) bo[x] = true; for (int x = 3; x * x <= n; x += 2) { if (!bo[x]) { int vv = (x << 1); for (int y = x * x; y <= n; y += vv) bo[y] = true; } } return bo; } long mul(long a, long b, long m) { long r = 1l; a %= m; while (b > 0) { if ((b & 1) == 1) r = (r * a) % m; b >>= 1; a = (a * a) % m; } return r; } int i() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return Integer.parseInt(st.nextToken()); } long l() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return Long.parseLong(st.nextToken()); } String s() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return st.nextToken(); } double d() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return Double.parseDouble(st.nextToken()); } void s(int a[]) { for (int e : a){sb.append(e);sb.append(' ');} sb.append("\n"); } void s(long a[]) { for (long e : a){sb.append(e);sb.append(' ');} sb.append("\n"); } void s(char a[]) { for (char e : a){sb.append(e);sb.append(' ');} sb.append("\n"); } void s(int ar[][]) {for (int a[] : ar) s(a);} void s(long ar[][]) {for (long a[] : ar) s(a);} void s(char ar[][]) {for (char a[] : ar) s(a);} int[] ari(int n) throws IOException { int ar[] = new int[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = Integer.parseInt(st.nextToken()); return ar; } long[] arl(int n) throws IOException { long ar[] = new long[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = Long.parseLong(st.nextToken()); return ar; } char[] arc(int n) throws IOException { char ar[] = new char[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = st.nextToken().charAt(0); return ar; } double[] ard(int n) throws IOException { double ar[] = new double[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = Double.parseDouble(st.nextToken()); return ar; } String[] ars(int n) throws IOException { String ar[] = new String[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = st.nextToken(); return ar; } int[][] ari(int n, int m) throws IOException { int ar[][] = new int[n][m]; for (int x = 0; x < n; x++)ar[x]=ari(m); return ar; } long[][] arl(int n, int m) throws IOException { long ar[][] = new long[n][m]; for (int x = 0; x < n; x++)ar[x]=arl(m); return ar; } char[][] arc(int n, int m) throws IOException { char ar[][] = new char[n][m]; for (int x = 0; x < n; x++)ar[x]=arc(m); return ar; } double[][] ard(int n, int m) throws IOException { double ar[][] = new double[n][m]; for (int x = 0; x < n; x++)ar[x]=ard(m); return ar; } void p(int ar[]) { sb = new StringBuilder(11 * ar.length); for (int a : ar) {sb.append(a);sb.append(' ');} out.println(sb); } void p(long ar[]) { StringBuilder sb = new StringBuilder(20 * ar.length); for (long a : ar){sb.append(a);sb.append(' ');} out.println(sb); } void p(double ar[]) { StringBuilder sb = new StringBuilder(22 * ar.length); for (double a : ar){sb.append(a);sb.append(' ');} out.println(sb); } void p(char ar[]) { StringBuilder sb = new StringBuilder(2 * ar.length); for (char aa : ar){sb.append(aa);sb.append(' ');} out.println(sb); } void p(String ar[]) { int c = 0; for (String s : ar) c += s.length() + 1; StringBuilder sb = new StringBuilder(c); for (String a : ar){sb.append(a);sb.append(' ');} out.println(sb); } void p(int ar[][]) { StringBuilder sb = new StringBuilder(11 * ar.length * ar[0].length); for (int a[] : ar) { for (int aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void p(long ar[][]) { StringBuilder sb = new StringBuilder(20 * ar.length * ar[0].length); for (long a[] : ar) { for (long aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void p(double ar[][]) { StringBuilder sb = new StringBuilder(22 * ar.length * ar[0].length); for (double a[] : ar) { for (double aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void p(char ar[][]) { StringBuilder sb = new StringBuilder(2 * ar.length * ar[0].length); for (char a[] : ar) { for (char aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void pl(Object... ar) {for (Object e : ar) p(e + " ");pl();} }
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
218844d7d431f35e311c4346460f593f
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 kg.my_algorithms.Codeforces; import java.util.*; import java.io.*; // Not a spectator public class Solution { private static final FastReader fr = new FastReader(); private static final long mod = 998244353L; public static void main(String[] args) throws IOException { BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); int testCases = fr.nextInt(); for(int testCase=1;testCase<=testCases;testCase++){ int rows = fr.nextInt(); int cols = fr.nextInt(); int k = fr.nextInt(); int qs = fr.nextInt(); int[] r_colored = new int[qs]; int[] c_colored = new int[qs]; for(int q=0;q<qs;q++){ int r = fr.nextInt(); int c = fr.nextInt(); r_colored[q] = r; c_colored[q] = c; } int cnt = 0; Set<Integer> rv = new HashSet<>(); Set<Integer> cv = new HashSet<>(); for(int i=qs-1;i>=0;i--){ if((rv.contains(r_colored[i]) && cv.contains(c_colored[i])) || rv.size()==rows || cv.size()==cols) continue; rv.add(r_colored[i]); cv.add(c_colored[i]); cnt++; } sb.append(powMod(k,cnt)).append("\n"); } output.write(sb.toString()); output.flush(); } private static long powMod(long x, long n){ if(n == 0) return 1L; long t = powMod(x,n/2); if(n%2 == 0) return t*t%mod; return t*t%mod*x%mod; } } //Fast Input 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
["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
e0cec132c983bf6aa418ec54363297fc
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 FastScanner fs = null; static long mod = (long)998244353; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); while (t-->0) { int n = fs.nextInt(); int m = fs.nextInt(); int k = fs.nextInt(); int q = fs.nextInt(); ArrayList<Pair> list = new ArrayList<>(); Set<Integer> row = new HashSet<>(); Set<Integer> col = new HashSet<>(); for(int i=1;i<=q;i++){ int x = fs.nextInt(); int y = fs.nextInt(); list.add(new Pair(x,y)); } Set<Pair> rp = new HashSet<>(); Set<Pair> cp = new HashSet<>(); int sourc = 0; for(int i = q-1;i>=0;i--){ Pair p = list.get(i); int ro = p.x; int co = p.y; int r = 0; if(row.add(ro)){ if(col.size()!=m){ r+=1; } } if(col.add(co)){ if(row.size()!=n){ r+=1; } } if(r>0){ sourc+=1; } } // sourc = set.size(); // out.println(sourc); long res = power((long)k,(long)sourc); out.println(res); } out.close(); } static long power(long a,long p){ if(p==(long)0) return (long)1; if(p%(long)2==(long)0){ return (power((a*a)%mod,p/(long)2))%mod; } else{ return (a*(power((a*a)%mod,p/(long)2))%mod)%mod; } } static class Pair{ int x; int y; Pair(int x,int y){ this.x =x ; this.y = y; } } 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 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()); } 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
0716bb7cccdb57d8dcd55b46ec1a60bd
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.*; // cd C:\Users\Lenovo\Desktop\New //ArrayList<Integer> a=new ArrayList<>(); //List<Integer> lis=new ArrayList<>(); //StringBuilder ans = new StringBuilder(); //HashMap<Integer,Integer> map=new HashMap<>(); public class cf { static FastReader in=new FastReader(); static final Random random=new Random(); static int mod=998244353; //static long dp[]=new long[200002]; public static void main(String args[]) throws IOException { FastReader sc=new FastReader(); //Scanner s=new Scanner(System.in); int tt=sc.nextInt(); //int tt=1; while(tt-->0){ int x=sc.nextInt(); int y=sc.nextInt(); int k=sc.nextInt(); int q=sc.nextInt(); int row[]=new int[q]; int col[]=new int[q]; for(int i=0;i<q;i++){ row[i]=sc.nextInt(); col[i]=sc.nextInt(); } int pow=0; HashSet<Integer> setx=new HashSet<>(); HashSet<Integer> sety=new HashSet<>(); for(int i=q-1;i>=0;i--){ boolean check=false; if(sety.size()<y && !setx.contains(row[i])){ setx.add(row[i]); check=true; } if(setx.size()<x && !sety.contains(col[i])){ sety.add(col[i]); check=true; } if(check){ pow++; } } power(k,pow); } } static void power(int k,int pow){ long ans=1; long cur=k; while(pow!=0){ if((pow&1)!=0){ ans=(ans*cur)%mod; } cur=(cur*cur)%mod; pow=pow/2; } System.out.println(ans); } static int[] func(int arr[],int st,int en){ int srt=st+1; int end=en-1; int neg=0; int count=0; int ans[]=new int[3]; for(int i=srt;i<=end;i++){ if(arr[i]<0){ neg++; } if(Math.abs(arr[i])==2){ count++; } } if(neg%2==0){ ans[0]=count; ans[1]=srt; ans[2]=end; return ans; } else{ int left=0; int right=0; int leftIndex=0; for(int k=srt;k<=end;k++){ if(Math.abs(arr[k])==2){ left++; } if(arr[k]<0){ leftIndex=k; break; } } int rightIndex=0; for(int k=end;k>=srt;k--){ if(Math.abs(arr[k])==2){ right++; } if(arr[k]<0){ rightIndex=k; break; } } //System.out.println(left+" "+leftIndex+" "+right+" "+rightIndex); if(left<right){ ans[0]=count-left; ans[1]=leftIndex+1; ans[2]=end; }else{ ans[0]=count-right; ans[1]=srt; ans[2]=rightIndex-1; //System.out.println((arr.length)); } return ans; } } static StringBuilder remove(StringBuilder f,char c){ StringBuilder a=new StringBuilder(); for(int i=0;i<f.length();i++){ if(f.charAt(i)==c){ } else{ a.append(f.charAt(i)); } } return a; } static boolean func(int m,int []rich,int []poor){ int len=rich.length; int ans=0; for(int i=0;i<len;i++){ if(m-ans-1<=rich[i] && ans<=poor[i]){ ans++; } } if(ans>=m){ return true; } return false; } static long comb(int n,int k){ return factorial(n) * pow(factorial(k), mod-2) % mod * pow(factorial(n-k), mod-2) % mod; } static long pow(long a, long b) { // long mod=1000000007; long res = 1; while (b != 0) { if ((b & 1) != 0) { res = (res * a) % mod; } a = (a * a) % mod; b /= 2; } return res; } static boolean powOfTwo(long n){ while(n%2==0){ n=n/2; } if(n!=1){ return false; } return true; } static int upper_bound(long arr[], long key) { int mid, N = arr.length; int low = 0; int high = N; // Till low is less than high while (low < high && low != N) { mid = low + (high - low) / 2; if (key >= arr[mid]) { low = mid + 1; } else { high = mid; } } if (low == N ) { return -1; } return low; } static boolean prime(int n){ for(int i=2;i<=Math.sqrt(n);i++){ if(n%i==0){ return false; } } return true; } static long factorial(int n){ long ret = 1; while(n > 0){ ret = ret * n % mod; n--; } return ret; } static long find(ArrayList<Long> arr,long n){ int l=0; int r=arr.size(); while(l+1<r){ int mid=(l+r)/2; if(arr.get(mid)<n){ l=mid; } else{ r=mid; } } return arr.get(l); } static void rotate(int ans[]){ int last=ans[0]; for(int i=0;i<ans.length-1;i++){ ans[i]=ans[i+1]; } ans[ans.length-1]=last; } static int countprimefactors(int n){ int ans=0; int z=(int)Math.sqrt(n); for(int i=2;i<=z;i++){ while(n%i==0){ ans++; n=n/i; } } if(n>1){ ans++; } return ans; } static String reverse(String s){ String ans=""; for(int i=s.length()-1;i>=0;i--){ ans+=s.charAt(i); } return ans; } static int msb(int x){ int ans=0; while(x!=0){ x=x/2; ans++; } return ans; } 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 int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } /* Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<Integer, Integer> entry = iterator.next(); int value = entry.getValue(); if(value==1){ iterator.remove(); } else{ entry.setValue(value-1); } } */ static class Pair implements Comparable { int a,b; public String toString() { return a+" " + b; } public Pair(int x , int y) { a=x;b=y; } @Override public int compareTo(Object o) { Pair p = (Pair)o; if(a!=p.a){ return a-p.a; } else{ return b-p.b; } /*if(p.a!=a){ return a-p.a;//in } else{ return b-p.b;// }*/ } } /* public static boolean checkAP(List<Integer> lis){ for(int i=1;i<lis.size()-1;i++){ if(2*lis.get(i)!=lis.get(i-1)+lis.get(i+1)){ return false; } } return true; } public static int minBS(int[]arr,int val){ int l=-1; int r=arr.length; while(r>l+1){ int mid=(l+r)/2; if(arr[mid]>=val){ r=mid; } else{ l=mid; } } return r; } public static int maxBS(int[]arr,int val){ int l=-1; int r=arr.length; while(r>l+1){ int mid=(l+r)/2; if(arr[mid]<=val){ l=mid; } else{ r=mid; } } return l; } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; }*/ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["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
c142e2794a2cab21907ce0ededb1926f
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 Solution { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuffer out = new StringBuffer(); int T = in.nextInt(); OUTER: while (T-->0) { int n = in.nextInt(), m = in.nextInt(); int k = in.nextInt(), q = in.nextInt(); int[][] a = new int[q][2]; for(int i=q-1; i>=0; i--) { for(int j=0; j<2; j++) { a[i][j] = in.nextInt(); } } HashSet<Integer> setX = new HashSet<>(), setY = new HashSet<>(); long ans = 1L; for(int i=0; i<q; i++) { boolean flag = false; if(!setX.contains(a[i][0])) { setX.add(a[i][0]); flag = true; } if(!setY.contains(a[i][1])) { setY.add(a[i][1]); flag = true; } if(flag) { ans = (ans*k)%998244353; } if(setX.size()==n || setY.size()==m) { break; } } out.append(ans+"\n"); } System.out.print(out); } private static long gcd(long a, long b) { if (a==0) return b; return gcd(b%a, a); } private static int toInt(String s) { return Integer.parseInt(s); } private static long toLong(String s) { return Long.parseLong(s); } private static void print(String s) { System.out.print(s); } private static void println(String s) { System.out.println(s); } }
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
5e22ae98156cad61f61f72e46d9cd993
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.HashSet; 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); Task solver = new Task(); int N = in.nextInt(); for(int i=1; i<=N; ++i) solver.solve(i, in, out); out.close(); } static class Task { public void solve(int testNumber, FastReader sc, PrintWriter out) { 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]); } out.println(modPow(k, cnt)); } 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; } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] readArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = nextInt(); return array; } 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 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
c70d62876691ab8791e097e92e7b7d3c
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.HashSet; 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); Task solver = new Task(); int N = in.nextInt(); for(int i=1; i<=N; ++i) solver.solve(i, in, out); out.close(); } static class Task { public void solve(int testNumber, FastReader sc, PrintWriter out) { 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]); } out.println(modPow(k, cnt)); } 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; } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] readArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = nextInt(); return array; } 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 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
b672004bbf93998878d1aa4a077c533c
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 { public static PrintWriter out; private static final long MOD = 998244353L; private static void solve(int n, int m, int k, int q, int[] row, int[] col){ Set<Integer> rowSet = new HashSet<>(); Set<Integer> colSet = new HashSet<>(); long res = 1L; for(int i = q-1; i >= 0; i--){ boolean colored = false; if(!rowSet.contains(row[i])){ rowSet.add(row[i]); colored = true; } if(!colSet.contains(col[i])){ colSet.add(col[i]); colored = true; } if(colored){ res = (res * k) % MOD; } if(rowSet.size() == n || colSet.size() == m){ break; } } out.println(res); } public static void main(String[] args){ MyScanner scanner = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int num = scanner.nextInt(); for(int i = 0; i < num; i++){ int n = scanner.nextInt(); int m = scanner.nextInt(); int k = scanner.nextInt(); int q = scanner.nextInt(); int[] row = new int[q]; int[] col = new int[q]; for(int j = 0; j < q; j++){ row[j] = scanner.nextInt(); col[j] = scanner.nextInt(); } solve(n,m,k,q,row,col); } out.close(); } 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
["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
86c94765db12d9794f1771b17add5c0b
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.*; // BEFORE 31ST MARCH 2022 !! //MAX RATING EVER ACHIEVED-1622(LETS SEE WHEN WILL I GET TO CHANGE THIS) ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class D_Cross_Coloring{ public static void main(String[] args) { FastScanner s= new FastScanner(); //PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); long mod=998244353; int t=s.nextInt(); int p=0; while(p<t){ int n=s.nextInt(); int m=s.nextInt(); int k=s.nextInt(); int q=s.nextInt(); int array1[]= new int[q]; int array2[]= new int[q]; for(int i=0;i<q;i++){ array1[i]=s.nextInt(); array2[i]=s.nextInt(); } long ans=1; Set<Integer> rows = new HashSet<Integer>(); Set<Integer> cols = new HashSet<Integer>(); long rownum=0; long colnum=0; for(int i=q-1;i>=0;i--){ if(rownum==n || colnum==m){ continue; } int yo=0; if(rows.contains(array1[i])){ yo++; } else{ rows.add(array1[i]); rownum++; } if(cols.contains(array2[i])){ yo++; } else{ cols.add(array2[i]); colnum++; } if(yo<2){ ans=(ans*k)%mod; } } res.append(ans+" \n"); p++; } System.out.println(res); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> 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 * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
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
f741464a3f423e287e72b7716b6c6f48
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.StringTokenizer; public class Main { static AReader scan = new AReader(); static int MOD = 998244353; static void slove() { int n = scan.nextInt(); int m = scan.nextInt(); int k = scan.nextInt(); int q = scan.nextInt(); boolean[] col = new boolean[m+10]; boolean[] row = new boolean[n+10]; Pair[] pairs = new Pair[q+1]; for(int i = 1;i<=q;i++){ pairs[i] = new Pair(scan.nextInt(), scan.nextInt()); } int _n = n,_m = m; long ans = 1; for(int i = q;i>0;i--){ int kk = 1; Pair pair = pairs[i]; if(_n <=0 || _m <= 0){ break; } if(!row[pair.x]){ row[pair.x] = true; _n--; kk = k; } if(!col[pair.y]){ col[pair.y] = true; _m--; kk = k; } ans = (ans * kk) % MOD; } System.out.println(ans); } public static void main(String[] args) { int T = scan.nextInt(); while (T-- > 0) { slove(); } } } class AReader { 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()); } } class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = 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
8b331a610c3de1c5fda933e95b796a6b
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.lang.*; // import java.math.*; public class Main { static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); // static long mod=1000000007; static long mod=998244353; static int MAX=Integer.MAX_VALUE; static int MIN=Integer.MIN_VALUE; static long MAXL=Long.MAX_VALUE; static long MINL=Long.MIN_VALUE; static ArrayList<Integer> graph[]; static long fact[]; static int seg[]; static int lazy[];//lazy propagation is used in case of range updates. // static int dp[][]; static long dp[]; public static void main (String[] args) throws java.lang.Exception { // code goes here int t=I(); outer:while(t-->0) { int n=I(),m=I(),k=I(),q=I(); int a[][]=new int[q][2]; for(int i=0;i<q;i++){ a[i][0]=I(); a[i][1]=I(); } HashSet<Integer> hs1=new HashSet<>(),hs2=new HashSet<>(); int cnt=0; for(int i=q-1;i>=0;i--){ boolean flag=true; if(hs1.size()==n || hs2.size()==m)flag=false; if(hs1.contains(a[i][0]) && hs2.contains(a[i][1]))flag=false; if(flag){ cnt++; hs1.add(a[i][0]); hs2.add(a[i][1]); } } out.println(modpwr(k,cnt)); } out.close(); } public static long kadane(long a[],int n) //largest sum subarray { long max_sum=Long.MIN_VALUE,max_end=0; for(int i=0;i<n;i++){ max_end+=a[i]; if(max_sum<max_end){max_sum=max_end;} if(max_end<0){max_end=0;} } return max_sum; } public static class pair { int a; int b; public pair(int aa,int bb) { a=aa; b=bb; } } public static class myComp implements Comparator<pair> { //sort in ascending order. public int compare(pair p1,pair p2) { if(p1.a==p2.a) return 0; else if(p1.a<p2.a) return -1; else return 1; } // sort in descending order. // public int compare(pair p1,pair p2) // { // if(p1.a==p2.a) // return 0; // else if(p1.a<p2.a) // return 1; // else // return -1; // } } public static void DFS(int s,boolean visited[],int dis) { visited[s]=true; for(int i:graph[s]){ if(!visited[i]){ DFS(i,visited,dis); } } } public static void setGraph(int n,int m) { graph=new ArrayList[n+1]; for(int i=0;i<=n;i++){ graph[i]=new ArrayList<>(); } for(int i=0;i<m;i++){ int u=I(),v=I(); graph[u].add(v); graph[v].add(u); } } //LOWER_BOUND and UPPER_BOUND functions //It returns answer according to zero based indexing. public static int lower_bound(long arr[],long X,int start, int end) //start=0,end=n-1 { if(start>end)return -1; if(arr[arr.length-1]<X)return end; if(arr[0]>X)return -1; int left=start,right=end; while(left<right){ int mid=(left+right)/2; // if(arr[mid]==X){ //Returns last index of lower bound value. // if(mid<end && arr[mid+1]==X){ // left=mid+1; // }else{ // return mid; // } // } if(arr[mid]==X){ //Returns first index of lower bound value. if(mid>start && arr[mid-1]==X){ right=mid-1; }else{ return mid; } } else if(arr[mid]>X){ if(mid>start && arr[mid-1]<X){ return mid-1; }else{ right=mid-1; } }else{ if(mid<end && arr[mid+1]>X){ return mid; }else{ left=mid+1; } } } return left; } //It returns answer according to zero based indexing. public static int upper_bound(long arr[],long X,int start,int end) //start=0,end=n-1 { if(arr[0]>=X)return start; if(arr[arr.length-1]<X)return -1; int left=start,right=end; while(left<right){ int mid=(left+right)/2; if(arr[mid]==X){ //returns first index of upper bound value. if(mid>start && arr[mid-1]==X){ right=mid-1; }else{ return mid; } } // if(arr[mid]==X){ //returns last index of upper bound value. // if(mid<end && arr[mid+1]==X){ // left=mid+1; // }else{ // return mid; // } // } else if(arr[mid]>X){ if(mid>start && arr[mid-1]<X){ return mid; }else{ right=mid-1; } }else{ if(mid<end && arr[mid+1]>X){ return mid+1; }else{ left=mid+1; } } } return left; } //END // File file = new File("C:\\Users\\Dell\\Desktop\\JAVA\\testcase.txt"); // FileWriter fw = new FileWriter("output.txt"); // BufferedReader br= new BufferedReader(new FileReader(file)); //Segment Tree Code public static void buildTree(int si,int ss,int se) { if(ss==se){ seg[si]=0; return; } int mid=(ss+se)/2; buildTree(2*si+1,ss,mid); buildTree(2*si+2,mid+1,se); seg[si]=max(seg[2*si+1],seg[2*si+2]); } public static void merge(ArrayList<Integer> f,ArrayList<Integer> a,ArrayList<Integer> b) { int i=0,j=0; while(i<a.size() && j<b.size()){ if(a.get(i)<=b.get(j)){ f.add(a.get(i)); i++; }else{ f.add(b.get(j)); j++; } } while(i<a.size()){ f.add(a.get(i)); i++; } while(j<b.size()){ f.add(b.get(j)); j++; } } public static void update(int si,int ss,int se,int pos,int val) { if(ss==se){ seg[si]=(int)add(seg[si],val); return; } int mid=(ss+se)/2; if(pos<=mid){ update(2*si+1,ss,mid,pos,val); }else{ update(2*si+2,mid+1,se,pos,val); } seg[si]=(int)add(seg[2*si+1],seg[2*si+2]); } public static int query(int si,int ss,int se,int qs,int qe) { if(qs>se || qe<ss)return 0; if(ss>=qs && se<=qe)return seg[si]; int mid=(ss+se)/2; return max(query(2*si+1,ss,mid,qs,qe),query(2*si+2,mid+1,se,qs,qe)); } //Segment Tree Code end //Prefix Function of KMP Algorithm public static int[] KMP(char c[],int n) { int pi[]=new int[n]; for(int i=1;i<n;i++){ int j=pi[i-1]; while(j>0 && c[i]!=c[j]){ j=pi[j-1]; } if(c[i]==c[j])j++; pi[i]=j; } return pi; } public static long nPr(int n,int r) { long ans=divide(fact(n),fact(n-r),mod); return ans; } public static long nCr(int n,int r) { long ans=divide(fact[n],mul(fact[n-r],fact[r]),mod); return ans; } public static boolean isSorted(int a[]) { int n=a.length; for(int i=0;i<n-1;i++){ if(a[i]>a[i+1])return false; } return true; } public static boolean isSorted(long a[]) { int n=a.length; for(int i=0;i<n-1;i++){ if(a[i]>a[i+1])return false; } return true; } public static int computeXOR(int n) //compute XOR of all numbers between 1 to n. { if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; return 0; } public static int np2(int x) { x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return x; } public static int hp2(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } public static long hp2(long x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } public static ArrayList<Integer> primeSieve(int n) { ArrayList<Integer> arr=new ArrayList<>(); 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; } } for (int i = 2; i <= n; i++) { if (prime[i] == true) arr.add(i); } return arr; } // Fenwick / BinaryIndexed Tree USE IT - FenwickTree ft1=new FenwickTree(n); public static class FenwickTree { int farr[]; int n; public FenwickTree(int c) { n=c+1; farr=new int[n]; } // public void update_range(int l,int r,long p) // { // update(l,p); // update(r+1,(-1)*p); // } public void update(int x,int p) { for(;x<n;x+=x&(-x)) { farr[x]+=p; } } public int get(int x) { int ans=0; for(;x>0;x-=x&(-x)) { ans=ans+farr[x]; } return ans; } } //Disjoint Set Union public static class DSU { int par[],rank[]; public DSU(int c) { par=new int[c+1]; rank=new int[c+1]; for(int i=0;i<=c;i++) { par[i]=i; rank[i]=0; } } public int find(int a) { if(a==par[a]) return a; return par[a]=find(par[a]); } public void union(int a,int b) { int a_rep=find(a),b_rep=find(b); if(a_rep==b_rep) return; if(rank[a_rep]<rank[b_rep]) par[a_rep]=b_rep; else if(rank[a_rep]>rank[b_rep]) par[b_rep]=a_rep; else { par[b_rep]=a_rep; rank[a_rep]++; } } } public static HashMap<Integer,Integer> primeFact(int a) { // HashSet<Long> arr=new HashSet<>(); HashMap<Integer,Integer> hm=new HashMap<>(); int p=0; while(a%2==0){ // arr.add(2L); p++; a=a/2; } hm.put(2,hm.getOrDefault(2,0)+p); for(int i=3;i*i<=a;i+=2){ p=0; while(a%i==0){ // arr.add(i); p++; a=a/i; } hm.put(i,hm.getOrDefault(i,0)+p); } if(a>2){ // arr.add(a); hm.put(a,hm.getOrDefault(a,0)+1); } // return arr; return hm; } public static boolean isInteger(double N) { int X = (int)N; double temp2 = N - X; if (temp2 > 0) { return false; } return true; } public static boolean isPalindrome(String s) { int n=s.length(); for(int i=0;i<=n/2;i++){ if(s.charAt(i)!=s.charAt(n-i-1)){ return false; } } return true; } public static int gcd(int a,int b) { if(b==0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } public static long fact(long n) { long fact=1; for(long i=2;i<=n;i++){ fact=((fact%mod)*(i%mod))%mod; } return fact; } public static long fact(int n) { long fact=1; for(int i=2;i<=n;i++){ fact=((fact%mod)*(i%mod))%mod; } return fact; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; 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; } public static boolean isPrime(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; } public static void printArray(long a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(int a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(char a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]); } out.println(); } public static void printArray(String a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(boolean a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(pair a[]) { for(pair p:a){ out.println(p.a+"->"+p.b); } } public static void printArray(int a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(long a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(char a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(ArrayList<?> arr) { for(int i=0;i<arr.size();i++){ out.print(arr.get(i)+" "); } out.println(); } public static void printMapI(HashMap<?,?> hm){ for(Map.Entry<?,?> e:hm.entrySet()){ out.println(e.getKey()+"->"+e.getValue()); }out.println(); } public static void printMap(HashMap<Long,ArrayList<Integer>> hm){ for(Map.Entry<Long,ArrayList<Integer>> e:hm.entrySet()){ out.print(e.getKey()+"->"); ArrayList<Integer> arr=e.getValue(); for(int i=0;i<arr.size();i++){ out.print(arr.get(i)+" "); }out.println(); } } //Modular Arithmetic public static long add(long a,long b) { a+=b; if(a>=mod)a-=mod; return a; } public static long sub(long a,long b) { a-=b; if(a<0)a+=mod; return a; } public static long mul(long a,long b) { return ((a%mod)*(b%mod))%mod; } public static long divide(long a,long b,long m) { a=mul(a,modInverse(b,m)); return a; } public static long modInverse(long a,long m) { int x=0,y=0; own p=new own(x,y); long g=gcdExt(a,m,p); if(g!=1){ out.println("inverse does not exists"); return -1; }else{ long res=((p.a%m)+m)%m; return res; } } public static long gcdExt(long a,long b,own p) { if(b==0){ p.a=1; p.b=0; return a; } int x1=0,y1=0; own p1=new own(x1,y1); long gcd=gcdExt(b,a%b,p1); p.b=p1.a - (a/b) * p1.b; p.a=p1.b; return gcd; } public static long pwr(long m,long n) { long res=1; if(m==0) return 0; while(n>0) { if((n&1)!=0) { res=(res*m); } n=n>>1; m=(m*m); } return res; } public static long modpwr(long m,long n) { long res=1; m=m%mod; if(m==0) return 0; while(n>0) { if((n&1)!=0) { res=(res*m)%mod; } n=n>>1; m=(m*m)%mod; } return res; } public static class own { long a; long b; public own(long val,long index) { a=val; b=index; } } //Modular Airthmetic public 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); } public static void sort(char[] A) { int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i) { char tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } public 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); } //max & min public static int max(int a,int b){return Math.max(a,b);} public static int min(int a,int b){return Math.min(a,b);} public static int max(int a,int b,int c){return Math.max(a,Math.max(b,c));} public static int min(int a,int b,int c){return Math.min(a,Math.min(b,c));} public static long max(long a,long b){return Math.max(a,b);} public static long min(long a,long b){return Math.min(a,b);} public static long max(long a,long b,long c){return Math.max(a,Math.max(b,c));} public static long min(long a,long b,long c){return Math.min(a,Math.min(b,c));} public static int maxinA(int a[]){int n=a.length;int mx=a[0];for(int i=1;i<n;i++){mx=max(mx,a[i]);}return mx;} public static long maxinA(long a[]){int n=a.length;long mx=a[0];for(int i=1;i<n;i++){mx=max(mx,a[i]);}return mx;} public static int mininA(int a[]){int n=a.length;int mn=a[0];for(int i=1;i<n;i++){mn=min(mn,a[i]);}return mn;} public static long mininA(long a[]){int n=a.length;long mn=a[0];for(int i=1;i<n;i++){mn=min(mn,a[i]);}return mn;} public static long suminA(int a[]){int n=a.length;long sum=0;for(int i=0;i<n;i++){sum+=a[i];}return sum;} public static long suminA(long a[]){int n=a.length;long sum=0;for(int i=0;i<n;i++){sum+=a[i];}return sum;} //end public static int[] I(int n) { int a[]=new int[n]; for(int i=0;i<n;i++){ a[i]=I(); } return a; } public static long[] IL(int n) { long a[]=new long[n]; for(int i=0;i<n;i++){ a[i]=L(); } return a; } public static long[] prefix(int a[]) { int n=a.length; long pre[]=new long[n]; pre[0]=a[0]; for(int i=1;i<n;i++){ pre[i]=pre[i-1]+a[i]; } return pre; } public static long[] prefix(long a[]) { int n=a.length; long pre[]=new long[n]; pre[0]=a[0]; for(int i=1;i<n;i++){ pre[i]=pre[i-1]+a[i]; } return pre; } public static int I(){return sc.I();} public static long L(){return sc.L();} public static String S(){return sc.S();} public static double D(){return sc.D();} } 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 I(){ return Integer.parseInt(next()); } long L(){ return Long.parseLong(next()); } double D(){ return Double.parseDouble(next()); } String S(){ 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
8521abc563acbb277ad64ce00b0aaa04
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 { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { int n=input.nextInt(); int m=input.nextInt(); int k=input.nextInt(); int q=input.nextInt(); int arr[][]=new int[q][2]; for(int i=0;i<q;i++) { int x=input.nextInt(); int y=input.nextInt(); arr[i][0]=x; arr[i][1]=y; } HashSet<Integer> row=new HashSet<>(); HashSet<Integer> col=new HashSet<>(); int c=0; for(int i=q-1;i>=0;i--) { int x=arr[i][0]; int y=arr[i][1]; int f=0; if(!row.contains(x) && col.size()!=m) f=1; if(!col.contains(y) && row.size()!=n) f=1; if(f==1) { c++; } row.add(x); col.add(y); } long mod=998244353; long ans=power(k,c,mod); out.println(ans); } out.close(); } public static long power(long a,long b,long m) { long res=1; while(b>0) { if(b%2!=0) { res=(res%m*a%m)%m; } b=b/2; a=(a%m*a%m)%m; } return res; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["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
bae320590525a21c61a8ab1b79ba7476
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.lang.*; import java.util.*; public class ComdeFormces { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub // Reader.init(System.in); FastReader sc=new FastReader(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); // OutputStream out = new BufferedOutputStream ( System.out ); int t=sc.nextInt(); int tc=1; while(t--!=0) { int n=sc.nextInt(); int m=sc.nextInt(); int k=sc.nextInt(); int q=sc.nextInt(); // if(tc==242) System.out.println(n+" "+m+" "+k+" "+q); long ans=0; int md=998244353; HashMap<String,Integer> hm=new HashMap<>(); HashMap<Integer,Integer> hsx=new HashMap<>(); HashMap<Integer,Integer> hsy=new HashMap<>(); ArrayList<pair> ar=new ArrayList<>(); for(int i=0;i<q;i++) { int a=sc.nextInt(); int b=sc.nextInt(); ar.add(new pair(a,b)); } for(int i=q-1;i>=0;i--) { int a=ar.get(i).a; int b=ar.get(i).b; if((hsx.getOrDefault(a, 0)<1 || hsy.getOrDefault(b,0)<1) && (hsx.size()!=n && hsy.size()!=m)) { ans++; } hsx.put(a,hsx.getOrDefault(a, 0)+1); hsy.put(b,hsy.getOrDefault(b, 0)+1); } long p=1; while(ans--!=0) { p=((k%md)*(p%md))%md; } log.write(p+"\n"); // log.write(ans+"\n"); tc++; log.flush(); } } static void update(long f[],long upd,int ind) { int vl=ind; while(vl<f.length) { f[vl]+=upd; int tp=~vl;tp++;tp&=vl; vl+=tp; } } static long ser(long f[],int ind) { int vl=ind; long sm=0; while(vl!=0) { sm+=f[vl]; int tp=~vl;tp++;tp&=vl; vl-=tp; } return sm; } static int bsfd(ArrayList<Integer> ar,int el) { int s=0; int e=ar.size()-1; while(s<=e) { int m=s+(e-s)/2; if(ar.get(m)<=el)s=m+1; else e=m-1; } return e>=0?e+1:0; } static int find(int el,int p[]) { if(p[el]<0)return el; return p[el]=find(p[el],p); } static boolean find(int a,int b,int p[]) { int p1=find(a,p); int p2=find(b,p); if(p1>=0 && p1==p2)return false; else { if(p[p1]<p[p2]) { p[p1]+=p[p2]; p[p2]=p1; } else { p[p2]+=p[p1]; p[p1]=p2; } return true; } } public static void radixSort(int a[]) { int n=a.length; int res[]=new int[n]; int p=1; for(int i=0;i<=8;i++) { int cnt[]=new int[10]; for(int j=0;j<n;j++) { a[j]=res[j]; cnt[(a[j]/p)%10]++; } for(int j=1;j<=9;j++) { cnt[j]+=cnt[j-1]; } for(int j=n-1;j>=0;j--) { res[cnt[(a[j]/p)%10]-1]=a[j]; cnt[(a[j]/p)%10]--; } p*=10; } } static int bits(long n) { int ans=0; while(n!=0) { if((n&1)==1)ans++; n>>=1; } return ans; } static long flor(ArrayList<Long> ar,long el) { int s=0; int e=ar.size()-1; while(s<=e) { int m=s+(e-s)/2; if(ar.get(m)==el)return ar.get(m); else if(ar.get(m)<el)s=m+1; else e=m-1; } return e>=0?e:-1; } public static int kadane(int a[]) { int sum=0,mx=Integer.MIN_VALUE; for(int i=0;i<a.length;i++) { sum+=a[i]; mx=Math.max(mx, sum); if(sum<0) sum=0; } return mx; } public static int m=(int)(1e9+7); public static int mul(int a, int b) { return ((a%m)*(b%m))%m; } public static long mul(long a, long b) { return ((a%md)*(b%md))%md; } public static int add(int a, int b) { return ((a%m)+(b%m))%m; } public static long add(long a, long b) { return ((a%m)+(b%m))%m; } //debug public static <E> void p(E[][] a,String s) { System.out.println(s); for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } public static void p(int[] a,String s) { System.out.print(s+"="); for(int i=0;i<a.length;i++)System.out.print(a[i]+" "); System.out.println(); } public static void p(long[] a,String s) { System.out.print(s+"="); for(int i=0;i<a.length;i++)System.out.print(a[i]+" "); System.out.println(); } public static <E> void p(E a,String s){ System.out.println(s+"="+a); } public static <E> void p(ArrayList<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(LinkedList<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(HashSet<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(Stack<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(Queue<E> a,String s){ System.out.println(s+"="+a); } //utils static ArrayList<Integer> divisors(int n){ ArrayList<Integer> ar=new ArrayList<>(); for (int i=2; i<=Math.sqrt(n); i++){ if (n%i == 0){ if (n/i == i) { ar.add(i); } else { ar.add(i); ar.add(n/i); } } } return ar; } static ArrayList<Integer> prime(int n){ ArrayList<Integer> ar=new ArrayList<>(); int cnt=0; boolean pr=false; while(n%2==0) { ar.add(2); n/=2; } for(int i=3;i*i<=n;i+=2) { pr=false; while(n%i==0) { n/=i; ar.add(i); pr=true; } } if(n>2) ar.add(n); return ar; } static long gcd(long a,long b) { if(b==0)return a; else return gcd(b,a%b); } static int gcd(int a,int b) { if(b==0)return a; else return gcd(b,a%b); } static long factmod(long n,long mod,long img) { if(n==0)return 1; long ans=1; long temp=1; while(n--!=0) { if(temp!=img) { ans=((ans%mod)*((temp)%mod))%mod; } temp++; } return ans%mod; } static int ncr(int n, int r){ if(r>n-r)r=n-r; int ans=1; for(int i=0;i<r;i++){ ans*=(n-i); ans/=(i+1); } return ans; } public static class trip{ int a,b; int c; public trip(int a,int b,int c) { this.a=a; this.b=b; this.c=c; } public int compareTo(trip q) { return this.b-q.b; } } static void mergesort(int[] a,int start,int end) { if(start>=end)return ; int mid=start+(end-start)/2; mergesort(a,start,mid); mergesort(a,mid+1,end); merge(a,start,mid,end); } static void merge(int[] a, int start,int mid,int end) { int ptr1=start; int ptr2=mid+1; int b[]=new int[end-start+1]; int i=0; while(ptr1<=mid && ptr2<=end) { if(a[ptr1]<a[ptr2]) { b[i]=a[ptr1]; ptr1++; // swp2+; i++; } else { b[i]=a[ptr2]; // swp+=mid+1-ptr1; // System.out.println("ch="+b[i]+" "+(ptr2-ptr1)); ptr2++; i++; } } while(ptr1<=mid) { b[i]=a[ptr1]; ptr1++; i++; } while(ptr2<=end) { b[i]=a[ptr2]; ptr2++; i++; } for(int j=start;j<=end;j++) { a[j]=b[j-start]; } } public static class FastReader { BufferedReader b; StringTokenizer s; public FastReader() { b=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(s==null ||!s.hasMoreElements()) { try { s=new StringTokenizer(b.readLine()); } catch(IOException e) { e.printStackTrace(); } } return s.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=b.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } boolean hasNext() { if (s != null && s.hasMoreTokens()) { return true; } String tmp; try { b.mark(1000); tmp = b.readLine(); if (tmp == null) { return false; } b.reset(); } catch (IOException e) { return false; } return true; } } public static class pair{ int a; int b; public pair(int a,int b) { this.a=a; this.b=b; } public int compareTo(pair b) { return this.a-b.a; } // public int compareToo(pair b) { // return this.b-b.b; // } @Override public String toString() { return "{"+this.a+" "+this.b+"}"; } } static long pow(long a, long pw) { long temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } public static int md=998244353; static long mpow(long a, long pw) { long temp; if(pw==0)return 1; temp=pow(a,pw/2)%md; if(pw%2==0)return mul(temp,temp); return mul(a,mul(temp,temp)); } static int pow(int a, int pw) { int temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } }
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 11
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
4d6d8d3b1beeb8be7d296075583ecb53
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.DecimalFormat; import java.util.Arrays; import java.util.*; import java.util.Scanner; import java.util.StringTokenizer; public class copy { static int log=18; static int[][] ancestor; static int[] depth; static void sieveOfEratosthenes(int n, ArrayList<Integer> arr) { 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] is not changed, then it is a // prime if (prime[p]) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i]) { arr.add(i); } } } public static long fac(long N, long mod) { if (N == 0) return 1; if(N==1) return 1; return ((N % mod) * (fac(N - 1, mod) % mod)) % mod; } 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); } // 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; return ((fac(n, p) % p * (modInverse(fac(r, p), p) % p)) % p * (modInverse(fac(n - r, p), p) % p)) % p; } public static int find(int[] parent, int x) { if (parent[x] == x) return x; return find(parent, parent[x]); } public static void merge(int[] parent, int[] rank, int x, int y,int[] child) { int x1 = find(parent, x); int y1 = find(parent, y); if (rank[x1] > rank[y1]) { parent[y1] = x1; child[x1]+=child[y1]; } else if (rank[y1] > rank[x1]) { parent[x1] = y1; child[y1]+=child[x1]; } else { parent[y1] = x1; child[x1]+=child[y1]; rank[x1]++; } } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int power(int x, int y, int p) { int res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } // Returns n^(-1) mod p static int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static int nCrModPFermat(int n, int r, int 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 int[] fac = new int[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } public static long[][] ncr(int n,int r) { long[][] dp=new long[n+1][r+1]; for(int i=0;i<=n;i++) dp[i][0]=1; for(int i=1;i<=n;i++) { for(int j=1;j<=r;j++) { if(j>i) continue; dp[i][j]=dp[i-1][j-1]+dp[i-1][j]; } } return dp; } public static boolean prime(long N) { int c=0; for(int i=2;i*i<=N;i++) { if(N%i==0) ++c; } return c==0; } public static int sparse_ancestor_table(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[] child) { int c=0; for(int i:arr.get(x)) { if(i!=parent) { // System.out.println(i+" hello "+x); depth[i]=depth[x]+1; ancestor[i][0]=x; // if(i==2) // System.out.println(parent+" hello"); for(int j=1;j<log;j++) ancestor[i][j]=ancestor[ancestor[i][j-1]][j-1]; c+=sparse_ancestor_table(arr,i,x,child); } } child[x]=1+c; return child[x]; } public static int lca(int x,int y) { if(depth[x]<depth[y]) { int temp=x; x=y; y=temp; } x=get_kth_ancestor(depth[x]-depth[y],x); if(x==y) return x; // System.out.println(x+" "+y); for(int i=log-1;i>=0;i--) { if(ancestor[x][i]!=ancestor[y][i]) { x=ancestor[x][i]; y=ancestor[y][i]; } } return ancestor[x][0]; } public static int get_kth_ancestor(int K,int x) { if(K==0) return x; int node=x; for(int i=0;i<log;i++) { if(K%2!=0) { node=ancestor[node][i]; } K/=2; } return node; } public static int bin(long[] pref,int l1,int r1,long w) { int l=l1,r=r1; while(l<=r) { int mid=(l+r)/2; // if(l==0 && r==2) // System.out.println(mid); long ch= l1-1>=0 ? pref[mid]-pref[l1-1]: pref[mid]; // System.out.println(ch+" "+mid); if(ch==w) { return mid; } else if(ch<w) l=mid+1; else r=mid-1; } return -1; } static boolean sta=true; public static void check(int l,int r,long w,long[] pref) { // System.out.println(w); long search=(long)(Math.ceil(w/2.0)); if(search<2 || l==r) { return; } int st=bin(pref,l,r,search); int st1=bin(pref,l,r,w/2); System.out.println(l+" "+r+" "+search+" "+st); System.out.println(l+" "+r+" "+w/2+" "+st1); if(st==-1 && st1==-1) { sta=false; } else { if(st!=-1) { if(st==6) System.out.println(w+" "+search); check(l, st, search, pref); check(st + 1, r, w - search, pref); } else { check(l, st1, w/2, pref); check(st1 + 1, r, w - w/2, pref); } } } public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); int T=Reader.nextInt(); A:for(int m=1;m<=T;m++) { int N=Reader.nextInt(); int M=Reader.nextInt(); int k=Reader.nextInt(); int q=Reader.nextInt(); int[][] que=new int[q][2]; for(int i=0;i<q;i++) { que[i][0]=Reader.nextInt(); que[i][1]=Reader.nextInt(); } HashSet<Integer> row=new HashSet<>(); HashSet<Integer> col=new HashSet<>(); int cnt=0; for(int i=q-1;i>=0;i--) { int r=que[i][0]; int c=que[i][1]; if(row.size()==N || col.size()==M) break; if(row.contains(r) && col.contains(c)) continue; row.add(r); col.add(c); ++cnt; } long ans=1,mod=998244353; for(int i=1;i<=cnt;i++) ans=((ans%mod)*(k%mod))%mod; output.write(ans+"\n"); } output.flush(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } } class sortat implements Comparator<div> { public int compare(div o1,div o2) { return o1.x-o2.x; } } class TreeNode { int data; TreeNode left; TreeNode right; TreeNode(int data) { left=null; right=null; this.data=data; } } class div { int x; int y; int z; div(int x,int y,int z) { this.x = x; this.y=y; this.z=z; } }
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 11
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
39b3e27a1996e85365020400c05c570e
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.DecimalFormat; import java.util.Arrays; import java.util.*; import java.util.Scanner; import java.util.StringTokenizer; public class copy { static int log=18; static int[][] ancestor; static int[] depth; static void sieveOfEratosthenes(int n, ArrayList<Integer> arr) { 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] is not changed, then it is a // prime if (prime[p]) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i]) { arr.add(i); } } } public static long fac(long N, long mod) { if (N == 0) return 1; if(N==1) return 1; return ((N % mod) * (fac(N - 1, mod) % mod)) % mod; } 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); } // 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; return ((fac(n, p) % p * (modInverse(fac(r, p), p) % p)) % p * (modInverse(fac(n - r, p), p) % p)) % p; } public static int find(int[] parent, int x) { if (parent[x] == x) return x; return find(parent, parent[x]); } public static void merge(int[] parent, int[] rank, int x, int y) { int x1 = find(parent, x); int y1 = find(parent, y); if (rank[x1] > rank[y1]) { parent[y1] = x1; } else if (rank[y1] > rank[x1]) { parent[x1] = y1; } else { parent[y1] = x1; rank[x1]++; } } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int power(int x, int y, int p) { int res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } // Returns n^(-1) mod p static int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static int nCrModPFermat(int n, int r, int 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 int[] fac = new int[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } public static long[][] ncr(int n,int r) { long[][] dp=new long[n+1][r+1]; for(int i=0;i<=n;i++) dp[i][0]=1; for(int i=1;i<=n;i++) { for(int j=1;j<=r;j++) { if(j>i) continue; dp[i][j]=dp[i-1][j-1]+dp[i-1][j]; } } return dp; } public static boolean prime(long N) { int c=0; for(int i=2;i*i<=N;i++) { if(N%i==0) ++c; } return c==0; } public static int sparse_ancestor_table(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[] child) { int c=0; for(int i:arr.get(x)) { if(i!=parent) { // System.out.println(i+" hello "+x); depth[i]=depth[x]+1; ancestor[i][0]=x; // if(i==2) // System.out.println(parent+" hello"); for(int j=1;j<log;j++) ancestor[i][j]=ancestor[ancestor[i][j-1]][j-1]; c+=sparse_ancestor_table(arr,i,x,child); } } child[x]=1+c; return child[x]; } public static int lca(int x,int y) { if(depth[x]<depth[y]) { int temp=x; x=y; y=temp; } x=get_kth_ancestor(depth[x]-depth[y],x); if(x==y) return x; // System.out.println(x+" "+y); for(int i=log-1;i>=0;i--) { if(ancestor[x][i]!=ancestor[y][i]) { x=ancestor[x][i]; y=ancestor[y][i]; } } return ancestor[x][0]; } public static int get_kth_ancestor(int K,int x) { if(K==0) return x; int node=x; for(int i=0;i<log;i++) { if(K%2!=0) { node=ancestor[node][i]; } K/=2; } return node; } public static long[] djikstra(ArrayList<ArrayList<Integer>> arr,ArrayList<ArrayList<Long>> weight,int N) { long[] dist=new long[N]; Arrays.fill(dist,Long.MAX_VALUE); dist[0]=0; PriorityQueue<div> pq=new PriorityQueue<>(new Comparator<div>() { @Override public int compare(div o1, div o2) { if(o1.y<o2.y) return -1; else if(o2.y<o1.y) return 1; else return 0; } }); HashSet<Integer> hp=new HashSet<>(); // hp.add(0); pq.add(new div(0,0)); while(pq.size()>0) { div temp=pq.poll(); hp.add(temp.x); for(int i=0;i<arr.get(temp.x).size();i++) { int x=arr.get(temp.x).get(i); long w=weight.get(temp.x).get(i); if(!hp.contains(x) && dist[temp.x]+w<dist[x]) { dist[x]=dist[temp.x]+w; pq.add(new div(x,dist[x])); } } } return dist; } public static boolean check(char[][] ch,String s,int N,int M) { for(int i=0;i<N;i++) { int c=0; for(int j=0;j<M;j++) { if(s.charAt(j)!=ch[i][j]) ++c; } if(c>=2) return false; } return true; } public static int check(int[] arr,int i) { // System.out.println(i); if(i-1<0) return 0; if(i+1>=arr.length) return 0; if ((arr[i]<arr[i-1] && arr[i]<arr[i+1]) || (arr[i]>arr[i-1] && arr[i]>arr[i+1])) return 1; return 0; } public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); int T=Reader.nextInt(); A:for(int m=1;m<=T;m++) { int N=Reader.nextInt(); int M=Reader.nextInt(); int k=Reader.nextInt(); int q=Reader.nextInt(); int[][] store=new int[q][2]; for(int i=0;i<q;i++) { store[i][0]=Reader.nextInt(); store[i][1]=Reader.nextInt(); } HashSet<Integer> row=new HashSet<>(); HashSet<Integer> col=new HashSet<>(); long mod=998244353,ans=1; for(int i=q-1;i>=0;i--) { int x=store[i][0]; int y=store[i][1]; if(col.size()==M || row.size()==N) break; boolean status=true; if(row.contains(x) && col.contains(y)) status=false; if(status) { ans=((ans%mod)*(k%mod))%mod; row.add(x); col.add(y); } } output.write(ans+"\n"); } output.flush(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } } class sortat implements Comparator<div> { public int compare(div o1,div o2) { return o1.x-o2.x; } } class TreeNode { int data; TreeNode left; TreeNode right; TreeNode(int data) { left=null; right=null; this.data=data; } } class div { int x; long y; div(int x,long y) { this.x = x; this.y=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 11
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
2c615aa5772494ccd019c6d50761cd02
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 javax.print.DocFlavor.INPUT_STREAM; import java.io.*; import java.math.*; import java.sql.Array; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; public class Main { private static class MyScanner { private static final int BUF_SIZE = 2048; BufferedReader br; private MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } private boolean isSpace(char c) { return c == '\n' || c == '\r' || c == ' '; } String next() { try { StringBuilder sb = new StringBuilder(); int r; while ((r = br.read()) != -1 && isSpace((char)r)); if (r == -1) { return null; } sb.append((char) r); while ((r = br.read()) != -1 && !isSpace((char)r)) { sb.append((char)r); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } static class Reader{ BufferedReader br; StringTokenizer st; public Reader() { 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 long mod = (long)(1e9 + 7); static void sort(long[] arr ) { ArrayList<Long> al = new ArrayList<>(); for(long e:arr) al.add(e); Collections.sort(al); for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i); } static void sort(int[] arr ) { ArrayList<Integer> al = new ArrayList<>(); for(int e:arr) al.add(e); Collections.sort(al); for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i); } static void sort(char[] arr) { ArrayList<Character> al = new ArrayList<Character>(); for(char cc:arr) al.add(cc); Collections.sort(al); for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i); } static long mod_mul( long... a) { long ans = a[0]%mod; for(int i = 1 ; i<a.length ; i++) { ans = (ans * (a[i]%mod))%mod; } return ans; } static long mod_sum( long... a) { long ans = 0; for(long e:a) { ans = (ans + e)%mod; } return ans; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void print(long[] arr) { System.out.println("---print---"); for(long e:arr) System.out.print(e+" "); System.out.println("-----------"); } static void print(int[] arr) { System.out.println("---print---"); for(long e:arr) System.out.print(e+" "); System.out.println("-----------"); } static boolean[] prime(int num) { boolean[] bool = new boolean[num]; for (int i = 0; i< bool.length; i++) { bool[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(bool[i] == true) { for(int j = (i*i); j<num; j = j+i) { bool[j] = false; } } } if(num >= 0) { bool[0] = false; bool[1] = false; } return bool; } static long modInverse(long a, long m) { long g = gcd(a, m); return power(a, m - 2); } static long lcm(long a , long b) { return (a*b)/gcd(a, b); } static int lcm(int a , int b) { return (int)((a*b)/gcd(a, b)); } static long power(long x, long y){ if(y<0) return 0; long m = mod; if (y == 0) return 1; long p = power(x, y / 2) % m; p = (int)((p * (long)p) % m); if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); } static class Combinations{ private long[] z; // factorial private long[] z1; // inverse factorial private long[] z2; // incerse number private long mod; public Combinations(long N , long mod) { this.mod = mod; z = new long[(int)N+1]; z1 = new long[(int)N+1]; z[0] = 1; for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod; z2 = new long[(int)N+1]; z2[0] = z2[1] = 1; for (int i = 2; i <= N; i++) z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod; z1[0] = z1[1] = 1; for (int i = 2; i <= N; i++) z1[i] = (z2[i] * z1[i - 1]) % mod; } long fac(long n) { return z[(int)n]; } long invrsNum(long n) { return z2[(int)n]; } long invrsFac(long n) { return z1[(int)n]; } long ncr(long N, long R) { if(R<0 || R>N ) return 0; long ans = ((z[(int)N] * z1[(int)R]) % mod * z1[(int)(N - R)]) % mod; return ans; } } static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } void makeSet() { for (int i = 0; i < n; i++) { parent[i] = i; } } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; } } } static int max(int... a ) { int max = a[0]; for(int e:a) max = Math.max(max, e); return max; } static long max(long... a ) { long max = a[0]; for(long e:a) max = Math.max(max, e); return max; } static int min(int... a ) { int min = a[0]; for(int e:a) min = Math.min(e, min); return min; } static long min(long... a ) { long min = a[0]; for(long e:a) min = Math.min(e, min); return min; } static int[] KMP(String str) { int n = str.length(); int[] kmp = new int[n]; for(int i = 1 ; i<n ; i++) { int j = kmp[i-1]; while(j>0 && str.charAt(i) != str.charAt(j)) { j = kmp[j-1]; } if(str.charAt(i) == str.charAt(j)) j++; kmp[i] = j; } return kmp; } /************************************************ Query **************************************************************************************/ /***************************************** Sparse Table ********************************************************/ static class SparseTable{ private long[][] st; SparseTable(long[] arr){ int n = arr.length; st = new long[n][25]; log = new int[n+2]; build_log(n+1); build(arr); } private void build(long[] arr) { int n = arr.length; for(int i = n-1 ; i>=0 ; i--) { for(int j = 0 ; j<25 ; j++) { int r = i + (1<<j)-1; if(r>=n) break; if(j == 0 ) st[i][j] = arr[i]; else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] ); } } } public long gcd(long a ,long b) { if(a == 0) return b; return gcd(b%a , a); } public long query(int l ,int r) { int w = r-l+1; int power = log[w]; return Math.min(st[l][power],st[r - (1<<power) + 1][power]); } private int[] log; void build_log(int n) { log[1] = 0; for(int i = 2 ; i<=n ; i++) { log[i] = 1 + log[i/2]; } } } /******************************************************** Segement Tree *****************************************************/ static class SegmentTree{ long[] tree; long[] arr; int n; SegmentTree(long[] arr){ this.n = arr.length; tree = new long[4*n+1]; this.arr = arr; buildTree(0, n-1, 1); } void buildTree(int s ,int e ,int index ) { if(s == e) { tree[index] = arr[s]; return; } int mid = (s+e)/2; buildTree( s, mid, 2*index); buildTree( mid+1, e, 2*index+1); tree[index] = gcd(tree[2*index] , tree[2*index+1]); } long query(int si ,int ei) { return query(0 ,n-1 , si ,ei , 1 ); } private long query( int ss ,int se ,int qs , int qe,int index) { if(ss>=qs && se<=qe) return tree[index]; if(qe<ss || se<qs) return (long)(0); int mid = (ss + se)/2; long left = query( ss , mid , qs ,qe , 2*index); long right= query(mid + 1 , se , qs ,qe , 2*index+1); return gcd(left, right); } public void update(int index , int val) { arr[index] = val; // for(long e:arr) System.out.print(e+" "); update(index , 0 , n-1 , 1); } private void update(int id ,int si , int ei , int index) { if(id < si || id>ei) return; if(si == ei ) { tree[index] = arr[id]; return; } if(si > ei) return; int mid = (ei + si)/2; update( id, si, mid , 2*index); update( id , mid+1, ei , 2*index+1); tree[index] = Math.min(tree[2*index] ,tree[2*index+1]); } } /* ***************************************************************************************************************************************************/ // static MyScanner sc = new MyScanner(); // only in case of less memory static Reader sc = new Reader(); static int TC; static StringBuilder sb = new StringBuilder(); static PrintWriter out=new PrintWriter(System.out); public static void main(String args[]) throws IOException { int tc = 1; tc = sc.nextInt(); TC = 0; for(int i = 1 ; i<=tc ; i++) { TC++; // sb.append("Case #" + i + ": " ); // During KickStart && HackerCup TEST_CASE(); } System.out.print(sb); } static void TEST_CASE() throws IOException { mod = 998244353 ; int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int q = sc.nextInt(); int[][] quer = new int[q][2]; for(int i = 0 ; i<q ; i++) { quer[i][0] = sc.nextInt(); quer[i][1] = sc.nextInt(); } Set<Integer> r = new HashSet<>(); Set<Integer> c = new HashSet<>(); Map<Integer , Integer> row = new HashMap<>(); Map<Integer , Integer> col = new HashMap<>(); for(int i = q-1 ; i>=0 ; i--) { int x = quer[i][0] , y = quer[i][1]; if(!row.containsKey(x-1)) row.put(x-1 , i); if(!col.containsKey(y-1)) col.put(y-1,i); r.add(x); c.add(y); if(r.size() == n || c.size() == m) break; } Set<Integer> set = new HashSet<>(); for(int key:row.keySet()) set.add(row.get(key)); for(int key:col.keySet()) set.add(col.get(key)); long len = set.size(); long ans = 1; for(int i = 1 ; i<=len ; i++) { ans = (ans * k)%mod; } ans %= mod; sb.append(ans+"\n"); } } /*******************************************************************************************************************************************************/ /** */
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 11
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
eb428d38c35f91a1384e47cdfa0fe752
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
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.lang.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.*; public class Eshan { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static DecimalFormat df = new DecimalFormat("0.0000000"); final static int mod = (int) (1e9 + 7); final static int MAX = Integer.MAX_VALUE; final static int MIN = Integer.MIN_VALUE; static Random rand = new Random(); // ======================= MAIN ================================== public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // ==== start ==== int t = readInt(); // int t = 1; preprocess(); while (t-- > 0) { solve(); } out.flush(); // ==== end ==== if (!oj) System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } private static void solve() throws IOException { int n = readInt(), m = readInt(), k = readInt(), q = readInt(); long ans = 1L; int[][] op = read2DIntArray(q, 2); Set<Integer> row = new HashSet<>(), col = new HashSet<>(); for (int i = q - 1; i >= 0; i--) { boolean flag = false; if (!row.contains(op[i][0]) && col.size() != m) flag = true; if (!col.contains(op[i][1]) && row.size() != n) flag = true; row.add(op[i][0]); col.add(op[i][1]); if (flag) { ans *= k; ans %= 998244353; } } out.println(ans); } private static void preprocess() { } // ==================== CUSTOM CLASSES ================================ static class Pair implements Comparable<Pair> { int first, second; Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair o) { if (this.first != o.first) return this.second - o.second; return this.first - o.first; } } static class DequeNode { DequeNode prev, next; int val; DequeNode(int val) { this.val = val; } DequeNode(int val, DequeNode prev, DequeNode next) { this.val = val; this.prev = prev; this.next = next; } } // ======================= FOR INPUT ================================== static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readString() throws IOException { return next(); } static String readLine() throws IOException { return br.readLine().trim(); } static int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = readInt(); return arr; } static int[][] read2DIntArray(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) arr[i] = readIntArray(m); return arr; } static List<Integer> readIntList(int n) throws IOException { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(readInt()); return list; } static long[] readLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = readLong(); return arr; } static long[][] read2DLongArray(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) arr[i] = readLongArray(m); return arr; } static List<Long> readLongList(int n) throws IOException { List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(readLong()); return list; } static char[] readCharArray(int n) throws IOException { return readString().toCharArray(); } static char[][] readMatrix(int n, int m) throws IOException { char[][] mat = new char[n][m]; for (int i = 0; i < n; i++) mat[i] = readCharArray(m); return mat; } // ========================= FOR OUTPUT ================================== private static void printIList(List<Integer> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printLList(List<Long> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printIArray(int[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DIArray(int[][] arr) { for (int i = 0; i < arr.length; i++) printIArray(arr[i]); } private static void printLArray(long[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DLArray(long[][] arr) { for (int i = 0; i < arr.length; i++) printLArray(arr[i]); } // ====================== TO CHECK IF STRING IS NUMBER ======================== private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } private static boolean isLong(String s) { try { Long.parseLong(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } // ==================== FASTER SORT ================================ private static void sort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void sort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // ==================== MATHEMATICAL FUNCTIONS =========================== private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static long power(long a, long b) { if (b == 0) return 1L; long ans = power(a, b >> 1); ans *= ans; if ((b & 1) == 1) ans *= a; return ans; } private static int mod_power(int a, int b) { if (b == 0) return 1; int temp = mod_power(a, b >> 1); temp %= mod; temp = (int) ((1L * temp * temp) % mod); if ((b & 1) == 1) temp = (int) ((1L * temp * a) % mod); return temp; } private static int multiply(int a, int b) { return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod); } private static boolean isPrime(long n) { for (long i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } private static long nCr(long n, long r) { if (n - r > r) r = n - r; long ans = 1L; for (long i = r + 1; i <= n; i++) ans *= i; for (long i = 2; i <= n - r; i++) ans /= i; return ans; } // ==================== Primes using Seive ===================== private static List<Integer> getPrimes(int n) { boolean[] prime = new boolean[n + 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; } } // return prime; List<Integer> list = new ArrayList<>(); for (int i = 2; i <= n; i++) if (prime[i]) list.add(i); return list; } private static int[] SeivePrime(int n) { int[] primes = new int[n]; for (int i = 0; i < n; i++) primes[i] = i; for (int i = 2; i * i < n; i++) { if (primes[i] != i) continue; for (int j = i * i; j < n; j += i) { if (primes[j] == j) primes[j] = i; } } return primes; } // ==================== STRING FUNCTIONS ================================ private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } private static String sortString(String str) { int[] arr = new int[256]; for (char ch : str.toCharArray()) arr[ch]++; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; i++) while (arr[i]-- > 0) sb.append((char) i); return sb.toString(); } // ==================== LIS & LNDS ================================ private static int LIS(int arr[], int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find1(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find1(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) >= val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } // =============== Lower Bound & Upper Bound =========== // less than or equal private static int lower_bound(List<Integer> list, int val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(List<Long> list, long val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(int[] arr, int val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(long[] arr, long val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } // greater than or equal private static int upper_bound(List<Integer> list, int val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(List<Long> list, long val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(int[] arr, int val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(long[] arr, long val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // ==================== UNION FIND ===================== private static int find(int x, int[] parent) { if (parent[x] == x) return x; return parent[x] = find(parent[x], parent); } private static boolean union(int x, int y, int[] parent, int[] rank) { int lx = find(x, parent), ly = find(y, parent); if (lx == ly) return false; if (rank[lx] > rank[ly]) parent[ly] = lx; else if (rank[lx] < rank[ly]) parent[lx] = ly; else { parent[lx] = ly; rank[ly]++; } return true; } // ==================== SEGMENT TREE (RANGE SUM) ===================== public static class SegmentTree { int n; int[] arr, tree, lazy; SegmentTree(int arr[]) { this.arr = arr; this.n = arr.length; this.tree = new int[(n << 2)]; this.lazy = new int[(n << 2)]; build(1, 0, n - 1); } void build(int id, int start, int end) { if (start == end) tree[id] = arr[start]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; build(left, start, mid); build(right, mid + 1, end); tree[id] = tree[left] + tree[right]; } } void update(int l, int r, int val) { update(1, 0, n - 1, l, r, val); } void update(int id, int start, int end, int l, int r, int val) { distribute(id, start, end); if (end < l || r < start) return; if (start == end) tree[id] += val; else if (l <= start && end <= r) { lazy[id] += val; distribute(id, start, end); } else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; update(left, start, mid, l, r, val); update(right, mid + 1, end, l, r, val); tree[id] = tree[left] + tree[right]; } } int query(int l, int r) { return query(1, 0, n - 1, l, r); } int query(int id, int start, int end, int l, int r) { if (end < l || r < start) return 0; distribute(id, start, end); if (start == end) return tree[id]; else if (l <= start && end <= r) return tree[id]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r); } } void distribute(int id, int start, int end) { if (start == end) tree[id] += lazy[id]; else { tree[id] += lazy[id] * (end - start + 1); lazy[(id << 1)] += lazy[id]; lazy[(id << 1) + 1] += lazy[id]; } lazy[id] = 0; } } // ==================== TRIE ================================ static class Trie { class Node { Node[] children; boolean isEnd; Node() { children = new Node[26]; } } Node root; Trie() { root = new Node(); } public void insert(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) curr.children[ch - 'a'] = new Node(); curr = curr.children[ch - 'a']; } curr.isEnd = true; } public boolean find(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) return false; curr = curr.children[ch - 'a']; } return curr.isEnd; } } // ==================== FENWICK TREE ================================ static class FT { long[] tree; int n; FT(int[] arr, int n) { this.n = n; this.tree = new long[n + 1]; for (int i = 1; i <= n; i++) { update(i, arr[i - 1]); } } void update(int idx, int val) { while (idx <= n) { tree[idx] += val; idx += idx & -idx; } } long query(int l, int r) { return getSum(r) - getSum(l - 1); } long getSum(int idx) { long ans = 0L; while (idx > 0) { ans += tree[idx]; idx -= idx & -idx; } return ans; } } // ==================== BINARY INDEX TREE ================================ static class BIT { long[][] tree; int n, m; BIT(int[][] mat, int n, int m) { this.n = n; this.m = m; tree = new long[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { update(i, j, mat[i - 1][j - 1]); } } } void update(int x, int y, int val) { while (x <= n) { int t = y; while (t <= m) { tree[x][t] += val; t += t & -t; } x += x & -x; } } long query(int x1, int y1, int x2, int y2) { return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1); } long getSum(int x, int y) { long ans = 0L; while (x > 0) { int t = y; while (t > 0) { ans += tree[x][t]; t -= t & -t; } x -= x & -x; } return ans; } } }
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 11
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
ce13a3b80304ff2557f30215aef4b99e
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.*; /** TODO: unsloved My idea: 1. form bottom to up, if remaining * k, or 1 * */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class D{ static int N = 200010; static int mod = 998244353; static int n, m, k, q; static int[][] a = new int[N][2]; static Set<Integer> rowSt = new HashSet<>(); static Set<Integer> colSt = new HashSet<>(); public static void main(String[] args) { FastScanner sc = new FastScanner(); int T = sc.nextInt(); while (T-- > 0) { n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt(); q = sc.nextInt(); rowSt = new HashSet<>(); colSt = new HashSet<>(); for(int i = 1; i <= q; i++){ a[i][0] = sc.nextInt(); a[i][1] = sc.nextInt(); } solver(); } } static void solver() { long res = 1; for(int i = q; i >= 1; i--){ int r = a[i][0]; int c = a[i][1]; if(rowSt.contains(r) && colSt.contains(c)) continue; res = res * k % mod; rowSt.add(r); colSt.add(c); if(rowSt.size() == n || colSt.size() == m) break; } System.out.println(res); } 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 11
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
0a22c8700707b979953fe6c6f3b5cfe1
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.Objects; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); DCrossColoring solver = new DCrossColoring(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class DCrossColoring { int mod = 998244353; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(), q = in.nextInt(); long[][] dp = new long[q][2]; HashSet<Integer> set1 = new HashSet<>(); HashSet<Integer> set2 = new HashSet<>(); ArrayList<Pair> list = new ArrayList<>(); for (int i = 0; i < q; i++) { list.add(new Pair(in.nextInt(), in.nextInt())); } if (n == 1 && m == 1) { out.println(k); return; } dp[q - 1][0] = 0; dp[q - 1][1] = k; set1.add(list.get(q - 1).a); set2.add(list.get(q - 1).b); boolean flag = false; long ans = k; for (int i = q - 2; i >= 0; i--) { if ((set1.contains(list.get(i).a) && set2.contains(list.get(i).b)) || (set1.size() == n || set2.size() == m)) { continue; } ans = (ans * k) % mod; // if(set1.contains(list.get(i).a)&& set2.contains(list.get(i).b)){ // dp[i][0]=dp[i+1][0]; // dp[i][1]=dp[i+1][1]; // }else{ //// dp[i][0]=dp[i+1][0]; //// if(!flag){ //// dp[i][1]= ((k-1))%mod; //// }else{ //// //// } // dp[i][1]=(dp[i+1][1]*k)%mod; // //// dp[i][1]=(dp[i+1][1]*k)%mod; //// dp[i][1]= (dp[i+1][1]*k)%mod; // dp[i][0]= (dp[i+1][0]*(k-1))%mod; // } set1.add(list.get(i).a); set2.add(list.get(i).b); } // out.println("HERE"); // for(int i=0;i<q;i++){ // out.println(dp[i]); // } // for(int i=1;i<=n;i++){ // if(!set1.contains(i)) flag= true; // } // for(int i=1;i<=m;i++){ // if(!set2.contains(i)) flag=true; // } // out.println(((!flag?(dp[1][0]*k+dp[1][1]*(k-1)):dp[0][1]))%mod); out.println(ans); } class Pair { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return Objects.hash(a, b); } public boolean equals(Object obj) { Pair that = (Pair) obj; return a == that.a && b == that.b; } public String toString() { return "[" + a + ", " + b + "]"; } } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } public void println(int i) { writer.println(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 11
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
400140ca390538d89c69eb52534b8563
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 _772 { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(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 [][] queries = new int[q][2]; for (int i = 0; i < q; i++) { int x = sc.nextInt() - 1; int y = sc.nextInt() - 1; queries[i][0] = x; queries[i][1] = y; } int s = 0; Set<Integer> row = new HashSet<>(); Set<Integer> col = new HashSet<>(); for (int i = q - 1; i >= 0; i--) { int x = queries[i][0]; int y = queries[i][1]; row.add(x); col.add(y); if (row.size() == n) { s = i; break; } if (col.size() == m) { s = i; break; } } Map<Integer, Integer> r = new HashMap<>(); Map<Integer, Integer> c = new HashMap<>(); for (int i = s; i < q; i++) { int x = queries[i][0]; int y = queries[i][1]; r.put(x, i + 1); c.put(y, i + 1); } Set<Integer> set = new HashSet<>(); for (Integer i: r.keySet()) set.add(r.get(i)); for (Integer i: c.keySet()) set.add(c.get(i)); out.println(pow(k, set.size())); } out.close(); } static long pow(long b, long e) { long ans = 1; while (e > 0) { if (e % 2 == 1) ans = ans * b % mod; e >>= 1; b = b * b % mod; } return ans; } static long mod = (long) 998244353; static void sort(int[] a) { ArrayList<Integer> q = new ArrayList<>(); for (int i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } static void sort(long[] a) { ArrayList<Long> q = new ArrayList<>(); for (long i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["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 11
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
68c91504f3415b887168a6e70917e7f4
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 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int a = 0; a < t; a++) { HashMap<Integer, Integer> xVals = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> yVals = new HashMap<Integer, Integer>(); long ans = 1; int n = sc.nextInt(); int m = sc.nextInt(); long k = sc.nextLong(); int q = sc.nextInt(); int[] xCord = new int[q]; int[] yCord = new int[q]; for(int i = 0; i < q; i++) { xCord[i] = sc.nextInt(); yCord[i] = sc.nextInt(); } for(int i = q - 1; i >= 0; i--) { int x = xCord[i]; int y = yCord[i]; if(!xVals.containsKey(x) || !yVals.containsKey(y)) { xVals.put(x, 1); yVals.put(y, 1); ans = ans * k % 998244353; } if(xVals.size() == n || yVals.size() == m) { break; } } System.out.println(ans % 998244353); } } }
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 11
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
6a497d3158fde851ddd9e0a73235de06
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 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int a = 0; a < t; a++) { HashMap<Integer, Integer> xVals = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> yVals = new HashMap<Integer, Integer>(); long ans = 1; int n = sc.nextInt(); int m = sc.nextInt(); long k = sc.nextLong(); int q = sc.nextInt(); int[] xCord = new int[q]; int[] yCord = new int[q]; for(int i = 0; i < q; i++) { xCord[i] = sc.nextInt(); yCord[i] = sc.nextInt(); } for(int i = q - 1; i >= 0; i--) { int x = xCord[i]; int y = yCord[i]; boolean works = false; if(!xVals.containsKey(x)) { xVals.put(x, 1); works = true; } if(!yVals.containsKey(y)) { yVals.put(y, 1); works = true; } if(works) { ans = ans * k % 998244353; } if(xVals.size() == n || yVals.size() == m) { break; } } System.out.println(ans % 998244353); } } }
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 11
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
670b5cc90c6b0647577031ebc22e72e2
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.lang.Math; import java.math.BigInteger; public final class code { static class sortCond implements Comparator<Pair<Integer, Pair<Long, Long>>> { @Override public int compare(Pair<Integer, Pair<Long, Long>> p1, Pair<Integer, Pair<Long, Long>> p2) { if (p1.b.b <= p2.b.b) { return -1; } else { return 1; } } } static class sortCond1 implements Comparator<Pair<Integer, Pair<Long, Long>>> { @Override public int compare(Pair<Integer, Pair<Long, Long>> p1, Pair<Integer, Pair<Long, Long>> p2) { if (p1.b.a <= p2.b.a) { return -1; } else { return 1; } } } static class Pair<f, s> { f a; s b; Pair(f a, s b) { this.a = a; this.b = b; } } interface modOperations { int mod(int a, int b, int mod); } static int findBinaryExponentian(int a, int pow, int mod) { if (pow == 1) { return a; } else if (pow == 0) { return 1; } else { int retVal = findBinaryExponentian(a, (int) pow / 2, mod); return modMul.mod(modMul.mod(retVal, retVal, mod), (pow % 2 == 0) ? 1 : a, mod); } } static int findPow(int a, int b, int mod) { if (b == 1) { return a % mod; } else if (b == 0) { return 1; } else { int res = findPow(a, (int) b / 2, mod); return modMul.mod(res, modMul.mod(res, (b % 2 == 1 ? a : 1), mod), mod); } } static int bleft(long ele, ArrayList<Long> sortedArr) { int l = 0; int h = sortedArr.size() - 1; int ans = -1; while (l <= h) { int mid = l + (int) (h - l) / 2; if (sortedArr.get(mid) < ele) { l = mid + 1; } else if (sortedArr.get(mid) >= ele) { ans = mid; h = mid - 1; } } return ans; } static long gcd(long a, long b) { long div = b; long rem = a % b; while (rem != 0) { long temp = rem; rem = div % rem; div = temp; } return div; } static int log(long no) { int i = 0; while ((1 << i) <= no) { i += 1; } return i - 1; } static modOperations modAdd = (int a, int b, int mod) -> { return (a % mod + b % mod) % mod; }; static modOperations modSub = (int a, int b, int mod) -> { return (a % mod - b % mod + mod) % mod; }; static modOperations modMul = (int a, int b, int mod) -> { return (int) (((1l * a % mod * b % mod)) % mod); }; static modOperations modDiv = (int a, int b, int mod) -> { return modMul.mod(a, findBinaryExponentian(b, mod - 1, mod), mod); }; static ArrayList<Integer> primeList(int MAXI) { int[] prime = new int[MAXI + 1]; ArrayList<Integer> obj = new ArrayList<Integer>(); for (int i = 2; i <= (int) Math.sqrt(MAXI) + 1; i++) { if (prime[i] == 0) { obj.add(i); for (int j = i * i; j <= MAXI; j += i) { prime[j] = 1; } } } for (int i = (int) Math.sqrt(MAXI) + 1; i <= MAXI; i++) { if (prime[i] == 0) { obj.add(i); } } return obj; } static int[] factorialList(int MAXI, int mod) { int[] factorial = new int[MAXI + 1]; factorial[0] = 0 % mod; factorial[1] = 1 % mod; for (int i = 2; i < MAXI + 1; i++) { factorial[i] = modMul.mod(factorial[i - 1], i, mod); } return factorial; } static long arrSum(ArrayList<Long> arr) { long tot = 0; for (int i = 0; i < arr.size(); i++) { tot += arr.get(i); } return tot; } static int ord(char b) { return (int) b - (int) 'a' + 1; } public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int cases = Integer.parseInt(br.readLine()), n, m, k, q, i, u, v, mod = 998244353; while (cases-- != 0) { String a[] = br.readLine().split(" "); n = Integer.parseInt(a[0]); m = Integer.parseInt(a[1]); k = Integer.parseInt(a[2]); q = Integer.parseInt(a[3]); HashSet<Integer> set1 = new HashSet<Integer>(); HashSet<Integer> set2 = new HashSet<Integer>(); int ans = 1; boolean ok = true; ArrayList<Pair<Integer, Integer>> ps = new ArrayList<>(); for (i = 0; i < q; i++) { a = br.readLine().split(" "); u = Integer.parseInt(a[0]); v = Integer.parseInt(a[1]); ps.add(new Pair<>(u, v)); } for (i = q - 1; i >= 0; i--) { boolean op = false; Pair<Integer, Integer> p = ps.get(i); u = p.a; v = p.b; if (ok) { if (!set1.contains(u)) { op = true; set1.add(u); } if (!set2.contains(v)) { op = true; set2.add(v); } if (op) { ans = modMul.mod(ans, k, mod); } } if (set1.size() == n || set2.size() == m) { ok = false; } } bw.write(Integer.toString(ans) + "\n"); } bw.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 11
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
2bc5ea35e118b2ebb1e5141740604922
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 mod = 998244353; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringBuilder sb = new StringBuilder(); int test = Integer.parseInt(br.readLine()); while (test-- > 0) { String split[] = br.readLine().split(" "); long n = Long.parseLong(split[0]); long m = Long.parseLong(split[1]); long k = Long.parseLong(split[2]); long q = Long.parseLong(split[3]); Set<Long> rows = new HashSet(); Set<Long> cols = new HashSet(); long queries[][] = new long[(int)q][2]; for(int i =0;i<queries.length;i++){ split = br.readLine().split(" "); long xi = Integer.parseInt(split[0]); long yi = Integer.parseInt(split[1]); queries[i][0] = xi; queries[i][1] = yi; } long count = 0; for(int i = queries.length-1;i>=0;i--){ boolean rc =false , cc = false; if(cols.size()==m||rows.contains(queries[i][0])) rc = true; if(rows.size()==n||cols.contains(queries[i][1])) cc = true; if(rc&&cc) continue; cols.add(queries[i][1]); rows.add(queries[i][0]); count++; } sb.append(pow(k,count)).append("\n"); } out.println(sb); out.close(); } //asfjoijasds static long pow(long x , long y){ long ans = 1; while(y>0){ if(y%2!=0) ans = ((ans*x)+mod)%mod; x= ((x*x)+mod)%mod; y=y/2; } return ans; } }
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 11
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
c275713882b0d1f49e278e0b59a2ff80
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 mod = 998244353; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringBuilder sb = new StringBuilder(); int test = Integer.parseInt(br.readLine()); while (test-- > 0) { String split[] = br.readLine().split(" "); long n = Long.parseLong(split[0]); long m = Long.parseLong(split[1]); long k = Long.parseLong(split[2]); long q = Long.parseLong(split[3]); Set<Long> rows = new HashSet(); Set<Long> cols = new HashSet(); long queries[][] = new long[(int)q][2]; for(int i =0;i<queries.length;i++){ split = br.readLine().split(" "); long xi = Integer.parseInt(split[0]); long yi = Integer.parseInt(split[1]); queries[i][0] = xi; queries[i][1] = yi; } long count = 0; for(int i = queries.length-1;i>=0;i--){ boolean rc =false , cc = false; if(cols.size()==m||rows.contains(queries[i][0])) rc = true; if(rows.size()==n||cols.contains(queries[i][1])) cc = true; if(rc&&cc) continue; cols.add(queries[i][1]); rows.add(queries[i][0]); count++; } sb.append(pow(k,count)).append("\n"); } out.println(sb); out.close(); } static long pow(long x , long y){ long ans = 1; while(y>0){ if(y%2!=0) ans = ((ans*x)+mod)%mod; x= ((x*x)+mod)%mod; y=y/2; } return ans; } }
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 11
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
65358417c0cedeb1d4752f8f61fd159b
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.*; public class D_Paint { public static void main(String[] args) throws IOException { BufferedScanner input = new BufferedScanner(); BufferedOutput output = new BufferedOutput(); int tasks = input.nextInt(); while (tasks-- > 0) { int rowCount = input.nextInt(); int columnCount = input.nextInt(); int colorsCount = input.nextInt(); int opsCount = input.nextInt(); Map<Integer, Integer> rows = new HashMap<>(); Map<Integer, Integer> columns = new HashMap<>(); for (int i = 1; i <= opsCount; i++) { rows.put(input.nextInt(), i); columns.put(input.nextInt(), i); } int minRow = rows.values().stream().mapToInt(i -> i).min().orElseThrow(); if (rows.size() < rowCount) { minRow = 0; } int minColumn = columns.values().stream().mapToInt(i -> i).min().orElseThrow(); if (columns.size() < columnCount) { minColumn = 0; } int components = 0; boolean[] used = new boolean[opsCount + 1]; for (Integer index : rows.values()) { if (index >= minColumn && !used[index] && index != 0) { used[index] = true; components++; } } for (Integer index : columns.values()) { if (index >= minRow && !used[index] && index != 0) { components++; used[index] = true; } } long combinations = 1; for (int i = 0; i < components; i++) { combinations = (combinations * colorsCount) % 998244353; } output.println(combinations); } output.flush(); } private static class BufferedScanner { private final BufferedReader reader; private StringTokenizer tokenizer; public BufferedScanner() { reader = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public String nextLine() throws IOException { tokenizer = null; return reader.readLine(); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } } private static class BufferedOutput { private final StringBuilder result; public BufferedOutput() { result = new StringBuilder(); } public void print(Object object) { result.append(object); } public void println(Object object) { result.append(object).append("\n"); } public void flush() { System.out.println(result); System.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 11
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
deed90c02fdf4e0d2cebffd682cce26a
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 CF1644D extends PrintWriter { CF1644D() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; byte[] bb = new byte[1 << 15]; int i, n; byte getc() { if (i == n) { i = n = 0; try { n = in.read(bb); } catch (IOException e) {} } return i < n ? bb[i++] : 0; } int nextInt() { byte c = 0; while (c <= ' ') c = getc(); int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); } return a; } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1644D o = new CF1644D(); o.main(); o.flush(); } static final int MD = 998244353, N = 200000; void main() { int[] hi = new int[N]; int[] hj = new int[N]; int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int q = sc.nextInt(); int[] ii = new int[q + 1]; int[] jj = new int[q + 1]; int n_ = 0; int m_ = 0; for (int h = 1; h <= q; h++) { int i = ii[h] = sc.nextInt() - 1; int j = jj[h] = sc.nextInt() - 1; if (hi[i] == 0) n_++; if (hj[j] == 0) m_++; hi[i] = h; hj[j] = h; } int hi_; if (n_ == n) { hi_ = q + 1; for (int h = 1; h <= q; h++) { int i = ii[h]; if (hi[i] == h) hi_ = Math.min(hi_, h); } } else hi_ = 0; int hj_; if (m_ == m) { hj_ = q + 1; for (int h = 1; h <= q; h++) { int j = jj[h]; if (hj[j] == h) hj_ = Math.min(hj_, h); } } else hj_ = 0; long ans = 1; for (int h = 1; h <= q; h++) { int i = ii[h]; int j = jj[h]; if (hi[i] == h && h >= hj_ || hj[j] == h && h >= hi_) ans = ans * k % MD; } println(ans); for (int h = 1; h <= q; h++) { int i = ii[h]; int j = jj[h]; hi[i] = hj[j] = 0; } } } }
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 11
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
c02d84bfde9fd8d0b137d7288fd1eb3b
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.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class App { 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 class Pair { private final int x; private final int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (x != pair.x) return false; return y == pair.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } } public static void main(String[] args) { FastReader reader = new FastReader(); PrintWriter writer = new PrintWriter(System.out, true); int t = reader.nextInt(); for (int i = 1; i <= t; i++) { int n = reader.nextInt(); int m = reader.nextInt(); int k = reader.nextInt(); int q = reader.nextInt(); Set<Integer> matrixRows = new HashSet<>(); Set<Integer> matrixColumns = new HashSet<>(); long res = 1; long modulo = 998244353; List<Pair> list = new ArrayList<>(); for (int j = 1; j <= q; j++) { list.add(new Pair(reader.nextInt(), reader.nextInt())); } for (int j = q - 1; j >= 0; j--) { Pair pair = list.get(j); int x = pair.x; int y = pair.y; boolean painted = !matrixRows.contains(x) && matrixColumns.size() != m; if (!matrixColumns.contains(y) && matrixRows.size() != n) { painted = true; } matrixRows.add(x); matrixColumns.add(y); if (painted) res = (res * k) % modulo; } writer.println(res); } } }
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 11
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
304c87aece33f8cb3103ee3a86e77d05
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 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int numCases = Integer.parseInt(br.readLine()); for (int i = 0; i < numCases; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int numRows = Integer.parseInt(st.nextToken()); int numCols = Integer.parseInt(st.nextToken()); int numColors = Integer.parseInt(st.nextToken()); int numOperations = Integer.parseInt(st.nextToken()); HashMap<Integer, Integer> rowMap = new HashMap<>(); HashMap<Integer, Integer> colMap = new HashMap<>(); for (int j = 0; j < numOperations; j++) { st = new StringTokenizer(br.readLine()); int row = Integer.parseInt(st.nextToken()); int col = Integer.parseInt(st.nextToken()); rowMap.put(row, j); colMap.put(col, j); } if (rowMap.size() >= numRows) { int minTime = Integer.MAX_VALUE; for (int key : rowMap.keySet()) { minTime = Math.min(minTime, rowMap.get(key)); } HashMap<Integer, Integer> colMapClone = new HashMap<>(); for (int key : colMap.keySet()) { int location = colMap.get(key); if (location >= minTime) colMapClone.put(key, location); } colMap = colMapClone; } if (colMap.size() >= numCols) { int minTime = Integer.MAX_VALUE; for (int key : colMap.keySet()) { minTime = Math.min(minTime, colMap.get(key)); } HashMap<Integer, Integer> rowMapClone = new HashMap<>(); for (int key : rowMap.keySet()) { int location = rowMap.get(key); if (location >= minTime) rowMapClone.put(key, location); } rowMap = rowMapClone; } int count = 0; boolean[] operationUsed = new boolean[numOperations]; for (int key : rowMap.keySet()) { int time = rowMap.get(key); if (!operationUsed[time]) { count++; operationUsed[time] = true; } } for (int key : colMap.keySet()) { int time = colMap.get(key); if (!operationUsed[time]) { count++; operationUsed[time] = true; } } long ret = 1; long MOD = 998244353; for (int j = 0; j < count; j++) { ret *= numColors; ret %= MOD; } pw.println(ret); } br.close(); 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 11
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
ba42d78452251fe93d0eb1253da956a8
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.*; import java.math.BigInteger; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; public class k { //public static int mod=1000000007; public static long printDivisors(long n, int k) { // Note that this loop runs till square root long x=(long) Math.sqrt(n); // int p=0; long sum=0; for (long i=1; i<=x; i++) { if (n%i == 0) { // If divisors are equal, print only one if (n/i == i) sum=sum+(long)(i); else // Otherwise print both sum=sum+(long)(i)+(long)(n/i); } if(sum>k)return -1; } return sum; } public static ArrayList<Long> Factors(long n) { ArrayList<Long> arr=new ArrayList<Long>(); int k=0; while (n%2==0) { k++; n /=2; arr.add((long)2); } int p=(int) Math.sqrt(n); for (int i = 3; i <=p; i+= 2) { if(n==1)break; while (n%i == 0) { k++; arr.add((long)i); n /= i; } } if (n > 2) { arr.add(n); } return arr; } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { 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(); } } public static long gcd(long x, long p) { if (x == 0) return p; return gcd(p%x, x); } // method to return LCM of two numbers static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<Integer, Integer> > list = new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() { public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } static int sieve = 1000000 ; static boolean[] prime = new boolean[sieve + 1] ; static ArrayList<Integer> pr=new ArrayList<Integer>(); public static void sieveOfEratosthenes() { // FALSE == prime and 1 // TRUE == COMPOSITE // time complexity = 0(NlogLogN)== o(N) // gives prime nos bw 1 to N // size - 1e7(at max) for(int i = 4; i<= sieve ; i++) { prime[i] = true ; i++ ; } for(int p = 3; p*p <= sieve; p++) { if(prime[p] == false) { pr.add(p); for(int i = p*p; i <= sieve; i += p) prime[i] = true; } p++ ; } } public static void arrInpInt(int [] arr, int n) throws IOException { Reader reader = new Reader(); for(int i=0;i<n;i++) { arr[i]=reader.nextInt(); } } public static void arrInpLong(long [] arr, int n) throws IOException { Reader reader = new Reader(); for(int i=0;i<n;i++) { arr[i]=reader.nextLong(); } } public static void printArr(int[] arr) { for(int i=0;i<arr.length;i++) { System.out.print(arr[i]+" "); } System.out.println(); } public static int[] decSort(int[] arr) { int[] arr1 = Arrays.stream(arr).boxed().sorted(Collections.reverseOrder()).mapToInt(Integer::intValue).toArray(); return arr1; } //if present - return the first occurrence of the no //not present- return the index of next greater value //if greater than all the values return N(taking high=N-1) //if smaller than all the values return 0(taking low =0) static int lower_bound(int arr[], int low,int high, int X) { if (low > high) { return low; } int mid = low + (high - low) / 2; if (arr[mid] >= X) { return lower_bound(arr, low, mid - 1, X); } return lower_bound(arr, mid + 1, high, X); } //if present - return the index of next greater value //not present- return the index of next greater value //if greater than all the values return N(taking high=N-1) //if smaller than all the values return 0(taking low =0)\ static int upper_bound(int arr[], int low, int high, int X) { if (low > high) return low; int mid = low + (high - low) / 2; if (arr[mid] <= X) { return upper_bound(arr, mid + 1, high, X); } return upper_bound(arr, low, mid - 1, X); } public static class Pair {// comparator with class int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } public static void sortbyColumn(int arr[][], int col) // send 2d array and col no { Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(final int[] entry1, final int[] entry2) { if (entry1[col] > entry2[col]) return 1; else if (entry1[col] < entry2[col]) return -1; else return 0; } }); } public static void sortbyColumn1(int arr[][], int col) // send 2d array and col no { Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(final int[] entry1, final int[] entry2) { if (entry1[col] > entry2[col]) return 1; else if (entry1[col] < entry2[col]) return -1; else if(entry1[col] == entry2[col]) { if(entry1[col-1]>entry2[col-1]) return -1; else if(entry1[col-1]<entry2[col-1]) return 1; else return 0; } else return 0; } }); } public static void print2D(int mat[][]) { // Loop through all rows for (int i = 0; i < mat.length; i++) { // Loop through all elements of current row { for (int j = 0; j < mat[i].length; j++) System.out.print(mat[i][j] + " "); } System.out.println(); } } public static int biggestFactor(int num) { int result = 1; for(int i=2; i*i <=num; i++){ if(num%i==0){ result = num/i; break; } } return result; } public static int knapsack(int[] weights,int[] price, int totW) { int[] dp1=new int[totW+1]; int[] dp2=new int[totW+1]; int N=totW; int ans=0; for(int i=0;i<price.length;i++) { for(int j=0;j<=N;j++) { if(weights[i]>j) { if(i%2==0) { dp1[j]=dp2[j]; } else { dp2[j]=dp1[j]; } } else { if(i%2==0) { dp1[j]=Math.max(dp2[j],dp2[j-weights[i]]+price[i]); } else { dp2[j]=Math.max(dp1[j], dp1[j-weights[i]]+price[i]); } } } if(i%2==0)ans=dp1[N]; else ans=dp2[N]; } return ans; } public static class p { int no; int h; public p(int no, long h) { this.no=no; this.h=(int) h; } } static class com implements Comparator<p>{ public int compare(p s1, p s2) { if (s1.h > s2.h) return -1; else if (s1.h < s2.h) return 1; else if(s1.h==s2.h) { if(s1.no>s2.no)return -1; else return 1; } return 0; } } static long hcf(long a,long b) { while (b > 0) { long temp = b; b = a % b; a = temp; } return a; } static int lower_bound_arr(ArrayList<Integer> arr, int low, int high, int X) { if (low > high) { return low; } int mid = low + (high - low) / 2; if (arr.get(mid) >= X) { return lower_bound_arr(arr, low, mid - 1, X); } return lower_bound_arr(arr, mid + 1, high, X); } public static int func2(int m,int[] arr,int k,int[] arr1) { for(int i=0;i<arr.length;i++) { int p=arr[i]; int q=arr[i]+m; int in=(q<=arr.length?arr1[q]:arr.length)-arr1[p-1]; if((in)-(arr.length-in)>=k)return arr[i]; } return 0; } public static boolean func(int m,int[] arr,int k,int[] arr1) { for(int i=0;i<arr.length;i++) { int p=arr[i]; int q=arr[i]+m; int in=(q<=arr.length?arr1[q]:arr.length)-arr1[p-1]; if((in)-(arr.length-in)>=k)return true; } return false; } public static int binarySearch(int min, int max, int[] arr,int k,int[] arr1) { int l = min, r = max; while (l <= r) { int m = l + (r - l) / 2; boolean x11=func(m,arr,k,arr1); boolean x1=func(m-1,arr,k,arr1); if(x11 && !x1)return m; //Check if x is present at mid // if (arr[m] == x) // return m; // If x greater, ignore left half if (!x1 && !x11) l = m + 1; // If x is smaller, ignore right half else r = m - 1; } return max; } static long isP(long x) { if (x >= 0) { // Find floating point value of // square root of x. long sr = (long)Math.sqrt(x); // if product of square root // is equal, then // return T/F long k=sr*sr; if(k == x)return sr; } return -1; } // public static long func(Integer[] arr, int k) // { // // } // public static HashMap<String,Integer> map1=new HashMap<String,Integer>(); // public static int function1(int[][] arr1,Integer[] arr, int start, int end) // { //// System.out.println("1"); // // int p=0; // int n=0; // p=arr1[end][0]-arr1[start-1][0]; // n=arr1[end][1]-arr1[start-1][1]; //// return Math.abs(n-p); // if(n==p)return 0; // if(map1.containsKey(start+" "+end))return map1.get(start+" "+end); // else // { // int min=Integer.MAX_VALUE; // int n1=0; // int p1=0; // for(int i=end-1;i>=start-1;i--) // { //// System.out.println("pp"); //// int P=p-(arr[i]==1?1:0)-p1+n1; //// int N=n-(arr[i]==-1?1:0)-n1+p1; // int P=(arr[i]==1?1:0)-p1+n1; // int N=(arr[i]==-1?1:0)-n1+p1; // if(arr[i]==-1)n1++; // else p1++; // // p=arr1[end][0]-arr1[i+1][0]; // n=arr1[end][1]-arr1[i+1][1]; // //// min=Math.min(Math.abs(P-N), min); //// map1.put((i+1)+" "+end,min+1); // } // // // // return min; // } // } public static long pwmd(long a, long n,long mod) { if (n == 0) return 1; long pt = pwmd(a, n / 2,mod); pt *= pt; pt %= mod; if ((n & 1) > 0) { pt *= a; pt %= mod; } return pt; } public static void main(String args[]) throws NumberFormatException, IOException ,java.lang.Exception { Reader reader = new Reader(); long mod= 998244353; //// power(); // long[] pow2 =new long[64]; // pow2[0]=1l; // for(int i=1;i<64;i++) // { //// pow2[i]=(int) Math.pow(2, i); // pow2[i]=((long)(2)*pow2[i-1])%mod; //// System.out.println(pow2[i]); // } // sieveOfEratosthenes(); //Scanner reader=new Scanner(System.in); // PrintWriter out = new PrintWriter(System.out); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // int cases=Integer.parseInt(br.readLine()); // int cases=1; int cases=reader.nextInt(); while (cases-->0){ // long N=reader.nextLong(); // // long M=reader.nextLong(); // long X=reader.nextLong(); // long Y=reader.nextLong(); // long H2=reader.nextLong(); // long D2=reader.nextLong(); // // long C=reader.nextLong(); // long W=reader.nextLong(); // long A=reader.nextLong(); int N=reader.nextInt(); int M=reader.nextInt(); int K=reader.nextInt(); int P=reader.nextInt(); // int K=reader.nextInt(); // long M=reader.nextLong(); // // long X=reader.nextLong(); // String p=""; // while(p.equals(""))p=br.readLine(); ////// // String[] first1=br.readLine().split(" "); // int N=Integer.parseInt(first1[0]); // int M=Integer.parseInt(first1[1]); // long K=Long.parseLong(first1[0]); // long X=Long.parseLong(first1[1]); // String s3=br.readLine(); // char[] s11=s2.toCharArray(); // char[] s12=new char[s11.length]; int max=Integer.MIN_VALUE; // int max1=Integer.MIN_VALUE; int min=Integer.MAX_VALUE; // long min=Inteeg.MAX_VALUE; // int min1=Integer.MAX_VALUE; // int min2=Integer.MAX_VALUE; // HashMap<Integer, Integer> map=new HashMap<Integer,Integer>(); // PriorityQueue<Integer> q = new PriorityQueue<Integer>(Collections.reverseOrder()); // PriorityQueue<Long> q = new PriorityQueue<Long>(Collections.reverseOrder()); // HashMap<Integer,TreeSet<Integer>> map=new HashMap<Integer,TreeSet<Integer>>(); // HashMap<Long,Long> map=new HashMap<Long,Long>(); // HashMap<String,String> map1=new HashMap<String,String>(); // HashMap<Integer,Integer> map1=new HashMap<Integer,Integer>(); // List<TreeMap<Integer,Integer>> map = new ArrayList<TreeMap<Integer,Integer>>(); // HashSet<Character> set =new HashSet<Character>(); // HashSet<String> set1 =new HashSet<String>(); // HashSet<Integer> map1 =new HashSet<Integer>(); HashSet<Integer> set =new HashSet<Integer>(); // TreeSet<Integer> a =new TreeSet<Integer>(); //TreeSet<Long> b =new TreeSet<Long>(); // TreeSet<Integer> map=new TreeSet<Integer>(); // int[] arr=new int[(int)M]; // int[] arr=new int[N]; // int[] arr2=new int[64]; // int[] ev=new int[N]; // int[] od=new int[N]; // // int[] arr1=new int[N]; // int[] arr2=new int[26];// i00nt[] odd=new int[100001]; // int[] arr=new int[N]; // int[] arr2=new int[5]; // Integer[] arr=new Integer[N]; // Integer[] arr1=new Integer[N]; // long[] arr=new long[N]; // Long[] arr=new Long[N]; int[][] arr1=new int[P][2]; // ArrayList<Long> list=new ArrayList<Long>(); // ArrayList<String> l=new ArrayList<String>(); // ArrayList<Integer> even=new ArrayList<Integer>(); // ArrayList<Integer> odd=new ArrayList<Integer>(); // ArrayList<Long> bees=new ArrayList<Long>(); // boolean[]arr1=new boolean[N]; // if(Math.abs(arr[0]-arr[1])>M-1)p=false; // if(Math.abs(arr[N-1]-arr[N-2])>M-1)p=false; for(int i=0;i<P;i++) { arr1[i][0]=reader.nextInt(); arr1[i][1]=reader.nextInt(); } int ind1=P-1; while(set.size()!=M && ind1>=0) { set.add(arr1[ind1][1]);ind1--; } int ind2=P-1; set.clear(); while(set.size()!=N && ind2>=0) { set.add(arr1[ind2][0]);ind2--; } // int diff=0; set.clear(); int ind=Math.max(ind1, ind2); HashSet<Integer> r=new HashSet<Integer>(); HashSet<Integer> c=new HashSet<Integer>(); int d=0; for(int i=P-1;i>=ind+1;i--) { if(r.contains(arr1[i][0]) && c.contains(arr1[i][1])) { continue; } d++; r.add(arr1[i][0]); c.add(arr1[i][1]); } System.out.println(pwmd(K,d,mod)); // System.out.println(ans); } // output.flush(); } } // output.flush(); // output.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 11
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
d33e9e7214516f32d81e701ba3ecf4bb
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 {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 int mod = 998244353 ; static int N = 200005; static long factorial_num_inv[] = new long[N+1]; static long natual_num_inv[] = new long[N+1]; static long fact[] = new long[N+1]; static void InverseofNumber() { natual_num_inv[0] = 1; natual_num_inv[1] = 1; for (int i = 2; i <= N; i++) natual_num_inv[i] = natual_num_inv[mod % i] * (mod - mod / i) % mod; } static void InverseofFactorial() { factorial_num_inv[0] = factorial_num_inv[1] = 1; for (int i = 2; i <= N; i++) factorial_num_inv[i] = (natual_num_inv[i] * factorial_num_inv[i - 1]) % mod; } static long nCrModP(long N, long R) { long ans = ((fact[(int)N] * factorial_num_inv[(int)R]) % mod * factorial_num_inv[(int)(N - R)]) % mod; return ans%mod; } static boolean prime[]; 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] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } } public static void main (String[] args) throws java.lang.Exception { InverseofNumber(); InverseofFactorial(); fact[0] = 1; for (long i = 1; i <= 2*100000; i++) { fact[(int)i] = (fact[(int)i - 1] * i) % mod; } FastReader scan = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int t = scan.nextInt(); while(t-->0){ int n = scan.nextInt(); int m = scan.nextInt(); long k = scan.nextLong(); int q = scan.nextInt(); long mod = 998244353; Pair query[] = new Pair[q]; for(int i=0;i<q;i++){ int x = scan.nextInt(); int y = scan.nextInt(); query[i] = new Pair(x,y); } HashSet<Integer> hsx = new HashSet<>(); HashSet<Integer> hsy = new HashSet<>(); long grp = 0; for(int i=q-1;i>=0;i--){ int x = query[i].x; int y = query[i].y; if(!hsx.contains(x) && !hsy.contains(y)){ grp++; hsx.add(x); hsy.add(y); } else if(!hsx.contains(x) && hsy.size()!=m){ grp++; hsx.add(x); } else if(!hsy.contains(y) && hsx.size()!=n){ grp++; hsy.add(y); } } long ans = bin_exp_mod(k, grp); pw.println(ans); pw.flush(); } } //static long bin_exp_mod(long a,long n){ // long res = 1; // while(n!=0){ // if(n%2==1){ // res = ((res)*(a)); // } // n = n/2; // a = ((a)*(a)); // } // return res; //} static long bin_exp_mod(long a,long n){ long mod = 998244353; long res = 1; while(n!=0){ if(n%2==1){ res = ((res%mod)*(a%mod))%mod; } n = n/2; a = ((a%mod)*(a%mod))%mod; } res = res%mod; return res; } // static long gcd(long a,long b){ // if(a==0) // return b; // return gcd(b%a,a); // } // static long lcm(long a,long b){ // return (a/gcd(a,b))*b; // } } class Pair{ int x,y; Pair(int x,int y){ this.x = x; this.y = y; } //public boolean equals(Object obj) { // // TODO Auto-generated method stub // if(obj instanceof Pair) // { // Pair temp = (Pair) obj; // if(this.x.equals(temp.x) && this.y.equals(temp.y)) // return true; // } // return false; //} //@Override //public int hashCode() { // // TODO Auto-generated method stub // return (this.x.hashCode() + this.y.hashCode()); //} } class Compar implements Comparator<Pair>{ public int compare(Pair p1,Pair p2){ if(p1.y==p2.y) return 0; else if(p1.y<p2.y) return -1; else return 1; } } //class DisjointSet{ // Map<Long,Node> map = new HashMap<>(); // class Node{ // long data; // Node parent; // int rank; // } // public void makeSet(long data){ // Node node = new Node(); // node.data = data; // node.parent = node; // node.rank = 0; // map.put(data,node); // } // //here we just need the rank of parent to be exact // public void union(long data1,long data2){ // Node node1 = map.get(data1); // Node node2 = map.get(data2); // Node parent1 = findSet(node1); // Node parent2 = findSet(node2); // if(parent1.data==parent2.data){ // return; // } // if(parent1.rank>=parent2.rank){ // parent1.rank = (parent1.rank==parent2.rank)?parent1.rank+1:parent1.rank; // parent2.parent = parent1; // } // else{ // parent1.parent = parent2; // } // } // public long findSet(long data){ // return findSet(map.get(data)).data; // } // private Node findSet(Node node){ // Node parent = node.parent; // if(parent==node){ // return parent; // } // node.parent = findSet(node.parent); // return node.parent; // } // }
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 11
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
37e32a463ef968879d0e0896cd2e7e00
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 Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]),k=Integer.parseInt(s[2]),q=Integer.parseInt(s[3]); int i,c[][]=new int[q][2]; for(i=0;i<q;i++) { s=bu.readLine().split(" "); int x=Integer.parseInt(s[0]),y=Integer.parseInt(s[1]); c[i][0]=x; c[i][1]=y; } long ans=1,M=998244353; Set<Integer> x=new HashSet<>(),y=new HashSet<>(); for(i=q-1;i>=0;i--) { boolean okrow=y.size()!=m && !x.contains(c[i][0]); boolean okcol=x.size()!=n && !y.contains(c[i][1]); if(okrow || okcol) ans=ans*k%M; x.add(c[i][0]); y.add(c[i][1]); } sb.append(ans+"\n"); } System.out.print(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 11
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
ff93dbe7043116ba8443d96ab81a87ad
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 Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void sort(int a[]){ // int -> long ArrayList<Integer> arr=new ArrayList<>(); // Integer -> Long for(int i=0;i<a.length;i++) arr.add(a[i]); Collections.sort(arr); for(int i=0;i<a.length;i++) a[i]=arr.get(i); } private static long gcd(long a, long b){ if(b==0)return a; return gcd(b,a%b); } private static long pow(long x,long y){ if(y==0)return 1; long temp = pow(x, y/2); if(y%2==1){ return (((x*temp)%mod)*temp)%mod; } else{ return (temp*temp)%mod; } } static int log(long n){ if(n<=1)return 0; long temp = n; int res = 0; while(n>1){ res++; n/=2; } return (1<<res)==temp?res:res+1; } static int mod = 998244353; static int INF = Integer.MAX_VALUE; static PrintWriter out; static FastReader sc ; public static void main(String[] args) throws IOException { sc = new FastReader(); out = new PrintWriter(System.out); // primes(); // ================================ // int test = sc.nextInt(); while (test-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int q = sc.nextInt(); solver(n,m,k,q); } // ================================ // // int n = sc.nextInt(); // solver(); // ================================ // out.flush(); } public static void solver(int n, int m, int k, int q) { HashSet<Integer> setx = new HashSet<>(); HashSet<Integer> sety = new HashSet<>(); int[][] arr = new int[q][2]; int p =0; for(int i=0;i<q;i++){ arr[i][0] = sc.nextInt(); arr[i][1] = sc.nextInt(); } for(int i=q-1;i>=0;i--){ if( setx.size()!=n && sety.size()!=m && (!setx.contains(arr[i][0]) || !sety.contains(arr[i][1])) ){ p++; } setx.add(arr[i][0]); sety.add(arr[i][1]); } out.println( pow(k,p)); } }
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 11
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
1e8850af57d04f4347ff874420ed8f02
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.Arrays; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; public class codeforces_Edu123_D { private static long mod = 998_244_353; private static void solve(FastIOAdapter in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int q = in.nextInt(); int[][] qq = new int[q][2]; for (int i = 0; i < q; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; qq[i][0] = x; qq[i][1] = y; } boolean[] row = new boolean[n]; int nc = n; boolean[] col = new boolean[m]; int mc = m; int sz = 0; for (int i = q - 1; i >= 0; i--) { if (!row[qq[i][0]] && mc > 0 || !col[qq[i][1]] && nc > 0) sz++; if (!row[qq[i][0]]) nc--; if (!col[qq[i][1]]) mc--; row[qq[i][0]] = true; col[qq[i][1]] = true; } long ans = 1; for (int i = 0; i < sz; i++) { ans = ans * k % mod; } out.println(ans); } public static void main(String[] args) throws Exception { try (FastIOAdapter ioAdapter = new FastIOAdapter()) { int count = 1; count = ioAdapter.nextInt(); while (count-- > 0) { solve(ioAdapter, ioAdapter.out); } } } static void ruffleSort(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static class FastIOAdapter implements AutoCloseable { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter((System.out)))); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } 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(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()); } @Override public void close() throws Exception { out.flush(); out.close(); br.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 11
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
19182def64e2e7f3ef5ce9dada9dba83
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.Arrays; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; public class codeforces_Edu123_D { private static long mod = 998_244_353; private static void solve(FastIOAdapter in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int q = in.nextInt(); int[][] qq = new int[q][]; for (int i = 0; i < q; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; qq[i] = new int[] {x, y}; } boolean[] row = new boolean[n]; int nc = n; boolean[] col = new boolean[m]; int mc = m; int sz = 0; for (int i = q - 1; i >= 0; i--) { if (!row[qq[i][0]] && mc > 0 || !col[qq[i][1]] && nc > 0) sz++; if (!row[qq[i][0]]) nc--; if (!col[qq[i][1]]) mc--; row[qq[i][0]] = true; col[qq[i][1]] = true; } long ans = 1; for (int i = 0; i < sz; i++) { ans = ans * k % mod; } out.println(ans); } public static void main(String[] args) throws Exception { try (FastIOAdapter ioAdapter = new FastIOAdapter()) { int count = 1; count = ioAdapter.nextInt(); while (count-- > 0) { solve(ioAdapter, ioAdapter.out); } } } static void ruffleSort(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static class FastIOAdapter implements AutoCloseable { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter((System.out)))); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } 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(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()); } @Override public void close() throws Exception { out.flush(); out.close(); br.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 11
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
31d061d45e2e150f5667fa6d31185f55
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 static java.lang.Math.*; public class D{ static long mod = 998244353; static class Pair{ int a, b; public Pair(int x, int y) {a=x;b=y;} } public static void main(String[] args) throws IOException { // br = new BufferedReader(new FileReader(".in")); // out = new PrintWriter(new FileWriter(".out")); //new Thread(null, new (), "peepee", 1<<28).start(); int t= readInt(); while(t-->0) { // If there exists row above, or col above, fail. // Also, if there's a coloring from 1-n or 1-m, everything below fails automatically int n = readInt(), m =readInt(); long k =readInt(); int q = readInt(); TreeMap<Integer, Integer> rowA = new TreeMap<>(); TreeMap<Integer, Integer> colA = new TreeMap<>(); Pair[] cor = new Pair[q]; for (int i = 0; i < q; i++) { int r =readInt(), c =readInt(); rowA.put(r, i); colA.put(c, i); cor[i] = new Pair(r,c); } int minOkRow = 0; int minOkCol = 0; TreeSet<Integer> ts = new TreeSet<Integer>(); for (int i = q-1; i >= 0; i--) { ts.add(cor[i].a); if (ts.size()==n) { minOkRow = i; break; } } ts.clear(); for (int i = q-1; i >= 0; i--) { ts.add(cor[i].b); if (ts.size()==m) { minOkCol = i; break; } } int start = max(minOkRow, minOkCol); int matter = 0; for (int i = start; i < q; i++) { if (rowA.get(cor[i].a) != i && colA.get(cor[i].b) != i) continue; matter++; } long prod = 1; while (matter-->0) { prod*=k; prod%=mod; } out.println(prod); } out.close(); } /* Stupid things to try if stuck: * n=1, expand bsearch range * brute force small patterns * submit stupid intuition */ static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static StringTokenizer st = new StringTokenizer(""); static String read() throws IOException{return st.hasMoreTokens() ? st.nextToken():(st = new StringTokenizer(br.readLine())).nextToken();} static int readInt() throws IOException{return Integer.parseInt(read());} static long readLong() throws IOException{return Long.parseLong(read());} static double readDouble() throws IOException{return Double.parseDouble(read());} }
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 11
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
12e24b0c00f471843e5c0f71ddcec456
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.*; public class Code { private static Scanner scanner; private static final Integer PRIME = 998_244_353; public static void main(String[] args) { scanner = new Scanner(System.in); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { solve(); } } private static void solve() { int n = scanner.nextInt(); int m = scanner.nextInt(); int k = scanner.nextInt(); int q = scanner.nextInt();; List<Integer> row = new ArrayList<>(); List<Integer> col = new ArrayList<>(); for (int i = 0; i < q; i++) { int r = scanner.nextInt(); int c = scanner.nextInt(); row.add(r); col.add(c); } Set<Integer> rowSet = new HashSet<>(); Set<Integer> colSet = new HashSet<>(); Long ans = 1L; for (int i = q-1; i >= 0; i--) { int r = row.get(i); int c = col.get(i); boolean flag = false; if (!rowSet.contains(r)) { rowSet.add(r); flag = true; } if (!colSet.contains(c)) { colSet.add(c); flag = true; } if (flag) ans = ((ans % PRIME) * (k % PRIME)) % PRIME; if (rowSet.size() == n || colSet.size() == m) break; } System.out.println(ans); } }
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 11
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
dda7abaae39261b842591cb8e2b888b5
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.Map; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class TaskD { final long mod = 998244353; public static void main(String[] args) { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while (t-- > 0) { TaskD s = new TaskD(); s.solve(in, out); } out.flush(); } void solve(FastScanner in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(), q = in.nextInt(); int queries[][] = new int[q][2]; for (int i = 0; i < q; i++) { queries[i][0] = in.nextInt() - 1; queries[i][1] = in.nextInt() - 1; } TreeSet<Integer> row = new TreeSet<>(); TreeSet<Integer> column = new TreeSet<>(); int cnt = 0; for (int i = q - 1; i >= 0; i--) { int x = queries[i][0]; int y = queries[i][1]; boolean fullRow = row.size() == n; boolean fullColumn = column.size() == m; if (!fullColumn && !row.contains(x)) { cnt++; row.add(x); column.add(y); continue; } if (!fullRow && !column.contains(y)) { cnt++; row.add(x); column.add(y); continue; } } out.println(mypow(k, cnt)); } long mypow(long a, long b) { long ans = 1; while (b > 0) { if ((b & 1) == 1) { ans = (ans * a) % mod; } a = (a * a) % mod; b >>= 1; } return ans; } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } float nextFloat() { return Float.parseFloat(next()); } 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 11
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
72dbfe9190535ede1e06407adf078083
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.*; public class Main implements Runnable { public static void main(String[] args) { new Thread(null, new Main(), "whatever", 1 << 26).start(); } // private FastScanner sc; private PrintWriter pw; public void run() { try { boolean isSumitting = true; // isSumitting = false; if (isSumitting) { pw = new PrintWriter(System.out); sc = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); } else { pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); sc = new FastScanner(new BufferedReader(new FileReader("input.txt"))); } } catch (Exception e) { throw new RuntimeException(); } int t = sc.nextInt(); // int t = 1; while (t-- > 0) { // sc.nextLine(); // System.out.println("for t=" + t); solve(); } pw.close(); } // public long mod = 1_000_000_007; public long mod = 998_244_353; private class Pair { int first, second; Pair(int first, int second) { this.first = first - 1; this.second = second - 1; } } public void solve() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int q = sc.nextInt(); if (q == 0) { pw.println(0); return; } int rowsCount = n; int columnsCount = m; boolean[] rows = new boolean[n]; boolean[] columns = new boolean[m]; Stack<Pair> queries = new Stack<Pair>(); for (int i = 0; i < q; i++) { queries.add(new Pair(sc.nextInt(), sc.nextInt())); } int x, y; int ans = 0; boolean found = false; Pair p; while (queries.size() != 0) { p = queries.pop(); x = p.first; y = p.second; found = false; if (!rows[x] && columnsCount > 0) { rows[x] = true; rowsCount--; found = true; } if (!columns[y] && rowsCount > 0) { columns[y] = true; columnsCount--; found = true; } if (found) ans++; } pw.println(fastPow((long)k, (long)ans, mod)); } class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(BufferedReader bf) { reader = bf; tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String[] nextStringArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = next(); } return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } private static class Sorter { public static <T extends Comparable<? super T>> void sort(T[] arr) { Arrays.sort(arr); } public static <T> void sort(T[] arr, Comparator<T> c) { Arrays.sort(arr, c); } public static <T> void sort(T[][] arr, Comparator<T[]> c) { Arrays.sort(arr, c); } public static <T extends Comparable<? super T>> void sort(ArrayList<T> arr) { Collections.sort(arr); } public static <T> void sort(ArrayList<T> arr, Comparator<T> c) { Collections.sort(arr, c); } public static void normalSort(int[] arr) { Arrays.sort(arr); } public static void normalSort(long[] arr) { Arrays.sort(arr); } public static void sort(int[] arr) { timSort(arr); } public static void sort(int[] arr, Comparator<Integer> c) { timSort(arr, c); } public static void sort(int[][] arr, Comparator<Integer[]> c) { timSort(arr, c); } public static void sort(long[] arr) { timSort(arr); } public static void sort(long[] arr, Comparator<Long> c) { timSort(arr, c); } public static void sort(long[][] arr, Comparator<Long[]> c) { timSort(arr, c); } private static void timSort(int[] arr) { Integer[] temp = new Integer[arr.length]; for (int i = 0; i < arr.length; i++) temp[i] = arr[i]; Arrays.sort(temp); for (int i = 0; i < arr.length; i++) arr[i] = temp[i]; } private static void timSort(int[] arr, Comparator<Integer> c) { Integer[] temp = new Integer[arr.length]; for (int i = 0; i < arr.length; i++) temp[i] = arr[i]; Arrays.sort(temp, c); for (int i = 0; i < arr.length; i++) arr[i] = temp[i]; } private static void timSort(int[][] arr, Comparator<Integer[]> c) { Integer[][] temp = new Integer[arr.length][arr[0].length]; for (int i = 0; i < arr.length; i++) for (int j = 0; j < arr[0].length; j++) temp[i][j] = arr[i][j]; Arrays.sort(temp, c); for (int i = 0; i < arr.length; i++) for (int j = 0; j < arr[0].length; j++) temp[i][j] = arr[i][j]; } private static void timSort(long[] arr) { Long[] temp = new Long[arr.length]; for (int i = 0; i < arr.length; i++) temp[i] = arr[i]; Arrays.sort(temp); for (int i = 0; i < arr.length; i++) arr[i] = temp[i]; } private static void timSort(long[] arr, Comparator<Long> c) { Long[] temp = new Long[arr.length]; for (int i = 0; i < arr.length; i++) temp[i] = arr[i]; Arrays.sort(temp, c); for (int i = 0; i < arr.length; i++) arr[i] = temp[i]; } private static void timSort(long[][] arr, Comparator<Long[]> c) { Long[][] temp = new Long[arr.length][arr[0].length]; for (int i = 0; i < arr.length; i++) for (int j = 0; j < arr[0].length; j++) temp[i][j] = arr[i][j]; Arrays.sort(temp, c); for (int i = 0; i < arr.length; i++) for (int j = 0; j < arr[0].length; j++) temp[i][j] = arr[i][j]; } } public long fastPow(long x, long y, long mod) { if (y == 0) return 1; if (y == 1) return x % mod; long temp = fastPow(x, y / 2, mod); long ans = (temp * temp) % mod; return (y % 2 == 1) ? (ans * (x % mod)) % mod : ans; } public long fastPow(long x, long y) { if (y == 0) return 1; if (y == 1) return x; long temp = fastPow(x, y / 2); long ans = (temp * temp); return (y % 2 == 1) ? (ans * x) : ans; } }
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 11
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
76d9df06a12136c9ff1be1c4e074c4e8
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.*; import java.awt.*; /*AUTHOR - SHIVAM GUPTA */ // U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE ,JUst keep faith in ur strengths .................................................. // ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219 // odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4 // FOR ANY ODD NO N : N,N-1,N-2,ALL ARE PAIRWISE COPRIME,THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS // two consecutive odds are always coprime to each other, two consecutive even have always gcd = 2 ; // Rectangle r = new Rectangle(int x , int y,int widht,int height) //Creates a rect. with bottom left cordinates as (x, y) and top right as ((x+width),(y+height)) //BY DEFAULT Priority Queue is MIN in nature in java //to use as max , just push with negative sign and change sign after removal // We can make a sieve of max size 1e7 .(no time or space issue) // In 1e7 starting nos we have about 66*1e4 prime nos // In 1e6 starting nos we have about 78,498 prime nos public class Main //public class Solution { static PrintWriter out; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out); } 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 int sumOfDigits(long n) { if( n< 0)return -1 ; int sum = 0; while( n > 0){ sum = sum + (int)( n %10) ; n /= 10 ; } return sum ; } ////////////////////////////////////////////////////////////////////////////////////////////////////// public static void swapArray(int[] arr , int start , int end) { while(start<end){ int temp = arr[start] ;arr[start] = arr[end]; arr[end] = temp; start++ ;end-- ;} } ////////////////////////////////////////////////////////////////////////////////// static long factorial(long a) { if(a== 0L || a==1L)return 1L ; return a*factorial(a-1L) ; } /////////////////////////////////////////////////////////////////////////////// public static int[][] rotate(int[][] input){ int n =input.length;int m = input[0].length ; int[][] output = new int [m][n]; for (int i=0; i<n; i++) for (int j=0;j<m; j++) output [j][n-1-i] = input[i][j]; return output; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// public static String reverse(String input) { StringBuilder str = new StringBuilder("") ; for(int i =input.length()-1 ; i >= 0 ; i-- ) { str.append(input.charAt(i)); } return str.toString() ; } /////////////////////////////////////////////////////////////////////////////////////////// public static int xorOfFirstN(int n) { if( n % 4 ==0)return n ; else if( n % 4 == 1)return 1 ; else if( n % 4 == 2)return n+1 ; else return 0 ; } ////////////////////////////////////////////////////////////////////////////////////////////// public static int gcd(int a, int b ) { if(b==0)return a ;else return gcd(b,a%b) ; } public static long gcd(long a, long b ) { if(b==0)return a ;else return gcd(b,a%b) ; } /////////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c ) { int temp = lcm(a,b) ;int ans = lcm(temp ,c) ;return ans ; } //////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a , int b ) { int gc = gcd(a,b);return (a/gc)*b ; } public static long lcm(long a , long b ) { long gc = gcd(a,b);return (a/gc)*b; } /////////////////////////////////////////////////////////////////////////////////////////// static boolean isPrime(long n) { if(n==1)return false ; for(long i = 2L; i*i <= n ;i++){ if(n% i ==0){return false; } } return true ; } static boolean isPrime(int n) { if(n==1)return false ; for(int i = 2; i*i <= n ;i++){ if(n% i ==0){return false ; } } return true ; } //////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// static int sieve = 1000000 ; static boolean[] prime = new boolean[sieve + 1] ; public static void sieveOfEratosthenes() { // FALSE == prime and 1 // TRUE == COMPOSITE // time complexity = 0(NlogLogN)== o(N) // gives prime nos bw 1 to N // size - 1e7(at max) for(int i = 4; i<= sieve ; i++) { prime[i] = true ; i++ ; } for(int p = 3; p*p <= sieve; p++) { if(prime[p] == false) { for(int i = p*p; i <= sieve; i += p) prime[i] = true; } p++ ; } } /////////////////////////////////////////////////////////////////////////////////// public static void sortD(int[] arr , int s , int e) { sort(arr ,s , e) ; int i =s ; int j = e ; while( i < j){ int temp = arr[i] ;arr[i] =arr[j] ; arr[j] = temp ; i++ ; j-- ;} } ///////////////////////////////////////////////////////////////////////////////////////// public static long countSubarraysSumToK(long[] arr ,long sum ) { HashMap<Long,Long> map = new HashMap<>() ; int n = arr.length ; long prefixsum = 0 ; long count = 0L ; for(int i = 0; i < n ; i++) { prefixsum = prefixsum + arr[i] ; if(sum == prefixsum)count = count+1 ; if(map.containsKey(prefixsum -sum))count = count + map.get(prefixsum -sum) ; if(map.containsKey(prefixsum )) map.put(prefixsum , map.get(prefixsum) +1 ); else map.put(prefixsum , 1L ); } return count ; } /////////////////////////////////////////////////////////////////////////////////////////////// // KMP ALGORITHM : TIME COMPL:O(N+M) // FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING //RETURN THE ARRAYLIST OF INDEXES // IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING public static ArrayList<Integer> kmpAlgorithm(String str , String pat) { ArrayList<Integer> list =new ArrayList<>(); int n = str.length() ; int m = pat.length() ; String q = pat + "#" + str ; int[] lps =new int[n+m+1] ; longestPefixSuffix(lps, q,(n+m+1)) ; for(int i =m+1 ; i < (n+m+1) ; i++ ) { if(lps[i] == m) { list.add(i-2*m) ; } } return list ; } public static void longestPefixSuffix(int[] lps ,String str , int n) { lps[0] = 0 ; for(int i = 1 ; i<= n-1; i++) { int l = lps[i-1] ; while( l > 0 && str.charAt(i) != str.charAt(l)) { l = lps[l-1] ; } if(str.charAt(i) == str.charAt(l)) {l++ ;} lps[i] = l ; } } /////////////////////////////////////////////////////////////////////////////////////////////////// // CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n // TOTIENT(N) = count of nos b/w 1 and n whose gcd with n is 1 // or n and the no will be coprime in nature //time : O(n*(log(logn))) public static void eulerTotientFunction(int[] arr ,int n ) { for(int i = 1; i <= n ;i++)arr[i] =i ; for(int i= 2 ; i<= n ;i++) { if(arr[i] == i) { arr[i] =i-1 ; for(int j =2*i ; j<= n ; j+= i ) { arr[j] = (arr[j]*(i-1))/i ; } } } } ///////////////////////////////////////////////////////////////////////////////////////////// public static long nCr(int n,int k) { long ans=1L; k=k>n-k?n-k:k; int j=1; for(;j<=k;j++,n--) { if(n%j==0) { ans*=n/j; }else if(ans%j==0) { ans=ans/j*n; }else { ans=(ans*n)/j; } } return ans; } /////////////////////////////////////////////////////////////////////////////////////////// public static ArrayList<Integer> allFactors(int n) { ArrayList<Integer> list = new ArrayList<>() ; for(int i = 1; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n)list.add(i) ; else{ list.add(i) ;list.add(n/i) ; } } } return list ; } public static ArrayList<Long> allFactors(long n) { ArrayList<Long> list = new ArrayList<>() ; for(long i = 1L; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) list.add(i) ; else{ list.add(i) ; list.add(n/i) ; } } } return list ; } //////////////////////////////////////////////////////////////////////////////////////////////////// static final int MAXN = 1000001; static int spf[] = new int[MAXN]; static void sieve() { for (int i=1; i<MAXN; i++) spf[i] = i; // ALL NOS HAVE SPF[i] =i AT START for (int i=4; i<MAXN; i+=2) //ALL EVEN NOS HAVE SPF[i] = 2 spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } static ArrayList<Integer> getPrimeFactorization(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() public static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } ///////////////////////////////////////////////////////////////////////////////////////// public static long knapsack(int[] weight,long value[],int maxWeight){ int n= value.length ; //dp[i] stores the profit with KnapSack capacity "i" long []dp = new long[maxWeight+1]; //initially profit with 0 to W KnapSack capacity is 0 Arrays.fill(dp, 0); // iterate through all items for(int i=0; i < n; i++) //traverse dp array from right to left for(int j = maxWeight; j >= weight[i]; j--) dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]); /*above line finds out maximum of dp[j](excluding ith element value) and val[i] + dp[j-wt[i]] (including ith element value and the profit with "KnapSack capacity - ith element weight") */ return dp[maxWeight]; } /////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// // to return max sum of any subarray in given array public static long kadanesAlgorithm(long[] arr) { if(arr.length == 0)return 0 ; long[] dp = new long[arr.length] ; dp[0] = arr[0] ;long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) dp[i] = dp[i-1] + arr[i] ; else dp[i] = arr[i] ; if(dp[i] > max)max = dp[i] ; } return max ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long kadanesAlgorithm(int[] arr) { if(arr.length == 0)return 0 ; long[] dp = new long[arr.length] ;dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) dp[i] = dp[i-1] + arr[i] ; else dp[i] = arr[i] ; if(dp[i] > max)max = dp[i] ; } return max ; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// public static long power(int a ,int b) { //time comp : o(logn) long x = (long)(a) ; long n = (long)(b) ; if(n==0)return 1 ;if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1)ans = ans *x ; n = n/2L ;x = x*x ; } return ans ; } public static long power(long a ,long b) { //time comp : o(logn) long x = (a) ;long n = (b) ; if(n==0)return 1L ;if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1)ans = ans *x ; n = n/2L ; x = x*x ; } return ans ; } ////////////////////////////////////////////////////////////////////////////////// /* lowerBound - finds largest element equal or less than value paased upperBound - finds smallest element equal or more than value passed if not present return -1; */ public static long lowerBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static int lowerBound(int[] arr,int k) { int ans=-1;int start=0;int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static long upperBound(long[] arr,long k) { long ans=-1;int start=0;int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } public static int upperBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } //////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// public static void printArray(int[] arr , int si ,int ei, int f) { for(int i = si ; i <= ei ; i++){ out.print(arr[i] +" ") ; } if(f==1)out.println() ; } public static void printArray(long[] arr , int si ,int ei, int f) { for(int i = si ; i <= ei ; i++){ out.print(arr[i] +" ") ; } if(f==1)out.println() ; } public static void printtwodArray(int[][] ans) { for(int i = 0; i< ans.length ; i++) { for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" "); out.println() ; } out.println() ; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// static long modPow(long a, long x, long p) { //calculates a^x mod p in logarithmic time. a = a % p ; if(a == 0)return 0L ; if(a == 1)return 1L ; if(x==0)return 1L; if(x==1)return a; long res = 1L; while(x > 0) { if( x % 2 != 0) { res = (res * a) % p; } a = (a * a) % p; x =x/2; } return res; } static long modInverse(long a, long p) { //calculates the modular multiplicative of a mod p. //(assuming p is prime). return modPow(a, p-2, p); } static long[] factorial = new long[1000001] ; static void modfac(long mod) { factorial[0]=1L ; factorial[1]=1L ; for(int i = 2; i<= 1000000 ;i++) { factorial[i] = factorial[i-1] *(long)(i) ; factorial[i] = factorial[i] % mod ; } } static long modBinomial(long n, long r, long p) { // calculates C(n,r) mod p (assuming p is prime). if(n < r) return 0L ; long num = factorial[(int)(n)] ; long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) % p ; long ans = num*(modInverse(den,p)) ; ans = ans % p ; return ans ; } static void update(int val , long[] bit ,int n) { for( ; val <= n ; val += (val &(-val)) ) { bit[val]++ ; } } static long query(int val , long[] bit , int n) { long ans = 0L; for( ; val >=1 ; val-=(val&(-val)) )ans += bit[val]; return ans ; } static int countSetBits(long n) { int count = 0; while (n > 0) { n = (n) & (n - 1L); count++; } return count; } static int abs(int x) { if(x<0)x=-x ; return x ; } static long abs(long x) { if(x<0)x=-x ; return x ; } //////////////////////////////////////////////////////////////////////////////////////////// // calculate total no of nos greater than or equal to key in sorted array arr static int bs(int[] arr, int s ,int e ,int key) { if( s> e)return 0 ; int mid = (s+e)/2 ; if(arr[mid] <key) return bs(arr ,mid+1,e , key) ; else {return bs(arr ,s ,mid-1, key) + e-mid+1;} } // static ArrayList<Integer>[] adj ; // static int mod= 1000000007 ; static class pair { int u; int v; public pair(int u,int v) { this.u = u ; this.v=v; } } static class Dsu { int n ;int[] par ; int[] size ; public Dsu(int n) { this.n = n ; par = new int[n] ; size = new int[n] ; for(int i = 0 ; i< n ;i++) { par[i] =i ;size[i] =1 ; } } // cheack if given element is root element of its set public boolean isRoot(int x) { return par[x] == x ; } // find root of given set public int findRoot(int x) { if(par[x] == x) { return par[x] ; } par[x] = findRoot(par[x]) ; //path compression return par[x] ; } public boolean unionSet(int a, int b) { int rootA = findRoot(a); int rootB=findRoot(b) ; if(rootA==rootB)return true ;//they are alraedy present in same set/connected already(in graph) if(size[rootA] > size[rootB]) { size[rootA] += size[rootB] ; par[rootB] =rootA ; } else{ size[rootB] += size[rootA] ; par[rootA] =rootB ; } return false ; // means we union both the sets now } } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// public static void solve() { FastReader scn = new FastReader() ; //DEBUGGING - // 1 - I/O - CHECK PRINTING OF NEXT LINE , READ INPUT , EXTRA LINE PRINT. //2-OVERFLOW ERROR. //3 -STATIC VARIABLE INITIALIZATION (INT MAINLIY) //4-DIVISION ERROR(FLOOR/CEIL) or DIVIDE BY ZERO //5-MOD -(MOD BY 1 OR 0 ) // DOUBLE LOOP/TRIPLE LOOP BREAK (SEE IF DO NOT BREAK ALL THE LOOPS IF U GET ANS EARLIER) //Scanner scn = new Scanner(System.in); //int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ; // product of first 11 prime nos is greater than 10 ^ 12; ArrayList<Integer> list = new ArrayList<>() ; ArrayList<Integer> listx = new ArrayList<>() ; ArrayList<Integer> listy = new ArrayList<>() ; HashMap<Integer,Integer> map = new HashMap<>() ; HashMap<Integer,Integer> mapx = new HashMap<>() ; HashMap<Integer,Integer> mapy = new HashMap<>() ; //HashMap<Point,Integer> point = new HashMap<>() ; Set<Integer> set = new HashSet<>() ; Set<Integer> setx = new HashSet<>() ; Set<Integer> sety = new HashSet<>() ; StringBuilder sb =new StringBuilder("") ; //Collections.sort(list);// Collections.reverse(list) ; //int bit =Integer.bitCount(n);// gives total no of set bits in n; // Arrays.sort(arr, new Comparator<Pair>() { // @Override // public int compare(Pair a, Pair b) { // if (a.first != b.first) { // return a.first - b.first; // for increasing order of first // } // return a.second - b.second ; //if first is same then sort on second basis // } // }); //if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ; //if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ; int testcase = 1; testcase = scn.nextInt() ; for(int testcases =1 ; testcases <= testcase ;testcases++) { int n= scn.nextInt() ;int m= scn.nextInt() ; long k = scn.nextLong();int q= scn.nextInt() ; int[][] arr = new int[q][2] ; for(int i = 0 ; i < q;i++){ arr[i][0] =scn.nextInt() ; arr[i][1] =scn.nextInt() ; } if(n==1 ||m== 1)out.println(k); else{ long ans =1L; HashSet<Integer> setr = new HashSet<>() ; HashSet<Integer> setc = new HashSet<>() ; for(int i =q-1 ;i>= 0;i--) { int r =arr[i][0] ;int c =arr[i][1] ; if(setr.contains(r) && setc.contains(c))continue ; // bot present else if(!setr.contains(r) && !setc.contains(c)){ // both absent ans = ans*k; ans = ans % 998244353 ; } else if(!setr.contains(r) && setc.contains(c)){// row absent col present if(setc.size() != m) { ans = ans*k; ans = ans % 998244353 ; } } else{// row present,col absent if(setr.size() != n) { ans = ans*k; ans = ans % 998244353 ; } } setr.add(r); setc.add(c) ; } out.println(ans) ; } //out.println("Case #" + testcases + ": " + ans ) ; //out.println("@") ; sb.delete(0 , sb.length()) ; list.clear() ;listx.clear() ;listy.clear() ; map.clear() ;mapx.clear() ;mapy.clear() ; set.clear() ;setx.clear() ;sety.clear() ; } // test case end loop out.flush() ; } // solve fn ends public static void main (String[] args) throws java.lang.Exception { solve() ; } } class Pair { int first ;int second ; public Pair(int x, int y) { this.first = x ;this.second = y ; } @Override public boolean equals(Object obj) { if(obj == this)return true ; if(obj == null)return false ; if(this.getClass() != obj.getClass()) return false ; Pair other = (Pair)(obj) ; if(this.first != other.first)return false ; if(this.second != other.second)return false ; return true ; } @Override public int hashCode() { return this.first^this.second ; } @Override public String toString() { String ans = "" ;ans += this.first ; ans += " "; ans += this.second ; return ans ; } }
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 11
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
d76b0ebd7df4329f5837df5b66c522ec
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.Arrays; import java.util.HashSet; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Random; import java.io.FileWriter; import java.io.PrintWriter; /* Solution Created: 17:49:08 22/02/2022 Custom Competitive programming helper. */ public class Main { public static void solve() { int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(), q = in.nextInt(); int[][] op = new int[q][2]; for(int i = 0; i<q; i++) op[i] = in.na(2); HashSet<Integer> usedX = new HashSet<Integer>(); HashSet<Integer> usedY = new HashSet<Integer>(); long ans = 1, mod = 998244353; for(int i = q-1; i>=0; i--) { int x = op[i][0], y = op[i][1]; boolean useful = false; boolean full = usedY.size() == m || usedX.size() == n; if(!usedX.contains(x) && !full) useful = true; if(!usedY.contains(y) && !full) useful = true; if(useful) ans = (ans*k)%mod; usedX.add(x); usedY.add(y); } out.println(ans); } public static void main(String[] args) { in = new Reader(); out = new Writer(); int t = in.nextInt(); while(t-->0) solve(); out.exit(); } static Reader in; static Writer out; static class Reader { static BufferedReader br; static StringTokenizer st; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String f){ try { this.br = new BufferedReader(new FileReader(f)); } catch (IOException e) { e.printStackTrace(); } } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] ns(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { ensureNext(); return Integer.parseInt(st.nextToken()); } public double nextDouble() { ensureNext(); return Double.parseDouble(st.nextToken()); } public Long nextLong() { ensureNext(); return Long.parseLong(st.nextToken()); } public String next() { ensureNext(); return st.nextToken(); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } private void ensureNext() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } } } static class Util{ private static Random random = new Random(); static long[] fact; public static void initFactorial(int n, long mod) { fact = new long[n+1]; fact[0] = 1; for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod; } public static long modInverse(long a, long MOD) { long[] gcdE = gcdExtended(a, MOD); if (gcdE[0] != 1) return -1; // Inverted doesn't exist long x = gcdE[1]; return (x % MOD + MOD) % MOD; } public static long[] gcdExtended(long p, long q) { if (q == 0) return new long[] { p, 1, 0 }; long[] vals = gcdExtended(q, p % q); long tmp = vals[2]; vals[2] = vals[1] - (p / q) * vals[2]; vals[1] = tmp; return vals; } public static long nCr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nCr(int n, int r) { return (fact[n]/fact[r])/fact[n-r]; } public static long nPr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nPr(int n, int r) { return fact[n]/fact[n-r]; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } static long pow(long x, long pow, long mod){ long res = 1; x = x % mod; if (x == 0) return 0; while (pow > 0){ if ((pow & 1) != 0) res = (res * x) % mod; pow >>= 1; x = (x * x) % mod; } return res; } public static int gcd(int a, int b) { int tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static long gcd(long a, long b) { long tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static int random(int min, int max) { return random.nextInt(max-min+1)+min; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } public static void reverse(int[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { int tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(int[] s) { reverse(s, 0, s.length-1); } public static void reverse(long[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { long tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(long[] s) { reverse(s, 0, s.length-1); } public static void reverse(float[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { float tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(float[] s) { reverse(s, 0, s.length-1); } public static void reverse(double[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { double tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(double[] s) { reverse(s, 0, s.length-1); } public static void reverse(char[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { char tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(char[] s) { reverse(s, 0, s.length-1); } public static <T> void reverse(T[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { T tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static <T> void reverse(T[] s) { reverse(s, 0, s.length-1); } public static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(float[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); float t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(double[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); double t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } public static <T> void shuffle(T[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); T t = s[i]; s[i] = s[j]; s[j] = t; } } public static void sortArray(int[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(long[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(float[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(double[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(char[] a) { shuffle(a); Arrays.sort(a); } public static <T extends Comparable<T>> void sortArray(T[] a) { Arrays.sort(a); } public static int[][] rotate90(int[][] a){ int n = a.length, m = a[0].length; int[][] ans = new int[m][n]; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j]; return ans; } public static char[][] rotate90(char[][] a){ int n = a.length, m = a[0].length; char[][] ans = new char[m][n]; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j]; return ans; } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public Writer(String f){ try { pw = new PrintWriter(new FileWriter(f)); } catch (IOException e) { e.printStackTrace(); } } public void yesNo(boolean condition) { println(condition?"YES":"NO"); } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { 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 11
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
c1fc2704c464db332e84dc31f620395c
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 { static long pow(long a , long b , long c) { if(b == 0) return 1; long ans = pow(a,b/2,c); if(b%2 == 0) return ans*ans%c; return ans*ans%c*a%c; } public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); //sc.nextLine(); while(t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int q = sc.nextInt(); int qu[][] = new int[q][2]; HashMap<Integer,Integer> x = new HashMap<Integer,Integer>(); HashMap<Integer,Integer> y = new HashMap<Integer,Integer>(); for(int i = 0 ; i < q ; i++) { qu[i][0] = sc.nextInt(); qu[i][1] = sc.nextInt(); } int tot = 0; long mod = 998244353; int xleft = n , yleft = m; for(int i = q-1 ; i >= 0 ; i--) { if(x.containsKey(qu[i][0])) x.replace(qu[i][0],x.get(qu[i][0])+1); else x.put(qu[i][0],1); if(y.containsKey(qu[i][1])) y.replace(qu[i][1],y.get(qu[i][1])+1); else y.put(qu[i][1],1); boolean xcov = false , ycov = false; if(x.get(qu[i][0]) > 1 || yleft == 0) xcov = true; if(y.get(qu[i][1]) > 1 || xleft == 0) ycov = true; if(x.get(qu[i][0]) == 1) xleft--; if(y.get(qu[i][1]) == 1) yleft--; if(xcov && ycov) continue; tot++; // x[qu[i][0]]; // y[qu[i][1]]; } System.out.println(pow(k,tot,mod)); } } }
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 11
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
1d4fb078923af700e2aab83934feb235
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 D1644 { public static void main(String[] args) throws IOException, FileNotFoundException { // Scanner in = new Scanner(new File("test.in")); Kattio in = new Kattio(); int T = in.nextInt(); while(T > 0){ int N = in.nextInt(); int M = in.nextInt(); int K = in.nextInt(); int Q = in.nextInt(); int[] x = new int[Q]; int[] y = new int[Q]; for(int i = 0; i < Q; i++){ x[i] = in.nextInt(); // to N y[i] = in.nextInt(); // to M } TreeSet<Integer> nx = new TreeSet<>(); TreeSet<Integer> ny = new TreeSet<>(); long ans = 1; long MOD = 998244353; for(int i = Q - 1; i >= 0; i--){ boolean works = false; if(!nx.contains(x[i])){ nx.add(x[i]); works = true; } if(!ny.contains(y[i])){ ny.add(y[i]); works = true; } if(works){ ans*=K; ans %= MOD; } if(nx.size() == N || ny.size() == M){ break; } } System.out.println(ans); T--; } } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(problemName + ".out"); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(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 11
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
4760ee2af304041b76c706c936ef892d
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
/* _oo0oo_ o8888888o 88" . "88 (| -_- |) 0\ = /0 ___/`---'\___ .' \\| |// '. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' |_/ | \ .-\__ '-' ___/-. / ___'. .' /--.--\ `. .'___ ."" '< `.___\_<|>_/___.' >' "". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `_. \_ __\ /__ _/ .-` / / =====`-.____`.___ \_____/___.-`___.-'===== `=---=' */ import java.util.*; import java.math.*; import java.io.*; import java.lang.Math.*; public class KickStart2020 { 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()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a, long b) { return a / gcd(a, b) * b; } public static class Pair implements Comparable<Pair> { public int index; public int value; public Pair(int index, int value) { this.index = index; this.value = value; } @Override public int compareTo(Pair other) { // multiplied to -1 as the author need descending sort order if(other.value < this.value) return 1; if(other.value > this.value) return -1; return 0; } @Override public String toString() { return this.index + " " + value; } } static boolean isPrime(long d) { if(d == 0) return true; if (d == 1) return false; for (int i = 2; i <= (long) Math.sqrt(d); i++) { if (d % i == 0) return false; } return true; } static void decimalTob(long n, int k , int arr[], int i) { arr[i] += (n % k); n /= k; if(n > 0) { decimalTob(n, k, arr, i + 1); } } static long powermod(long x, long y, long mod) { if(y == 0) return 1; long value = powermod(x, y / 2, mod); if(y % 2 == 0) return (value * value) % mod; return (value * (value * x) % mod) % mod; } static long power(long x, long y) { if(y == 0) return 1; long value = power(x, y / 2); if(y % 2 == 0) return (value * value); return value * value * x; } static int bS(int l, int r, int find, int arr[]) { if(r < l) return l - 1; int mid = (l + r) / 2; if(arr[mid] <= find) return bS(mid + 1, r, find, arr); return bS(l, mid - 1, find, arr); } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); outerloop: while(t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int q = sc.nextInt(); int arr[][] = new int[q][2]; HashSet<Integer> row = new HashSet<>(); HashSet<Integer> col = new HashSet<>(); for(int i = 0; i < q; i++) { arr[i][0] = sc.nextInt(); arr[i][1] = sc.nextInt(); } long mod = 998244353; long sum = 1; for(int i = q - 1; i >= 0; i--) { int u = arr[i][0]; int v = arr[i][1]; if(row.contains(u) && col.contains(v)) continue; if(col.size() == m) continue; if(row.size() == n) continue; sum *= k; sum %= mod; row.add(u); col.add(v); } out.println(sum); } 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 11
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
54aeec279b480f37ec428f310da60da3
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 Cross { static int mod = 998244353; public static void main(String[] args) throws Exception { FastIO in = new FastIO(); int t = in.nextInt(); for (int tc=0; tc<t; tc++) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int q = in.nextInt(); HashSet<Integer> rows = new HashSet<Integer>(); HashSet<Integer> cols = new HashSet<Integer>(); Pair[] ops = new Pair[q]; for (int i=0; i<q; i++) { ops[i] = new Pair(in.nextInt(), in.nextInt()); } int power = 0; for (int i=q-1; i>=0; i--) { int x = ops[i].x; int y = ops[i].y; if ((!rows.contains(x) || !cols.contains(y)) && (cols.size()<m && rows.size()<n)) { power++; } rows.add(x); cols.add(y); } // System.out.println(power); long ans = 1; for (int i=0; i<power; i++) { ans*=k; ans%=mod; } System.out.println(ans); } } static class Pair { int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } } static class FastIO { BufferedReader br; StringTokenizer st; public FastIO() throws IOException { br = new BufferedReader( new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { String str = br.readLine(); 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 11
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
4d1c560e20bfd6f1f89c5ea37f8d34b2
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
/* 2 1 1 3 2 1 1 1 1 2 2 2 3 2 1 1 1 2 2 1 4 4 3 5 1 1 2 1 2 2 2 3 2 4 If a cross a covers a cross b, then the color of cross a does not matter Likewise, if the row of a cross x and the column of a cross x are covered, the color of cross x does not matter If the row of a cross and the column of a cross are contained in a set of later crosses, then the color of that cross does not matter. Output k^(q - number of these crosses) */ import java.util.*; import java.io.*; public class Main{ public static long mod = 998244353; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int nc = Integer.parseInt(br.readLine()); for(int cc = 0; cc < nc; cc++){ StringTokenizer details = new StringTokenizer(br.readLine()); long n = Long.parseLong(details.nextToken()); long m = Long.parseLong(details.nextToken()); long k = Long.parseLong(details.nextToken()); int q = Integer.parseInt(details.nextToken()); long[][] coords = new long[q][2]; HashMap<Long, Integer> lgx = new HashMap<Long, Integer>(); HashMap<Long, Integer> lgy = new HashMap<Long, Integer>(); int largestX = 1000000000; //earliest visible row int largestY = 1000000000; //earliest visible col for(int a = 0; a < q; a++){ StringTokenizer st = new StringTokenizer(br.readLine()); coords[a][0] = Long.parseLong(st.nextToken()); coords[a][1] = Long.parseLong(st.nextToken()); lgx.put(coords[a][0], a); lgy.put(coords[a][1], a); } for(long item : lgx.keySet()) largestX = Math.min(largestX, lgx.get(item)); for(long item : lgy.keySet()) largestY = Math.min(largestY, lgy.get(item)); //System.out.println(lgx + " smallest is " + largestX); //System.out.println(lgy + " smallest is " + largestY); long excluded = 0; for(int a = 0; a < q; a++){ //if entire row and entire column are covered then this cross does not matter boolean rowc = false; if(lgx.get(coords[a][0]) > a) rowc = true; if(lgy.size() == m && largestY > a) rowc = true; boolean colc = false; if(lgy.get(coords[a][1]) > a) colc = true; if(lgx.size() == n && largestX > a) colc = true; //System.out.println(a + " " + rowc + " " + colc); if(rowc && colc) excluded++; } //System.out.println(excluded); System.out.println(pow(k, (long) q - excluded)); } br.close(); } public static long pow(long n, long pw){ if(pw == 0) return 1L; long half = pow(n, pw/2); if(pw % 2 == 0) return (half * half) % mod; return (((half * half) % mod) * n) % mod; } }
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 11
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
f471041cb7ef59e045951300fba7a043
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 Practice { // static final long mod=7420738134811L; static int mod=998244353;//1000000007; static int size=(int)1e7+1; static FastReader sc=new FastReader(System.in); // static Reader sc=new Reader(); // static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); static long[] factorialNumInverse; static long[] naturalNumInverse; static int[] sp; static long[] fact; static ArrayList<Integer> pr; public static void main(String[] args) throws IOException, CloneNotSupportedException { // System.setIn(new FileInputStream("input.txt")); // System.setOut(new PrintStream("output.txt")); // factorial(mod); // InverseofNumber(mod); // InverseofFactorial(mod); // make_seive(); int t=1; t=sc.nextInt(); for(int i=1;i<=t;i++) solve(i); out.close(); out.flush(); // System.out.flush(); // System.exit(0); } static void solve(int CASENO) throws IOException, CloneNotSupportedException { int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(),q=sc.nextInt(); HashMap<Integer,Integer> xf=new HashMap<Integer, Integer>(); HashMap<Integer,Integer> yf=new HashMap<Integer, Integer>(); int ar[][]=new int[q][2]; for(int i=0;i<q;i++) { ar[i][0]=sc.nextInt(); ar[i][1]=sc.nextInt(); } int cx=0,cy=0; long ans=1; for(int i=q-1;i>=0;i--) { int r=ar[i][0],c=ar[i][1]; if(cx==n || cy==m) break; if(xf.getOrDefault(r, 0)==0 || yf.getOrDefault(c, 0)==0) { ans=(ans*k)%mod; if(xf.getOrDefault(r, 0)==0) { xf.put(r, xf.getOrDefault(r, 0)+1); cx++; } if(yf.getOrDefault(c, 0)==0) { yf.put(c, yf.getOrDefault(r, 0)+1); cy++; } } } out.println(ans); } static class Pair implements Cloneable, Comparable<Pair> { int x,y; Pair(int a,int b) { this.x=a; this.y=b; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { Pair p=(Pair)obj; return p.x==this.x && p.y==this.y; } return false; } @Override public int hashCode() { return (int)Math.abs(x)+500*Math.abs(y); } @Override public String toString() { return "("+x+" "+y+")"; } @Override protected Pair clone() throws CloneNotSupportedException { return new Pair(this.x,this.y); } @Override public int compareTo(Pair a) { long t=(this.x-a.x); if(t!=0) return t>0?1:-1; else return (int)(this.y-a.y); } public void swap() { this.y=this.y+this.x; this.x=this.y-this.x; this.y=this.y-this.x; } } static class Tuple implements Cloneable, Comparable<Tuple> { int x,y,z; Tuple(int a,int b,int c) { this.x=a; this.y=b; this.z=c; } public boolean equals(Object obj) { if(obj instanceof Tuple) { Tuple p=(Tuple)obj; return p.x==this.x && p.y==this.y && p.z==this.z; } return false; } @Override public int hashCode() { return (this.x+501*this.y); } @Override public String toString() { return "("+x+","+y+" "+z+")"; } @Override protected Tuple clone() throws CloneNotSupportedException { return new Tuple(this.x,this.y,this.z); } @Override public int compareTo(Tuple a) { int x=this.x-a.x; if(x!=0) return x; int X= this.y-a.y; return X; } } static void arraySort(int arr[]) { ArrayList<Integer> a=new ArrayList<Integer>(); for (int i = 0; i < arr.length; i++) { a.add(arr[i]); } Collections.sort(a); // Collections.sort(a,Comparator.reverseOrder()); for (int i = 0; i < arr.length; i++) { arr[i]=a.get(i); } } static void arraySort(long arr[]) { ArrayList<Long> a=new ArrayList<Long>(); for (int i = 0; i < arr.length; i++) { a.add(arr[i]); } // Collections.sort(a); Collections.sort(a,Comparator.reverseOrder()); for (int i = 0; i < arr.length; i++) { arr[i]=a.get(i); } } static HashMap<Integer,Integer> primeFactors(int n) { HashMap<Integer,Integer> ans=new HashMap<Integer, Integer>(); while((n&1)==0) { ans.put(2,ans.getOrDefault(2, 0)+1); n=n>>1; } for(int i=3;i*i<=n;i+=2) { while(n%i==0) { ans.put(i,ans.getOrDefault(i, 0)+1); n=n/i; } } if(n!=1) { ans.put(n,ans.getOrDefault(n, 0)+1); } return ans; } static ArrayList<Integer> findAllFactors(int n) { ArrayList<Integer> ans=new ArrayList<Integer>(); for(int i=1;i*i<=n;i++) { ans.add(i); if(n!=i*i) ans.add(n/i); } return ans; } static class sparseTable{ int n; int[][]dp; int log2[]; int P; void buildTable(int[] arr) { n=arr.length; P=(int)Math.floor(Math.log(n)/Math.log(2)); log2=new int[n+1]; log2[0]=log2[1]=0; for(int i=2;i<=n;i++) log2[i]=log2[i/2]+1; dp=new int[P+1][n]; for(int i=0;i<n;i++) dp[0][i]=arr[i]; for(int p=1;p<=P;p++) { for(int i=0;i+(1<<p)<=n;i++) { int left=dp[p-1][i]; int right=dp[p-1][i+(1<<(p-1))]; dp[p][i]=gcd(left, right); } } } int query(int l,int r) { int len=r-l+1; int p=(int)Math.floor(log2[len]); int left=dp[p][l]; int right=dp[p][r-(1<<p)+1]; return gcd(left,right); } } static void make_seive() { sp=new int[size]; pr=new ArrayList<Integer>(); for (int i=2; i<size; ++i) { if (sp[i] == 0) { sp[i] = i; pr.add(i); } for (int j=0; j<(int)pr.size() && pr.get(j)<=sp[i] && i*pr.get(j)<size; ++j) sp[i * pr.get(j)] = pr.get(j); } } public static void InverseofNumber(int p) { naturalNumInverse=new long[size]; naturalNumInverse[0] = naturalNumInverse[1] = 1; for(int i = 2; i < size; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p; } // Function to precompute inverse of factorials public static void InverseofFactorial(int p) { factorialNumInverse=new long[size]; factorialNumInverse[0] = factorialNumInverse[1] = 1; // pre-compute inverse of natural numbers for(int i = 2; i < size; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p; } // Function to calculate factorial of 1 to 200001 public static void factorial(int p) { fact=new long[size]; fact[0] = 1; for(int i = 1; i < size; i++) fact[i] = (fact[i - 1] * (long)i) % p; } // Function to return nCr % p in O(1) time public static long Binomial(int N, int R) { if(R<0) return 1; // n C r = n!*inverse(r!)*inverse((n-r)!) long ans = ((fact[N] * factorialNumInverse[R]) % mod * factorialNumInverse[N - R]) % mod; return ans; } static int findXOR(int x) //from 0 to x { if(x<0) return 0; if(x%4==0) return x; if(x%4==1) return 1; if(x%4==2) return x+1; return 0; } static boolean isPrime(long x) { if(x==1) return false; if(x<=3) return true; if(x%2==0 || x%3==0) return false; for(int i=5;i<=Math.sqrt(x);i+=2) if(x%i==0) return false; return true; } static long gcd(long a,long b) { return (b==0)?a:gcd(b,a%b); } static int gcd(int a,int b) { return (b==0)?a:gcd(b,a%b); } static class Node { int vertex,ind; ArrayList<Node> adj; Node(int ver) { vertex=ver; ind=0; adj=new ArrayList<Node>(); } @Override public String toString() { return vertex+" "; } } static class Edge { Node to; int cost; Edge(Node t,int c) { this.to=t; this.cost=c; } @Override public String toString() { return "("+to.vertex+","+cost+") "; } } static long power(long x, long y) { if(x<=0) return 1; long res = 1; x = x % mod; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % mod; y = y >> 1; // y = y/2 x = (x * x) % mod; } return res%mod; } static long binomialCoeff(long n, long k) { if(n<k) return 0; long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (long i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } static 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(); } 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; } public void printarray(int arr[]) { for (int i = 0; i < arr.length; i++) System.out.print(arr[i]+" "); System.out.println(); } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { 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(); } public void printarray(int arr[]) { for (int i = 0; i < arr.length; i++) System.out.print(arr[i]+" "); System.out.println(); } } }
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 11
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
8cde40b6cad5cbd71d2ab79908c7c646
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 Main { void solve() { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int q = in.nextInt(); HashSet<Integer> x = new HashSet<>(); HashSet<Integer> y = new HashSet<>(); int[][] query = new int[q][]; for (int i = 0; i < q; i++) { query[i] = array(2, 1); } mod = 998244353; int count = 0; for (int i = q - 1; i >= 0; i--) { int xi = query[i][0]; int yi = query[i][1]; if (x.contains(xi) && y.contains(yi))continue; if (x.size() == n || y.size() == m)continue; count++; x.add(xi); y.add(yi); } println(k + " " + count); long res = cal(k, count); // println(cal(22034, 51)); out.append(res + endl); } // a = k , b = count long cal(long a, long b) { long res = 1; while (b > 0) { if (b % 2 == 1) { res = (res * a) % mod; } a = (a * a) % mod; b = (b >> 1); } return res; } public static void main (String[] args) { // It happens - Syed Mizbahuddin Main sol = new Main(); int t = 1; t = in.nextInt(); while (t-- != 0) { sol.solve(); } System.out.print(out); } <T> void println(T[] s) { if (err == null)return; err.println(Arrays.toString(s)); } <T> void println(T s) { if (err == null)return; err.println(s); } void println(int s) { if (err == null)return; err.println(s); } void println(int[] a) { if (err == null)return; println(Arrays.toString(a)); } void println(long[] a) { if (err == null)return; println(Arrays.toString(a)); } int[] array(int n, int x) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } return a; } long[] array(int n, long x) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.nextLong(); } return a; } int[] array1(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } return a; } int max(int[] a) { int max = a[0]; for (int i = 0; i < a.length; i++)max = Math.max(max, a[i]); return max; } int min(int[] a) { int min = a[0]; for (int i = 0; i < a.length; i++)min = Math.min(min, a[i]); return min; } int count(int[] a, int x) { int count = 0; for (int i = 0; i < a.length; i++)if (x == a[i])count++; return count; } void printArray(int[] a) { for (int ele : a)out.append(ele + " "); out.append("\n"); } void printArray(long[] a) { for (long ele : a)out.append(ele + " "); out.append("\n"); } static { try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); err = new PrintStream(new FileOutputStream("error.txt")); } catch (Exception e) {} } static FastReader in; static StringBuilder out; static PrintStream err; static String yes , no , endl; final int MAX; final int MIN; int mod ; Main() { in = new FastReader(); out = new StringBuilder(); MAX = Integer.MAX_VALUE; MIN = Integer.MIN_VALUE; mod = (int)1e9 + 7; yes = "YES\n"; no = "NO\n"; endl = "\n"; } 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 Pair implements Comparable<Pair> { int first , second; Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair b) { return this.first - b.first; } public String toString() { String s = "{ " + Integer.toString(first) + " , " + Integer.toString(second) + " }"; return s; } } }
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 11
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
38bc6b58c249c922a524bfe336783106
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 new1{ static long mod = 998244353; public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } public static void main(String[] args) throws IOException{ BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); FastReader s = new FastReader(); int t = s.nextInt(); for(int z = 0; z < t; z++) { int n = s.nextInt(); int m = s.nextInt(); int k = s.nextInt(); int q = s.nextInt(); int[][] arr = new int[q][2]; for(int i = 0; i < q; i++) { int x = s.nextInt(); int y = s.nextInt(); arr[i][0] = x; arr[i][1] = y; } Set<Integer> row = new HashSet<Integer>(); Set<Integer> col = new HashSet<Integer>(); long ans = 1L; for(int i = arr.length - 1; i >= 0; i--) { int r = arr[i][0]; int c = arr[i][1]; if(row.contains(r) && col.contains(c)) continue; ans = (ans * (k + 0L)) % mod; row.add(r); col.add(c); //System.out.println(k + " " + r + " " + c + " " + row.toString() + " " + col.toString()); if(row.size() == n || col.size() == m) break; } System.out.println(ans); } output.flush(); } } 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(); } public 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 11
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
cf9f6583c57d1bac751c733bd8a76812
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.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class E123D { static StringBuffer ans1 = new StringBuffer(""); static FastScanner sc = new FastScanner(); static PrintWriter printWriter = new PrintWriter(System.out); public static void solve(int n, int m, int k, int q, int[][] ops) { Set<Integer> rows = new HashSet<>(); Set<Integer> cols = new HashSet<>(); int count = 0; for(int i = q - 1; i >= 0; i--) { int[] op = ops[i]; int x = op[0] - 1, y = op[1] - 1; // printWriter.println("x " + x + " y " + y ); if(rows.contains(x) && cols.contains(y)) continue; if(rows.size() == n || cols.size() == m) continue; rows.add(x); cols.add(y); count++; } long res = 1; // printWriter.println("count " + count); while(count-- > 0) { res *= k; res %= 998_244_353; } printWriter.println(res); } public static void main(String[] args) { 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(); int[][] ops = new int[q][2]; for(int i = 0; i < q; i++) { ops[i][0] = sc.nextInt(); ops[i][1] = sc.nextInt(); } solve(n, m, k, q, ops); } printWriter.flush(); } /***************************************************************** ******************** DO NOT READ AFTER THIS LINE ***************** *****************************************************************/ 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[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] read2dArray(int n, int m) { int arr[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextInt(); } } return arr; } ArrayList<Integer> readArrayList(int n) { ArrayList<Integer> arr = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int a = nextInt(); arr.add(a); } return arr; } 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 11
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
7540c112f0567c53e761830041ca9c94
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.*; public class cf { static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException, InterruptedException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); int mod = 998244353; while (t-- > 0) { int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt(), q = sc.nextInt(); pair[] arr = new pair[q]; for (int i = 0; i < arr.length; i++) { arr[i] = new pair(sc.nextInt(), sc.nextInt()); } boolean[] row = new boolean[n]; boolean[] col = new boolean[m]; long ans = 1; int r = 0, c = 0; for (int i = arr.length - 1; i >= 0; i--) { if (r != n && c != m) { if (!row[arr[i].x - 1] && !col[arr[i].y - 1]) { ans = (ans * k) % mod; row[arr[i].x - 1] = true; col[arr[i].y - 1] = true; r++; c++; } else if (!row[arr[i].x - 1]) { ans = (ans * k) % mod; row[arr[i].x - 1] = true; r++; } else if (!col[arr[i].y - 1]) { ans = (ans * k) % mod; col[arr[i].y - 1] = true; c++; } } // pw.println(Arrays.toString(row)); // pw.println(Arrays.toString(col)); } pw.println(ans); } pw.close(); } public static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) return this.z - other.z; return this.y - other.y; } else { return this.x - other.x; } } } public static class pair implements Comparable<pair> { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Integer(x).hashCode() * 31 + new Integer(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["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 11
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
9f10b4d75caad656fdb5af27933c64e3
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 { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); private static StringTokenizer st; private static long MOD = 998244353; public static void main(String[] args) throws IOException { st = new StringTokenizer(reader.readLine()); int T = Integer.parseInt(st.nextToken()); for (int t = 0; t < T; t++) { st = new StringTokenizer(reader.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[] x = new int[q]; int[] y = new int[q]; for (int i = 0; i < q; i++) { st = new StringTokenizer(reader.readLine()); x[i] = Integer.parseInt(st.nextToken()); y[i] = Integer.parseInt(st.nextToken()); } Set<Integer> rows = new HashSet<>(); Set<Integer> columns = new HashSet<>(); long sets = 0; for (int i = q - 1; i >= 0; i--) { if (rows.size() == n || columns.size() == m) { break; } if (!rows.contains(x[i]) || !columns.contains(y[i])) { sets++; } rows.add(x[i]); columns.add(y[i]); } writer.write(Long.toString(power(k, sets, MOD))); writer.newLine(); } writer.flush(); } public static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) != 0) { res = (res * x) % p; } y = y >> 1; x = (x * x) % p; } return res; } }
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 11
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
92ffd3ddc2fee5dbdb70d73074afd597
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Khater */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); DCrossColoring solver = new DCrossColoring(); solver.solve(1, in, out); out.close(); } static class DCrossColoring { public void solve(int testNumber, Scanner sc, PrintWriter pw) { int t = 1; t = sc.nextInt(); long mod = 998244353; while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); long k = sc.nextInt(); int q = sc.nextInt(); int[][] queries = new int[q][2]; for (int i = 0; i < q; i++) { queries[i][0] = sc.nextInt() - 1; queries[i][1] = sc.nextInt() - 1; } long ans = 1; HashSet<Integer> cols = new HashSet<>(); HashSet<Integer> rows = new HashSet<>(); for (int i = q - 1; i >= 0; i--) { int x = queries[i][0]; int y = queries[i][1]; int sum = (cols.contains(y) ? 0 : n - rows.size()) + (rows.contains(x) ? 0 : m - cols.size()); if (sum > 0) { ans *= k; ans %= mod; } rows.add(x); cols.add(y); } pw.println(ans); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(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 11
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
96e186d691fe562faa70643aaebb7099
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 class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; byte[] bb = new byte[1 << 15]; int i, n; byte getc() { if (i == n) { i = n = 0; try { n = in.read(bb); } catch (IOException e) {} } return i < n ? bb[i++] : 0; } int nextInt() { byte c = 0; while (c <= ' ') c = getc(); boolean negative = false; if (c == '-') { negative = true; c = getc(); } int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); } if (negative) { a = -a; } return a; } long nextLong() { byte c = 0; while (c <= ' ') c = getc(); long a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); } return a; } } public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int T = in.nextInt(); int[] X = new int[200200]; int[] Y = new int[200200]; boolean[] rows = new boolean[200200]; boolean[] columns = new boolean[200200]; final long REM = 998244353L; for (int ts=1; ts<=T; ts++) { int N = in.nextInt(); int M = in.nextInt(); long K = in.nextLong(); int Q = in.nextInt(); for (int i=1; i<=Q; i++) { X[i] = in.nextInt(); Y[i] = in.nextInt(); } /*for (int i=1; i<=N; i++) { rows[i] = false; } for (int i=1; i<=M; i++) { columns[i] = false; }*/ int row_count = 0; int col_count = 0; long ans = 1L; for (int i=Q; i>=1; i--) { if (row_count == N || col_count == M) { continue; } if ((!rows[X[i]]) || (!columns[Y[i]])) { ans = (ans * K) % REM; } if (!rows[X[i]]) { rows[X[i]] = true; row_count++; } if (!columns[Y[i]]) { col_count++; columns[Y[i]] = true; } } for (int i=1; i<=Q; i++) { rows[X[i]] = false; columns[Y[i]] = false; } out.write(ans + "\n"); } //in.close(); 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 11
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
6fe65ec0e4be66ee98dea633a6007e25
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) if(factors[i]==0) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { factors[p] = p; ar.add(p); } } } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort2(char ar[]) { int n = ar.length; ArrayList<Character> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static class SegTree { long tree[]; long lz[]; long r; long combine(long a, long b){ return Math.min(a,b); } void build(long a[], int v, int tl, int tr) { if (tl == tr) { tree[v] = a[tl]; } else { int tm = (tl + tr) / 2; build(a, v*2, tl, tm); build(a, v*2+1, tm+1, tr); tree[v] = combine(tree[2*v], tree[2*v+1]); } } void pointUpdate(int v, int tl, int tr, int pos, long val) { if(tl>pos||tr<pos) return; if(tl==pos&&tr==pos){ tree[v] = val; return; } int tm = ((tl + tr) >> 1); pointUpdate(v*2, tl, tm, pos, val); pointUpdate(v*2+1, tm+1, tr, pos, val); tree[v] = combine(tree[2*v],tree[2*v+1]); } // void push(int v, int tl, int tr){ // if(tl==tr){ // lz[v] = 0; // return; // } // tree[2*v] += lz[v]; // tree[2*v+1] += lz[v]; // lz[2*v] += lz[v]; // lz[2*v+1] += lz[v]; // lz[v] = 0; // } // void rangeUpdate(int v, int tl, int tr, int l, int r, long val) { // if(tl>r||tr<l) // return; // push(v, tl, tr); // if(tl>=l&&tr<=r){ // tree[v] += val; // lz[v] += val; // return; // } // int tm = ((tl + tr) >> 1); // rangeUpdate(v*2, tl, tm, l, r, val); // rangeUpdate(v*2+1, tm+1, tr, l, r, val); // tree[v] = combine(tree[2*v],tree[2*v+1]); // } long get(int v, int tl, int tr, int l, int r, long val) { if(l>tr||r<tl||tree[v]>val){ return 0; } if (tl == tr) { tree[v] = Integer.MAX_VALUE; return 1; } int tm = ((tl + tr) >> 1); long al = get(2*v, tl, tm, l, r, val); long ar = get(2*v+1, tm+1, tr, l, r, val); tree[v] = combine(tree[2*v],tree[2*v+1]); return al+ar; } } static class BIT{ int n; long tree[]; long operate(long el, long val){ return el+val; } void update(int x, long val){ for(;x<n;x+=(x&(-x))){ tree[x] = operate(tree[x], val); } } long get(int x){ long sum = 0; for(;x>0;x-=(x&(-x))){ sum = operate(sum, tree[x]); } return sum; } } static int parent[]; static int rank[]; static long m = 0; static int find_set(int v) { if (v == parent[v]) return v; return find_set(parent[v]); } static void make_set(int v) { parent[v] = v; rank[v] = 1; } static void union_sets(int a, int b) { a = find_set(a); b = find_set(b); if (a != b) { if (rank[a] < rank[b]){ int tmp = a; a = b; b = tmp; } parent[b] = a; // if (rank[a] == rank[b]) // rank[a]++; rank[a] += rank[b]; max1 = Math.max(max1,rank[a]); } } static int parent1[]; static int rank1[]; static int find_set1(int v) { if (v == parent1[v]) return v; return find_set1(parent1[v]); } static void make_set1(int v) { parent1[v] = v; rank1[v] = 1; } static void union_sets1(int a, int b) { a = find_set1(a); b = find_set1(b); if (a != b) { if (rank1[a] < rank1[b]){ int tmp = a; a = b; b = tmp; } parent1[b] = a; // if (rank1[a] == rank1[b]) // rank1[a]++; rank1[a] += rank1[b]; } } static long max1 = 0; static int count = 0; static int count1 = 0; static boolean possible; public static void solve(InputReader sc, PrintWriter pw){ int i, j = 0; long mod = 998244353; // int factors[] = new int[1000001]; // ArrayList<Integer> ar = new ArrayList<>(); // sieveOfEratosthenes(1000000, factors, ar); // HashSet<Integer> set = new HashSet<>(); // for(int x:ar){ // set.add(x); // } // int t = 1; int t = sc.nextInt(); u: while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int q = sc.nextInt(); int a[] = new int[q]; int b[] = new int[q]; for(i=0;i<q;i++){ a[i] = sc.nextInt(); b[i] = sc.nextInt(); } HashSet<Integer> set1 = new HashSet<>(); HashSet<Integer> set2 = new HashSet<>(); long val = 1; for(i=q-1;i>=0;i--){ if(set1.contains(a[i])&&set2.contains(b[i])) continue; set1.add(a[i]); set2.add(b[i]); val *= k; val %= mod; if(set1.size()==n||set2.size()==m) break; } pw.println(val); } } static void KMPSearch(char pat[], char txt[], long pres[]){ int M = pat.length; int N = txt.length; int lps[] = new int[M]; int j = 0; computeLPSArray(pat, M, lps); int i = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { pres[i-1] = 1; j = lps[j - 1]; } else if (i < N && pat[j] != txt[i]) { if (j != 0) j = lps[j - 1]; else i = i + 1; } } } static void computeLPSArray(char pat[], int M, int lps[]) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; i++; } } } } static long[][] matrixMult(long a[][], long b[][], long mod){ int n = a.length; int m = a[0].length; int p = b[0].length; long c[][] = new long[n][p]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ for(int k=0;k<p;k++){ c[i][k] += a[i][j]*b[j][k]; c[i][k] %= mod; } } } return c; } static long[][] exp(long mat[][], long b, long mod){ if(b==0){ int n = mat.length; long res[][] = new long[n][n]; for(int i=0;i<n;i++){ res[i][i] = 1; } return res; } long half[][] = exp(mat, b/2, mod); long res[][] = matrixMult(half, half, mod); if(b%2==1){ res = matrixMult(res, mat, mod); } return res; } static void countPrimeFactors(int num, int a[], HashMap<Integer,Integer> pos){ for(int i=2;i*i<num;i++){ if(num%i==0){ int y = pos.get(i); while(num%i==0){ a[y]++; num/=i; } } } if(num>1){ int y = pos.get(num); a[y]++; } } static void assignAnc(ArrayList<Integer> ar[], int depth[], int sz[], int par[][] ,int curr, int parent, int d){ depth[curr] = d; sz[curr] = 1; par[curr][0] = parent; for(int v:ar[curr]){ if(parent==v) continue; assignAnc(ar, depth, sz, par, v, curr, d+1); sz[curr] += sz[v]; } } static int findLCA(int a, int b, int par[][], int depth[]){ if(depth[a]>depth[b]){ a = a^b; b = a^b; a = a^b; } int diff = depth[b] - depth[a]; for(int i=19;i>=0;i--){ if((diff&(1<<i))>0){ b = par[b][i]; } } if(a==b) return a; for(int i=19;i>=0;i--){ if(par[b][i]!=par[a][i]){ b = par[b][i]; a = par[a][i]; } } return par[a][0]; } static void formArrayForBinaryLifting(int n, int par[][]){ for(int j=1;j<20;j++){ for(int i=0;i<n;i++){ if(par[i][j-1]==-1) continue; par[i][j] = par[par[i][j-1]][j-1]; } } } static long lcm(int a, int b){ return a*b/gcd(a,b); } static class CustomPair { long a[]; CustomPair(long a[]) { this.a = a; } } static class Pair1 implements Comparable<Pair1> { long a; long b; Pair1(long a, long b) { this.a = a; this.b = b; } public int compareTo(Pair1 p) { if(a!=p.a) return (a<p.a?-1:1); return (b<p.b?-1:1); } } static class Pair implements Comparable<Pair> { int a; int b; int c; Pair(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int compareTo(Pair p) { if(b!=p.b) return (b-p.b); return (a-p.a); } } static class Pair2 implements Comparable<Pair2> { int a; int b; int c; Pair2(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int compareTo(Pair2 p) { return a-p.a; } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 9992768); 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 11
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
ba8eb1387d95b98049a270fbb265365e
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.LinkedList; import java.util.StringTokenizer; public class D { public static FastScanner s = new FastScanner(); public static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int lines = s.nextInt(); for (int i = 0; i < lines; i += 1) { solve(s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt()); } out.close(); } static long mod = 998244353; public static void solve(int h, int w, int c, int q) { LinkedList<int[]> p = new LinkedList<>(); for (int i = 0; i < q; i++) { p.add(new int[]{s.nextInt() - 1, s.nextInt() - 1}); } int[] t; boolean[] row = new boolean[w]; boolean[] col = new boolean[h]; int rc = 0; int cc = 0; long count = 1; for (int i = 0; i < q; i++) { t = p.pollLast(); if (!col[t[0]] | !row[t[1]]) if (rc < w && cc < h) count = (count * c) % mod; if (!col[t[0]]) cc++; if (!row[t[1]]) rc++; col[t[0]] = true; row[t[1]] = true; } out.println(count); } static class FastScanner {//copied from secondthread 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 11
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
da35fd1f6576253cffcb7907b81b7a62
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); DCrossColoring solver = new DCrossColoring(); solver.solve(1, in, out); out.close(); } static class DCrossColoring { public void solve(int testNumber, FastReader in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int m = in.nextInt(); long k = in.nextInt(); int q = in.nextInt(); int[][] a = new int[q][2]; in.readArr(a); boolean[] row = new boolean[n + 2]; boolean[] col = new boolean[m + 2]; long num = 0; int rowNum = 0; int colNum = 0; for (int i = q - 1; i >= 0; i--) { if (row[a[i][0]] && col[a[i][1]]) { continue; } num++; if (!row[a[i][0]]) { row[a[i][0]] = true; rowNum++; } if (!col[a[i][1]]) { col[a[i][1]] = true; colNum++; } if (rowNum == n || colNum == m) break; } long ans = 1; for (int i = 0; i < num; i++) { ans = (ans * k) % 998244353L; } out.println(ans); } } } static class FastReader { BufferedReader br; StringTokenizer st = new StringTokenizer(""); public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || (!st.hasMoreElements())) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void readArr(int[][] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) { a[i][j] = nextInt(); } } } public int nextInt() { return Integer.parseInt(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 11
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
45d87673db996b35c3b3af0e8397522b
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 { public void prayGod() throws IOException { int t = nextInt(); while (t-- > 0) { int n = nextInt(), m = nextInt(); int k = nextInt(), q = nextInt(); int[] x = new int[q]; int[] y = new int[q]; HashSet<Integer> seenRow = new HashSet<>(); HashSet<Integer> seenCol = new HashSet<>(); int colorCount = 0; for (int i = 0; i < q; i++) { x[i] = nextInt(); y[i] = nextInt(); } for (int i = q - 1; i >= 0; i--) { boolean rowExisted = seenRow.contains(x[i]); boolean colExisted = seenCol.contains(y[i]); if (!rowExisted || !colExisted) { colorCount++; seenRow.add(x[i]); seenCol.add(y[i]); } if (seenRow.size() >= n || seenCol.size() >= m) break; } out.println(binpow((long) k, (long) colorCount, 998244353)); } } public long binpow(long a, long b, long m2) { if (b < 0) return 0; long ret = 1, curr = a; while (b > 0) { if (b % 2 == 1) ret = (ret * curr) % m2; b /= 2; curr = (curr * curr) % m2; } return ret; } public void printVerdict(boolean verdict) { if (verdict) out.println("YES"); else out.println("NO"); } static final boolean RUN_TIMING = true; static final boolean AUTOFLUSH = false; static final boolean FILE_INPUT = false; static final boolean FILE_OUTPUT = false; static int iinf = 0x3f3f3f3f; static long inf = (long) 1e18 + 10; static long mod = 998244353L; static char[] inputBuffer = new char[1 << 20]; static PushbackReader in = new PushbackReader(new BufferedReader(new InputStreamReader(System.in)), 1 << 20); static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), AUTOFLUSH); // int data-type public int nextInt() throws IOException { return Integer.parseInt(next()); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public void sort(int[] a) { shuffle(a); Arrays.sort(a); } public static void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(); } // long data-type public long nextLong() throws IOException { return Long.parseLong(next()); } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public static void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(); } public void sort(long[] a) { shuffle(a); Arrays.sort(a); } // double data-type public double nextDouble() throws IOException { return Double.parseDouble(next()); } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) arr[i] = nextDouble(); return arr; } public static void printArray(double[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(); } // Generic type public <T> void sort(T[] a) { shuffle(a); Arrays.sort(a); } public static <T> void printArray(T[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(); } public String next() throws IOException { int len = 0; int c; do { c = in.read(); } while (Character.isWhitespace(c) && c != -1); if (c == -1) { throw new NoSuchElementException("Reached EOF"); } do { inputBuffer[len] = (char) c; len++; c = in.read(); } while (!Character.isWhitespace(c) && c != -1); while (c != '\n' && Character.isWhitespace(c) && c != -1) { c = in.read(); } if (c != -1 && c != '\n') { in.unread(c); } return new String(inputBuffer, 0, len); } public String nextLine() throws IOException { int len = 0; int c; while ((c = in.read()) != '\n' && c != -1) { if (c == '\r') { continue; } inputBuffer[len] = (char) c; len++; } return new String(inputBuffer, 0, len); } public boolean hasNext() throws IOException { String line = nextLine(); if (line.isEmpty()) { return false; } in.unread('\n'); in.unread(line.toCharArray()); return true; } public void shuffle(int[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { int j = (int) (Math.random() * (n - i)); int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } public void shuffle(long[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { int j = (int) (Math.random() * (n - i)); long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } public void shuffle(Object[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { int j = (int) (Math.random() * (n - i)); Object temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } public static void main(String[] args) throws IOException { if (FILE_INPUT) in = new PushbackReader(new BufferedReader(new FileReader(new File("output.txt"))), 1 << 20); if (FILE_OUTPUT) out = new PrintWriter(new FileWriter(new File("output.txt"))); long time = 0; time -= System.nanoTime(); new D().prayGod(); time += System.nanoTime(); if (RUN_TIMING) System.err.printf("%.3f ms%n", time / 1000000.0); out.flush(); in.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 11
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
9ee12983b760d3a19d7684ce29a6c117
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 crosscoloring; import java.util.*; import java.io.*; public class crosscoloring { public static void main(String[] args) throws IOException { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(fin.readLine()); StringBuilder fout = new StringBuilder(); while(t-- > 0) { StringTokenizer st = new StringTokenizer(fin.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()); long mod = 998244353; int[][] ops = new int[q][2]; for(int i = 0; i < q; i++) { st = new StringTokenizer(fin.readLine()); ops[i][0] = Integer.parseInt(st.nextToken()) - 1; ops[i][1] = Integer.parseInt(st.nextToken()) - 1; } HashSet<Integer> r = new HashSet<Integer>(); HashSet<Integer> c = new HashSet<Integer>(); //System.out.println(r + " " + c); long ans = 1; for(int i = q - 1; i >= 0; i--) { int nextR = ops[i][0]; int nextC = ops[i][1]; //System.out.println(nextR + " " + nextC); if(r.size() == n || c.size() == m || (r.contains(nextR) && c.contains(nextC))) { continue; } r.add(nextR); c.add(nextC); ans *= (long) k; ans %= mod; } fout.append(ans).append("\n"); } System.out.print(fout); } }
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 11
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
403befab08ce3d859a5236988f0b117f
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
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.lang.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.*; public class Eshan { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static DecimalFormat df = new DecimalFormat("0.0000000"); final static int mod = (int) (1e9 + 7); final static int MAX = Integer.MAX_VALUE; final static int MIN = Integer.MIN_VALUE; static Random rand = new Random(); // ======================= MAIN ================================== public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // ==== start ==== int t = readInt(); // int t = 1; preprocess(); while (t-- > 0) { solve(); } out.flush(); // ==== end ==== if (!oj) System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } private static void solve() throws IOException { int n = readInt(), m = readInt(), k = readInt(), q = readInt(); long ans = 1L; int[][] op = read2DIntArray(q, 2); Set<Integer> row = new HashSet<>(), col = new HashSet<>(); for (int i = q - 1; i >= 0; i--) { boolean flag = false; if (!row.contains(op[i][0]) && col.size() != m) flag = true; if (!col.contains(op[i][1]) && row.size() != n) flag = true; row.add(op[i][0]); col.add(op[i][1]); if (flag) { ans *= k; ans %= 998244353; } } out.println(ans); } private static void preprocess() { } // ==================== CUSTOM CLASSES ================================ static class Pair implements Comparable<Pair> { int first, second; Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair o) { if (this.first != o.first) return this.second - o.second; return this.first - o.first; } } static class DequeNode { DequeNode prev, next; int val; DequeNode(int val) { this.val = val; } DequeNode(int val, DequeNode prev, DequeNode next) { this.val = val; this.prev = prev; this.next = next; } } // ======================= FOR INPUT ================================== static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readString() throws IOException { return next(); } static String readLine() throws IOException { return br.readLine().trim(); } static int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = readInt(); return arr; } static int[][] read2DIntArray(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) arr[i] = readIntArray(m); return arr; } static List<Integer> readIntList(int n) throws IOException { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(readInt()); return list; } static long[] readLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = readLong(); return arr; } static long[][] read2DLongArray(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) arr[i] = readLongArray(m); return arr; } static List<Long> readLongList(int n) throws IOException { List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(readLong()); return list; } static char[] readCharArray(int n) throws IOException { return readString().toCharArray(); } static char[][] readMatrix(int n, int m) throws IOException { char[][] mat = new char[n][m]; for (int i = 0; i < n; i++) mat[i] = readCharArray(m); return mat; } // ========================= FOR OUTPUT ================================== private static void printIList(List<Integer> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printLList(List<Long> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printIArray(int[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DIArray(int[][] arr) { for (int i = 0; i < arr.length; i++) printIArray(arr[i]); } private static void printLArray(long[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DLArray(long[][] arr) { for (int i = 0; i < arr.length; i++) printLArray(arr[i]); } // ====================== TO CHECK IF STRING IS NUMBER ======================== private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } private static boolean isLong(String s) { try { Long.parseLong(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } // ==================== FASTER SORT ================================ private static void sort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void sort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // ==================== MATHEMATICAL FUNCTIONS =========================== private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static long power(long a, long b) { if (b == 0) return 1L; long ans = power(a, b >> 1); ans *= ans; if ((b & 1) == 1) ans *= a; return ans; } private static int mod_power(int a, int b) { if (b == 0) return 1; int temp = mod_power(a, b >> 1); temp %= mod; temp = (int) ((1L * temp * temp) % mod); if ((b & 1) == 1) temp = (int) ((1L * temp * a) % mod); return temp; } private static int multiply(int a, int b) { return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod); } private static boolean isPrime(long n) { for (long i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } private static long nCr(long n, long r) { if (n - r > r) r = n - r; long ans = 1L; for (long i = r + 1; i <= n; i++) ans *= i; for (long i = 2; i <= n - r; i++) ans /= i; return ans; } // ==================== Primes using Seive ===================== private static List<Integer> getPrimes(int n) { boolean[] prime = new boolean[n + 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; } } // return prime; List<Integer> list = new ArrayList<>(); for (int i = 2; i <= n; i++) if (prime[i]) list.add(i); return list; } private static int[] SeivePrime(int n) { int[] primes = new int[n]; for (int i = 0; i < n; i++) primes[i] = i; for (int i = 2; i * i < n; i++) { if (primes[i] != i) continue; for (int j = i * i; j < n; j += i) { if (primes[j] == j) primes[j] = i; } } return primes; } // ==================== STRING FUNCTIONS ================================ private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } private static String sortString(String str) { int[] arr = new int[256]; for (char ch : str.toCharArray()) arr[ch]++; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; i++) while (arr[i]-- > 0) sb.append((char) i); return sb.toString(); } // ==================== LIS & LNDS ================================ private static int LIS(int arr[], int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find1(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find1(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) >= val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } // =============== Lower Bound & Upper Bound =========== // less than or equal private static int lower_bound(List<Integer> list, int val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(List<Long> list, long val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(int[] arr, int val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(long[] arr, long val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } // greater than or equal private static int upper_bound(List<Integer> list, int val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(List<Long> list, long val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(int[] arr, int val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(long[] arr, long val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // ==================== UNION FIND ===================== private static int find(int x, int[] parent) { if (parent[x] == x) return x; return parent[x] = find(parent[x], parent); } private static boolean union(int x, int y, int[] parent, int[] rank) { int lx = find(x, parent), ly = find(y, parent); if (lx == ly) return false; if (rank[lx] > rank[ly]) parent[ly] = lx; else if (rank[lx] < rank[ly]) parent[lx] = ly; else { parent[lx] = ly; rank[ly]++; } return true; } // ==================== SEGMENT TREE (RANGE SUM) ===================== public static class SegmentTree { int n; int[] arr, tree, lazy; SegmentTree(int arr[]) { this.arr = arr; this.n = arr.length; this.tree = new int[(n << 2)]; this.lazy = new int[(n << 2)]; build(1, 0, n - 1); } void build(int id, int start, int end) { if (start == end) tree[id] = arr[start]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; build(left, start, mid); build(right, mid + 1, end); tree[id] = tree[left] + tree[right]; } } void update(int l, int r, int val) { update(1, 0, n - 1, l, r, val); } void update(int id, int start, int end, int l, int r, int val) { distribute(id, start, end); if (end < l || r < start) return; if (start == end) tree[id] += val; else if (l <= start && end <= r) { lazy[id] += val; distribute(id, start, end); } else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; update(left, start, mid, l, r, val); update(right, mid + 1, end, l, r, val); tree[id] = tree[left] + tree[right]; } } int query(int l, int r) { return query(1, 0, n - 1, l, r); } int query(int id, int start, int end, int l, int r) { if (end < l || r < start) return 0; distribute(id, start, end); if (start == end) return tree[id]; else if (l <= start && end <= r) return tree[id]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r); } } void distribute(int id, int start, int end) { if (start == end) tree[id] += lazy[id]; else { tree[id] += lazy[id] * (end - start + 1); lazy[(id << 1)] += lazy[id]; lazy[(id << 1) + 1] += lazy[id]; } lazy[id] = 0; } } // ==================== TRIE ================================ static class Trie { class Node { Node[] children; boolean isEnd; Node() { children = new Node[26]; } } Node root; Trie() { root = new Node(); } public void insert(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) curr.children[ch - 'a'] = new Node(); curr = curr.children[ch - 'a']; } curr.isEnd = true; } public boolean find(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) return false; curr = curr.children[ch - 'a']; } return curr.isEnd; } } // ==================== FENWICK TREE ================================ static class FT { long[] tree; int n; FT(int[] arr, int n) { this.n = n; this.tree = new long[n + 1]; for (int i = 1; i <= n; i++) { update(i, arr[i - 1]); } } void update(int idx, int val) { while (idx <= n) { tree[idx] += val; idx += idx & -idx; } } long query(int l, int r) { return getSum(r) - getSum(l - 1); } long getSum(int idx) { long ans = 0L; while (idx > 0) { ans += tree[idx]; idx -= idx & -idx; } return ans; } } // ==================== BINARY INDEX TREE ================================ static class BIT { long[][] tree; int n, m; BIT(int[][] mat, int n, int m) { this.n = n; this.m = m; tree = new long[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { update(i, j, mat[i - 1][j - 1]); } } } void update(int x, int y, int val) { while (x <= n) { int t = y; while (t <= m) { tree[x][t] += val; t += t & -t; } x += x & -x; } } long query(int x1, int y1, int x2, int y2) { return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1); } long getSum(int x, int y) { long ans = 0L; while (x > 0) { int t = y; while (t > 0) { ans += tree[x][t]; t -= t & -t; } x -= x & -x; } return ans; } } }
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 11
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
7bd9655623a5c9d88b846b0c59319acd
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 c1644; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.Random; import java.util.StringTokenizer; // // Educational Codeforces Round 123 (Rated for Div. 2) 2022-02-22 06:35 // D. Cross Coloring // https://codeforces.com/contest/1644/problem/D // time limit per test 2 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // There is a sheet of paper that can be represented with a grid of size n x 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. // // Input // // The first line contains a single integer t (1 <= t <= 10^4)-- the number of testcases. // // The first line of the testcase contains four integers n, m, k and q (1 <= n, m, k, q <= 2 * // 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 <= x_i <= n; 1 <= y_i <= m)-- the row and the column the operation is applied to. // // The sum of q over all testcases doesn't exceed 2 * 10^5. // // Output // // For each testcase, print a single integer-- the number of different colorings modulo 998,244,353. // // Example /* input: 2 1 1 3 2 1 1 1 1 2 2 2 3 2 1 1 1 2 2 output: 3 4 */ // public class C1644D { static final int MOD = 998244353; static final Random RAND = new Random(); static int solve(int n, int m, int k, int[][] ops) { int q = ops.length; boolean[] rows = new boolean[n]; boolean[] cols = new boolean[m]; int numRows = 0; int numCols = 0; int count = 0; for (int i = q - 1; i >= 0; i--) { int r = ops[i][0]; int c = ops[i][1]; // Is the op deemed irrelevant due to ops after? if (rows[r] && cols[c]) { continue; } if (numRows == n || numCols == m) { continue; } if (!rows[r]) { rows[r] = true; numRows++; } if (!cols[c]) { cols[c] = true; numCols++; } count++; } long ans = 1; for (int i = 0; i < count; i++) { ans = (ans * k) % MOD; } return (int) ans; } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int q = in.nextInt(); int[][] ops = new int[q][2]; for (int i = 0; i < q; i++) { ops[i][0] = in.nextInt() - 1; ops[i][1] = in.nextInt() - 1; } int ans = solve(n, m, k, ops); System.out.println(ans); } } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 500) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName(); cname = cname.lastIndexOf('.') > 0 ? cname.substring(0, cname.lastIndexOf('.')) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } 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 11
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
bc4668ec2d4f6fc5084e84d5c1fd8ef0
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.Set; import java.util.InputMismatchException; import java.io.IOException; import java.util.HashSet; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); DCrossColoring solver = new DCrossColoring(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) { solver.solve(i, in, out); } out.close(); } static class DCrossColoring { public void solve(int testNumber, InputReader in, OutputWriter out) { int mod = 998244353; int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int q = in.nextInt(); int[] row = new int[q]; int[] col = new int[q]; for (int i = 0; i < q; i++) { row[i] = in.nextInt(); col[i] = in.nextInt(); } Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); long res = 1; for (int i = q - 1; i >= 0; i--) { int x = row[i]; int y = col[i]; boolean f = false; if (set1.contains(x) && set2.contains(y)) { f = true; } if (!set2.contains(y) && set1.size() == n) { f = true; } if (!set1.contains(x) && set2.size() == m) { f = true; } if (!f) { res *= k; res %= mod; } set1.add(x); set2.add(y); } out.println(res); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public 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 close() { writer.close(); } public void println(long i) { writer.println(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 11
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
ed26f143103475fc66abf11882375c64
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.*; public class P1644D { public static void solve (int n, int m, int k, int q, List<Integer> rs, List<Integer> cs){ long ans = 1; long mod = 998244353; Set<Integer> vrow = new HashSet<>(); Set<Integer> vcol = new HashSet<>(); for (int i=q-1; i >= 0; i--){ if ((vrow.contains(rs.get(i)) && vcol.contains(cs.get(i))) || vrow.size() == n || vcol.size() == m){ } else { ans *= k; ans %= mod; } vrow.add(rs.get(i)); vcol.add(cs.get(i)); } System.out.println(ans); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { StringTokenizer 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()); List<Integer> rs = new ArrayList<>(); List<Integer> cs = new ArrayList<>(); for (int j=0; j < q; j++){ st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken())-1; int y = Integer.parseInt(st.nextToken())-1; rs.add(x); cs.add(y); } solve (n, m, k, q, rs, cs); } } }
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 11
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
c779045b55badf0ee348fb30269903cc
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.HashSet; import java.util.Scanner; import java.util.Set; public class TaskD { public static void main(String[] args) { Scanner in = new Scanner(System.in); TaskD taskD = new TaskD(); int t = in.nextInt(); for (int i = 0; i < t; i++) { taskD.solve(in); } } private void solve(final Scanner in) { final int n = in.nextInt(); final int m = in.nextInt(); final int k = in.nextInt(); final int q = in.nextInt(); final int[] rows = new int[q]; final int[] columns = new int[q]; for (int i = 0; i < q; i++) { rows[i] = in.nextInt(); columns[i] = in.nextInt(); } final Set<Integer> insertedRows = new HashSet<>(); final Set<Integer> insertedColumns = new HashSet<>(); long res = 1L; for (int i = q - 1; i >= 0; i--) { if (insertedRows.contains(rows[i]) && insertedColumns.contains(columns[i])) { continue; } else if (insertedRows.size() == n) { continue; } else if (insertedColumns.size() == m) { continue; } else { res = mod(res, k); } insertedRows.add(rows[i]); insertedColumns.add(columns[i]); } System.out.println(res); } private long mod(final long a, final long b) { final long MOD = 998244353; return ((a % MOD) * (b % MOD)) % MOD; } }
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 11
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
cd9b4220a6d90260876988a4f9dcd288
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{ public static long mod = 998244353; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int nc = Integer.parseInt(br.readLine()); for(int cc = 0; cc < nc; cc++){ StringTokenizer details = new StringTokenizer(br.readLine()); long n = Long.parseLong(details.nextToken()); long m = Long.parseLong(details.nextToken()); long k = Long.parseLong(details.nextToken()); int q = Integer.parseInt(details.nextToken()); long[][] coords = new long[q][2]; HashMap<Long, Integer> lgx = new HashMap<Long, Integer>(); HashMap<Long, Integer> lgy = new HashMap<Long, Integer>(); int largestX = 1000000000; //earliest visible row int largestY = 1000000000; //earliest visible col for(int a = 0; a < q; a++){ StringTokenizer st = new StringTokenizer(br.readLine()); coords[a][0] = Long.parseLong(st.nextToken()); coords[a][1] = Long.parseLong(st.nextToken()); lgx.put(coords[a][0], a); lgy.put(coords[a][1], a); } for(long item : lgx.keySet()) largestX = Math.min(largestX, lgx.get(item)); for(long item : lgy.keySet()) largestY = Math.min(largestY, lgy.get(item)); //System.out.println(lgx + " smallest is " + largestX); //System.out.println(lgy + " smallest is " + largestY); long excluded = 0; for(int a = 0; a < q; a++){ //if entire row and entire column are covered then this cross does not matter boolean rowc = false; if(lgx.get(coords[a][0]) > a) rowc = true; if(lgy.size() == m && largestY > a) rowc = true; boolean colc = false; if(lgy.get(coords[a][1]) > a) colc = true; if(lgx.size() == n && largestX > a) colc = true; //System.out.println(a + " " + rowc + " " + colc); if(rowc && colc) excluded++; } //System.out.println(excluded); System.out.println(pow(k, (long) q - excluded)); } br.close(); } public static long pow(long n, long pw){ if(pw == 0) return 1L; long half = pow(n, pw/2); if(pw % 2 == 0) return (half * half) % mod; return (((half * half) % mod) * n) % mod; } }
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 11
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
13e9f29c9cff07cb642a1fd2f7c5f65d
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 CF_Edu123 { static FastScanner fs; static FastWriter fw; static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null; private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}}; private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; private static final int iMax = (int) (1e9 + 100), iMin = (int) (-1e9 - 100); private static final long lMax = (long) (1e18 + 100), lMin = (long) (-1e18 - 100); private static final int mod1 = (int) (1e9 + 7); private static final int mod2 = 998244353; public static void main(String[] args) throws IOException { fs = new FastScanner(); fw = new FastWriter(); int t = 1; t = fs.nextInt(); while (t-- > 0) { solve(); } fw.out.close(); } private static void solve() { int n = fs.nextInt(), m = fs.nextInt(), k = fs.nextInt(), q = fs.nextInt(); int[] arr1 = new int[q], arr2 = new int[q]; for (int i = 0; i < q; i++) { arr1[i] = fs.nextInt(); arr2[i] = fs.nextInt(); } Set<Integer> rows = new HashSet<>(), cols = new HashSet<>(); int cnt = 0; for (int i = (q - 1); i >= 0; i--) { int x = arr1[i], y = arr2[i]; boolean temp1 = !rows.contains(x) && (cols.size() != m); boolean temp2 = !cols.contains(y) && (rows.size() != n); if (temp1 || temp2) cnt++; rows.add(x); cols.add(y); } long result = pow(k, cnt, mod2); fw.out.println(result); } private static class UnionFind { private final int[] parent; private final int[] rank; UnionFind(int n) { parent = new int[n + 5]; rank = new int[n + 5]; for (int i = 0; i <= n; i++) { parent[i] = i; rank[i] = 0; } } private int find(int i) { if (parent[i] == i) return i; return parent[i] = find(parent[i]); } private void union(int a, int b) { a = find(a); b = find(b); if (a != b) { if (rank[a] < rank[b]) { int temp = a; a = b; b = temp; } parent[b] = a; if (rank[a] == rank[b]) rank[a]++; } } } private static long gcd(long a, long b) { return (b == 0 ? a : gcd(b, a % b)); } private static long lcm(long a, long b) { return ((a * b) / gcd(a, b)); } private static long pow(long a, long b, int mod) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a) % mod; } a = (a * a) % mod; b >>= 1; } return result; } private static long ceilDiv(long a, long b) { return ((a + b - 1) / b); } private static long getMin(long... args) { long min = lMax; for (long arg : args) min = Math.min(min, arg); return min; } private static long getMax(long... args) { long max = lMin; for (long arg : args) max = Math.max(max, arg); return max; } private static boolean isPalindrome(String s, int l, int r) { int i = l, j = r; while (j - i >= 1) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; } return true; } private static List<Integer> primes(int n) { boolean[] primeArr = new boolean[n + 5]; Arrays.fill(primeArr, true); for (int i = 2; (i * i) <= n; i++) { if (primeArr[i]) { for (int j = i * i; j <= n; j += i) { primeArr[j] = false; } } } List<Integer> primeList = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (primeArr[i]) primeList.add(i); } return primeList; } private static class Pair<U, V> { private final U first; private final V second; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return first.equals(pair.first) && second.equals(pair.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return "(" + first + ", " + second + ")"; } private Pair(U ff, V ss) { this.first = ff; this.second = ss; } } private static <T> void randomizeArr(T[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swap(arr, i, j); } } private static Integer[] readIntArray(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextInt(); return arr; } private static List<Integer> readIntList(int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextInt()); return list; } private static <T> void swap(T[] arr, int i, int j) { T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } private static <T> void displayArr(T[] arr) { for (T x : arr) fw.out.print(x + " "); fw.out.println(); } private static <T> void displayList(List<T> list) { for (T x : list) fw.out.print(x + " "); fw.out.println(); } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws IOException { if (checkOnlineJudge) this.br = new BufferedReader(new FileReader("src/input.txt")); else this.br = new BufferedReader(new InputStreamReader(System.in)); this.st = new StringTokenizer(""); } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException err) { err.printStackTrace(); } } return st.nextToken(); } public String nextLine() { if (st.hasMoreTokens()) { return st.nextToken("").trim(); } try { return br.readLine().trim(); } catch (IOException err) { err.printStackTrace(); } return ""; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } private static class FastWriter { PrintWriter out; FastWriter() throws IOException { if (checkOnlineJudge) out = new PrintWriter(new FileWriter("src/output.txt")); else out = new PrintWriter(System.out); } } }
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 11
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
957152b0320c60a990ee2bb885c4b1c3
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.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; public class Main { static final long MOD1=1000000007; static final long MOD=998244353; static int[] ans; public static void main(String[] args){ PrintWriter out = new PrintWriter(System.out); InputReader sc=new InputReader(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { 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 j = 0; j < y.length; j++) { x[j] = sc.nextInt()-1; y[j] = sc.nextInt()-1; } out.println(solve(n, m, k, q, x, y)); } out.flush(); } static long solve(int n, int m, int k, int q, int[] x,int[] y){ long ans = 1l; boolean[] xvis = new boolean[n]; boolean[] yvis = new boolean[m]; int xcnt = 0; int ycnt = 0; for (int i = q-1; i >= 0; i--) { if(xcnt==n||ycnt==m) break; if (xvis[x[i]] && yvis[y[i]]) continue; ans = (ans * k)%MOD; if(!xvis[x[i]]) xcnt++; if(!yvis[y[i]]) ycnt++; xvis[x[i]] = true; yvis[y[i]] = true; } return ans; } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } }
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 11
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
bae11b9dc419c0f08e43e9124087264e
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 Main { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } int[] na(int n) throws IOException { int[]A=new int[n]; for (int i=0;i<n;i++) A[i]=ni(); return A; } long mod=998244353; void solve() throws IOException { for (int tc=ni();tc>0;tc--) { int n=ni(),m=ni(); long k=ni(); int q=ni(); boolean[]R=new boolean[n+1]; boolean[]C=new boolean[m+1]; int rct=0; int cct=0; int act=0; int[][]Q=new int[q][2]; for (int i=0;i<q;i++) { Q[i][0]=ni(); Q[i][1]=ni(); } for (int i=q-1;i>=0;i--) { int x=Q[i][0]; int y=Q[i][1]; if (R[x] && C[y]) continue; act++; if (!R[x]) { R[x]=true; rct++; } if (!C[y]) { C[y]=true; cct++; } if (rct==n || cct==m) break; } out.println(mp(k,act)); } out.flush(); } int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); } long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); } long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; } public static void main(String[] args) throws IOException { new Main().solve(); } }
Java
["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 11
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
74c02c7b55a6dc984355b1a60a3725cf
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.util.HashMap; import java.util.function.Consumer; import java.util.Comparator; public class FirstProject{ static void solve(Scanner src) { int n=src.nextInt(); int m=src.nextInt(); int k=src.nextInt(); int q=src.nextInt(); long ans = 1L; HashSet<Integer>row=new HashSet<>(); HashSet<Integer>col=new HashSet<>(); int op[][]=new int[q][2]; for(int i=0;i<q;i++) { for(int j=0;j<2;j++) { op[i][j]=src.nextInt(); } } for(int i=q-1;i>=0;i--) { boolean flag = false; if (!row.contains(op[i][0]) && col.size() != m) flag = true; if (!col.contains(op[i][1]) && row.size() != n) flag = true; row.add(op[i][0]); col.add(op[i][1]); if (flag) { ans *= k; ans %= 998244353; } } System.out.println(ans); } public static void main(String[] args) throws IOException{ Scanner src=new Scanner(System.in); int t=src.nextInt(); while(t-- > 0) { solve(src); } } }
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 11
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
9707d58f6e89a00e70c69ec2aa51f2bf
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
//some updates in import stuff import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class Main{ static long mod = 998244353L; static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final double eps = 1e-10; static List<Integer> primeNumbers = new ArrayList<>(); public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); //code below int test = sc.nextInt(); while(test --> 0){ int n = sc.nextInt(); int m = sc.nextInt(); long k = sc.nextLong(); int q = sc.nextInt(); int[][] query = new int[q][2]; for(int i = 0; i < q; i++){ query[i][0] = sc.nextInt(); query[i][1] = sc.nextInt(); } //after this is done, figure out number of different position for different colors Set<Integer> row = new HashSet<>(); Set<Integer> col = new HashSet<>(); int count = 0; for(int i = q-1; i >= 0; i--){ //simple logic should be used no matter what for sure!! int cr = query[i][0]; int cc = query[i][1]; // out.println(cr + " " + cc); if(!row.contains(cr)){ if(col.size() < m){ count++; } row.add(cr); col.add(cc); } if(!col.contains(cc)){ if(row.size() < n){ count++; } col.add(cc); row.add(cr); } } // out.println(count); //pretty much what i think is correct //now permutation part is started for sure // out.println(count + " " + k); long answer = powerMOD(k, (long)count); out.println(answer); } out.close(); } //Updation Required //Fenwick Tree (customisable) //Segment Tree (customisable) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //primeExponentCounts //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //GRAPH (basic structure) public static class Graph{ public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V){ this.V = V; edges = new ArrayList<>(V+1); for(int i= 0; i <= V; i++){ edges.add(new ArrayList<>()); } } public void addEdge(int from , int to){ edges.get(from).add(to); edges.get(to).add(from); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent,-1); this.n = n; } public int find(int curr){ if(parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b){ int s1 = find(a); int s2 = find(b); if(s1 != s2){ if(rank[s1] < rank[s2]){ parent[s1] = s2; rank[s2] += rank[s1]; }else{ parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ x %= mod; res %= mod; res = (res * x)%mod; } // y must be even now y = y >> 1; // y = y/2 x%= mod; x = (x * x)%mod; // Change x to x^2 } return res%mod; } //without mod public static long power(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ res = (res * x); } // y must be even now y = y >> 1; // y = y/ x = (x * x); } return res; } public static class segmentTree{ public long[] arr; public long[] tree; public long[] lazy; segmentTree(long[] array){ int n = array.length; arr = new long[n]; for(int i= 0; i < n; i++) arr[i] = array[i]; tree = new long[4*n + 1]; lazy = new long[4*n + 1]; } public void build(int[]arr, int s, int e, int[] tree, int index){ if(s == e){ tree[index] = arr[s]; return; } //otherwise divide in two parts and fill both sides simply int mid = (s+e)/2; build(arr, s, mid, tree, 2*index); build(arr, mid+1, e, tree, 2*index+1); //who will build the current position dude tree[index] = Math.min(tree[2*index], tree[2*index+1]); } public int query(int sr, int er, int sc, int ec, int index, int[] tree){ if(lazy[index] != 0){ tree[index] += lazy[index]; if(sc != ec){ lazy[2*index+1] += lazy[index]; lazy[2*index] += lazy[index]; } lazy[index] = 0; } //no overlap if(sr > ec || sc > er) return Integer.MAX_VALUE; //found the index baby if(sr <= sc && ec <= er) return tree[index]; //finding the index on both sides hehehehhe int mid = (sc + ec)/2; int left = query(sr, er, sc, mid, 2*index, tree); int right = query(sr, er, mid+1, ec, 2*index + 1, tree); return Integer.min(left, right); } //now we will do point update implementation //it should be simple then we expected for sure public void update(int index, int indexr, int increment, int[] tree, int s, int e){ if(lazy[index] != 0){ tree[index] += lazy[index]; if(s != e){ lazy[2*index+1] = lazy[index]; lazy[2*index] = lazy[index]; } lazy[index] = 0; } //no overlap if(indexr < s || indexr > e) return; //found the required index if(s == e){ tree[index] += increment; return; } //search for the index on both sides int mid = (s+e)/2; update(2*index, indexr, increment, tree, s, mid); update(2*index+1, indexr, increment, tree, mid+1, e); //now update the current range simply tree[index] = Math.min(tree[2*index+1], tree[2*index]); } public void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){ //if not at all in the same range if(e < sr || er < s) return; //complete then also move forward if(s == e){ tree[index] += increment; return; } //otherwise move in both subparts int mid = (s+e)/2; rangeUpdate(tree, 2*index, s, mid, sr, er, increment); rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment); //update current range too na //i always forget this step for some reasons hehehe, idiot tree[index] = Math.min(tree[2*index], tree[2*index + 1]); } public void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){ //update lazy values //resolve lazy value before going down if(lazy[index] != 0){ tree[index] += lazy[index]; if(s != e){ lazy[2*index+1] += lazy[index]; lazy[2*index] += lazy[index]; } lazy[index] = 0; } //no overlap case if(sr > e || s > er) return; //complete overlap if(sr <= s && er >= e){ tree[index] += increment; if(s != e){ lazy[2*index+1] += increment; lazy[2*index] += increment; } return; } //otherwise go on both left and right side and do your shit int mid = (s + e)/2; rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment); rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment); tree[index] = Math.min(tree[2*index+1], tree[2*index]); return; } } //prime sieve public static void primeSieve(int n){ BitSet bitset = new BitSet(n+1); for(long i = 0; i < n ; i++){ if (i == 0 || i == 1) { bitset.set((int) i); continue; } if(bitset.get((int) i)) continue; primeNumbers.add((int)i); for(long j = i; j <= n ; j+= i) bitset.set((int)j); } } //number of divisors public static int countDivisors(long number){ if(number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while(curr * curr <= number){ while(number % curr == 0){ number = number/curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if(number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //primeExponentCounts public static int primeExponentsCount(int n) { if (n <= 1) return 0; int sqrt = (int) Math.sqrt(n); int remainingNumber = n; int result = 0; for (int i = 2; i <= sqrt; i++) { while (remainingNumber % i == 0) { result++; remainingNumber /= i; } } //in case of prime numbers this would happen if (remainingNumber > 1) { result++; } return result; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } //is vowel function public static boolean isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } //to sort the array with better method public 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); } //sort long public 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); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair{ public int a; public int b; Pair(int a , int b){ this.a = a; this.b = b; } @Override public String toString(){ return a + " -> " + b; } } //Triplet with int int int public static class Triplet{ public int a; public int b; public int c; Triplet(int a , int b, int c){ this.a = a; this.b = b; this.c = c; } @Override public String toString(){ return a + " -> " + b; } } //Shortcut function public static long lcm(long a , long b){ return a * (b/gcd(a,b)); } //let's make one for calculating lcm basically public static int lcm(int a , int b){ return (a * b)/gcd(a,b); } //int version for gcd public static int gcd(int a, int b){ if(b == 0) return a; return gcd(b , a%b); } //long version for gcd public static long gcd(long a, long b){ if(b == 0) return a; return gcd(b , a%b); } //for ncr calculator(ignore this code) public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } //swapping two elements in an array public static void swap(int[] arr, int left , int right){ int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //for char array public static void swap(char[] arr, int left , int right){ char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr){ int left = 0; int right = arr.length-1; while(left <= right){ swap(arr, left,right); left++; right--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K , long mod){ long upper = 1L; long lower = 1L; long lowerr = 1L; for(long i = 1; i <= N; i++){ upper = mod_mul(upper, i, mod); } for(long i = 1; i <= K; i++){ lower = mod_mul(lower, i, mod); } for(long i = 1; i <= (N - K); i++){ lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // long[] fact = new long[2 * n + 1]; // long[] ifact = new long[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (long i = 1; i <= 2 * n; i++) // { // fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod); // ifact[(int)i] = mminvprime(fact[(int)i], mod); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int)n]; long val2 = ifact[(int)(n - r)]; long val3 = ifact[(int)r]; return (((val1 * val2) % m) * val3) % m; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["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 11
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
2771bb2ac030a37641a33b4a6869dea4
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 Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]),k=Integer.parseInt(s[2]),q=Integer.parseInt(s[3]); int i,c[][]=new int[q][2]; for(i=0;i<q;i++) { s=bu.readLine().split(" "); int x=Integer.parseInt(s[0]),y=Integer.parseInt(s[1]); c[i][0]=x; c[i][1]=y; } long ans=1,M=998244353; Set<Integer> x=new HashSet<>(),y=new HashSet<>(); for(i=q-1;i>=0;i--) { boolean okrow=y.size()!=m && !x.contains(c[i][0]); boolean okcol=x.size()!=n && !y.contains(c[i][1]); if(okrow || okcol) ans=ans*k%M; x.add(c[i][0]); y.add(c[i][1]); } sb.append(ans+"\n"); } System.out.print(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 11
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
188d26192f35eac497e5a879142bbd7f
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 javax.print.DocFlavor.INPUT_STREAM; import java.io.*; import java.math.*; import java.sql.Array; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; public class Main { private static class MyScanner { private static final int BUF_SIZE = 2048; BufferedReader br; private MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } private boolean isSpace(char c) { return c == '\n' || c == '\r' || c == ' '; } String next() { try { StringBuilder sb = new StringBuilder(); int r; while ((r = br.read()) != -1 && isSpace((char)r)); if (r == -1) { return null; } sb.append((char) r); while ((r = br.read()) != -1 && !isSpace((char)r)) { sb.append((char)r); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } static class Reader{ BufferedReader br; StringTokenizer st; public Reader() { 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 long mod = (long)(1e9 + 7); static void sort(long[] arr ) { ArrayList<Long> al = new ArrayList<>(); for(long e:arr) al.add(e); Collections.sort(al); for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i); } static void sort(int[] arr ) { ArrayList<Integer> al = new ArrayList<>(); for(int e:arr) al.add(e); Collections.sort(al); for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i); } static void sort(char[] arr) { ArrayList<Character> al = new ArrayList<Character>(); for(char cc:arr) al.add(cc); Collections.sort(al); for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i); } static long mod_mul( long... a) { long ans = a[0]%mod; for(int i = 1 ; i<a.length ; i++) { ans = (ans * (a[i]%mod))%mod; } return ans; } static long mod_sum( long... a) { long ans = 0; for(long e:a) { ans = (ans + e)%mod; } return ans; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void print(long[] arr) { System.out.println("---print---"); for(long e:arr) System.out.print(e+" "); System.out.println("-----------"); } static void print(int[] arr) { System.out.println("---print---"); for(long e:arr) System.out.print(e+" "); System.out.println("-----------"); } static boolean[] prime(int num) { boolean[] bool = new boolean[num]; for (int i = 0; i< bool.length; i++) { bool[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(bool[i] == true) { for(int j = (i*i); j<num; j = j+i) { bool[j] = false; } } } if(num >= 0) { bool[0] = false; bool[1] = false; } return bool; } static long modInverse(long a, long m) { long g = gcd(a, m); return power(a, m - 2); } static long lcm(long a , long b) { return (a*b)/gcd(a, b); } static int lcm(int a , int b) { return (int)((a*b)/gcd(a, b)); } static long power(long x, long y){ if(y<0) return 0; long m = mod; if (y == 0) return 1; long p = power(x, y / 2) % m; p = (int)((p * (long)p) % m); if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); } static class Combinations{ private long[] z; // factorial private long[] z1; // inverse factorial private long[] z2; // incerse number private long mod; public Combinations(long N , long mod) { this.mod = mod; z = new long[(int)N+1]; z1 = new long[(int)N+1]; z[0] = 1; for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod; z2 = new long[(int)N+1]; z2[0] = z2[1] = 1; for (int i = 2; i <= N; i++) z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod; z1[0] = z1[1] = 1; for (int i = 2; i <= N; i++) z1[i] = (z2[i] * z1[i - 1]) % mod; } long fac(long n) { return z[(int)n]; } long invrsNum(long n) { return z2[(int)n]; } long invrsFac(long n) { return z1[(int)n]; } long ncr(long N, long R) { if(R<0 || R>N ) return 0; long ans = ((z[(int)N] * z1[(int)R]) % mod * z1[(int)(N - R)]) % mod; return ans; } } static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } void makeSet() { for (int i = 0; i < n; i++) { parent[i] = i; } } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; } } } static int max(int... a ) { int max = a[0]; for(int e:a) max = Math.max(max, e); return max; } static long max(long... a ) { long max = a[0]; for(long e:a) max = Math.max(max, e); return max; } static int min(int... a ) { int min = a[0]; for(int e:a) min = Math.min(e, min); return min; } static long min(long... a ) { long min = a[0]; for(long e:a) min = Math.min(e, min); return min; } static int[] KMP(String str) { int n = str.length(); int[] kmp = new int[n]; for(int i = 1 ; i<n ; i++) { int j = kmp[i-1]; while(j>0 && str.charAt(i) != str.charAt(j)) { j = kmp[j-1]; } if(str.charAt(i) == str.charAt(j)) j++; kmp[i] = j; } return kmp; } /************************************************ Query **************************************************************************************/ /***************************************** Sparse Table ********************************************************/ static class SparseTable{ private long[][] st; SparseTable(long[] arr){ int n = arr.length; st = new long[n][25]; log = new int[n+2]; build_log(n+1); build(arr); } private void build(long[] arr) { int n = arr.length; for(int i = n-1 ; i>=0 ; i--) { for(int j = 0 ; j<25 ; j++) { int r = i + (1<<j)-1; if(r>=n) break; if(j == 0 ) st[i][j] = arr[i]; else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] ); } } } public long gcd(long a ,long b) { if(a == 0) return b; return gcd(b%a , a); } public long query(int l ,int r) { int w = r-l+1; int power = log[w]; return Math.min(st[l][power],st[r - (1<<power) + 1][power]); } private int[] log; void build_log(int n) { log[1] = 0; for(int i = 2 ; i<=n ; i++) { log[i] = 1 + log[i/2]; } } } /******************************************************** Segement Tree *****************************************************/ static class SegmentTree{ long[] tree; long[] arr; int n; SegmentTree(long[] arr){ this.n = arr.length; tree = new long[4*n+1]; this.arr = arr; buildTree(0, n-1, 1); } void buildTree(int s ,int e ,int index ) { if(s == e) { tree[index] = arr[s]; return; } int mid = (s+e)/2; buildTree( s, mid, 2*index); buildTree( mid+1, e, 2*index+1); tree[index] = gcd(tree[2*index] , tree[2*index+1]); } long query(int si ,int ei) { return query(0 ,n-1 , si ,ei , 1 ); } private long query( int ss ,int se ,int qs , int qe,int index) { if(ss>=qs && se<=qe) return tree[index]; if(qe<ss || se<qs) return (long)(0); int mid = (ss + se)/2; long left = query( ss , mid , qs ,qe , 2*index); long right= query(mid + 1 , se , qs ,qe , 2*index+1); return gcd(left, right); } public void update(int index , int val) { arr[index] = val; // for(long e:arr) System.out.print(e+" "); update(index , 0 , n-1 , 1); } private void update(int id ,int si , int ei , int index) { if(id < si || id>ei) return; if(si == ei ) { tree[index] = arr[id]; return; } if(si > ei) return; int mid = (ei + si)/2; update( id, si, mid , 2*index); update( id , mid+1, ei , 2*index+1); tree[index] = Math.min(tree[2*index] ,tree[2*index+1]); } } /* ***************************************************************************************************************************************************/ // static MyScanner sc = new MyScanner(); // only in case of less memory static Reader sc = new Reader(); static int TC; static StringBuilder sb = new StringBuilder(); static PrintWriter out=new PrintWriter(System.out); public static void main(String args[]) throws IOException { int tc = 1; tc = sc.nextInt(); TC = 0; for(int i = 1 ; i<=tc ; i++) { TC++; // sb.append("Case #" + i + ": " ); // During KickStart && HackerCup TEST_CASE(); } System.out.print(sb); } static void TEST_CASE() throws IOException { mod = 998244353 ; int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int q = sc.nextInt(); int[][] quer = new int[q][2]; for(int i = 0 ; i<q ; i++) { quer[i][0] = sc.nextInt(); quer[i][1] = sc.nextInt(); } Set<Integer> r = new HashSet<>(); Set<Integer> c = new HashSet<>(); Map<Integer , Integer> row = new HashMap<>(); Map<Integer , Integer> col = new HashMap<>(); for(int i = q-1 ; i>=0 ; i--) { int x = quer[i][0] , y = quer[i][1]; if(!row.containsKey(x-1)) row.put(x-1 , i); if(!col.containsKey(y-1)) col.put(y-1,i); r.add(x); c.add(y); if(r.size() == n || c.size() == m) break; } Set<Integer> set = new HashSet<>(); for(int key:row.keySet()) set.add(row.get(key)); for(int key:col.keySet()) set.add(col.get(key)); long len = set.size(); long ans = 1; for(int i = 1 ; i<=len ; i++) { ans = (ans * k)%mod; } ans %= mod; sb.append(ans+"\n"); } } /*******************************************************************************************************************************************************/ /** */
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 11
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
40cb6aa1f210613e30cc19091664b044
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.*; public class Solution { static int mod=1000000007; 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) { int start=(int) System.currentTimeMillis(); FastReader sc = new FastReader(); int tt=1; // tt = sc.nextInt(); // while (tt-->0) { int n=sc.nextInt(); int m=sc.nextInt(); int k=sc.nextInt(); int q=sc.nextInt(); int query[][]=new int[q][2]; for(int i=0;i<q;i++) { query[i][0]=sc.nextInt(); query[i][1]=sc.nextInt(); } HashSet<Integer>setx=new HashSet<>(); HashSet<Integer>sety=new HashSet<>(); int a=0; for(int i=q-1;i>=0;i--) { boolean pure=false; if(!setx.contains(query[i][0])) { setx.add(query[i][0]); pure=true; } if(!sety.contains(query[i][1])) { sety.add(query[i][1]); pure=true; } if(pure) { a++; } if(setx.size()==n||sety.size()==m)break; } long ans=modulo(k,a,998244353); System.out.println(ans); //while } // int end=(int) System.currentTimeMillis(); // end-=start; // System.out.println(); // System.out.println(); // System.out.println("time : "+end); //main } static long modulo(long a,long b,int n) { long res=1; while(b>0) { if((b&1)==1) { res=(res*(a%n))%n; } a=((a%n)*(a%n))%n; b=b>>1; } return res; } //class }
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 11
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
7559b8f7e786a00ffb6b63c20643f113
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 Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]),k=Integer.parseInt(s[2]),q=Integer.parseInt(s[3]); int i,c[][]=new int[q][2]; for(i=0;i<q;i++) { s=bu.readLine().split(" "); int x=Integer.parseInt(s[0]),y=Integer.parseInt(s[1]); c[i][0]=x; c[i][1]=y; } long ans=1,M=998244353; Set<Integer> x=new HashSet<>(),y=new HashSet<>(); for(i=q-1;i>=0;i--) { boolean okrow=y.size()!=m && !x.contains(c[i][0]); boolean okcol=x.size()!=n && !y.contains(c[i][1]); if(okrow || okcol) ans=ans*k%M; x.add(c[i][0]); y.add(c[i][1]); } sb.append(ans+"\n"); } System.out.print(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 11
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
599826bf2b2a7ab584f6856aaa3d6f85
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.text.DecimalFormat; import java.io.*; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static DecimalFormat df = new DecimalFormat("0.0000000"); final static int mod = 998244353 ; final static int MAX = Integer.MAX_VALUE; final static int MIN = Integer.MIN_VALUE; // ======================= MAIN ================================== public static void main(String[] args) throws IOException { int t=readInt(); while(t-->0){ int n=readInt(); int m=readInt(); int k=readInt(); int q=readInt(); int[][] query=new int[q][2]; for(int i=0;i<q;i++){ for(int j=0;j<2;j++) query[i][j]=readInt(); } Set<Integer> row=new HashSet<>(),col=new HashSet<>(); long ans=1l; for(int i=q-1;i>=0;i--){ boolean notPresent=false; if(!row.contains(query[i][0])){ notPresent=true; row.add(query[i][0]); } if(!col.contains(query[i][1])){ notPresent=true; col.add(query[i][1]); } if(notPresent) ans=(ans*k)%mod; if(row.size()==n || col.size()==m) break; } out.println(ans); } out.flush(); } private static void preprocess() { } // ======================= FOR INPUT ================================== static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readString() throws IOException { return next(); } static String readLine() throws IOException { return br.readLine().trim(); } static int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = readInt(); return arr; } static long[] readLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = readLong(); return arr; } // ========================= FOR OUTPUT ================================== private static void printIList(List<Integer> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printLList(List<Long> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printIArray(int[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void printIArray(int[][] arr) { for (int i = 0; i < arr.length; i++) printIArray(arr[i]); } private static void printLArray(long[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } // ====================== TO CHECK IF STRING IS NUMBER ======================== private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } private static boolean isLong(String s) { try { Long.parseLong(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } // ==================== FASTER SORT ================================ private static void sort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void sort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // ==================== MATHEMATICAL FUNCTIONS =========================== private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static int mod_power(int a, int b) { if (b == 0) return 1; int temp = mod_power(a, b / 2); temp %= mod; temp = (int) ((1L * temp * temp) % mod); if ((b & 1) == 1) temp = (int) ((1L * temp * a) % mod); return temp; } private static int multiply(int a, int b) { return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod); } private static boolean isPrime(long n) { for (long i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } // ==================== Primes using Seive ===================== private static List<Integer> SeivePrime(int n) { boolean[] prime = new boolean[n + 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; } } List<Integer> list = new ArrayList<>(); for (int i = 2; i <= n; i++) if (prime[i]) list.add(i); return list; } // ==================== STRING FUNCTIONS ================================ private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } // ==================== LIS & LNDS ================================ private static int LIS(int arr[], int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) >= val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } // ==================== UNION FIND ===================== private static int find(int x, int[] parent) { if (parent[x] == x) return x; return parent[x] = find(parent[x], parent); } private static boolean union(int x, int y, int[] parent, int[] rank) { int lx = find(x, parent), ly = find(y, parent); if (lx == ly) return true; if (rank[lx] > rank[ly]) parent[ly] = lx; else if (rank[lx] < rank[ly]) parent[lx] = ly; else { parent[lx] = ly; rank[ly]++; } return false; } // ==================== SEGMENT TREE (RANGE SUM) ===================== public static class SegmentTree { int n; int[] arr, tree, lazy; SegmentTree(int arr[]) { this.arr = arr; this.n = arr.length; this.tree = new int[(n << 2)]; this.lazy = new int[(n << 2)]; build(1, 0, n - 1); } void build(int id, int start, int end) { if (start == end) tree[id] = arr[start]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; build(left, start, mid); build(right, mid + 1, end); tree[id] = tree[left] + tree[right]; } } void update(int l, int r, int val) { update(1, 0, n - 1, l, r, val); } void update(int id, int start, int end, int l, int r, int val) { distribute(id, start, end); if (end < l || r < start) return; if (start == end) tree[id] += val; else if (l <= start && end <= r) { lazy[id] += val; distribute(id, start, end); } else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; update(left, start, mid, l, r, val); update(right, mid + 1, end, l, r, val); tree[id] = tree[left] + tree[right]; } } int query(int l, int r) { return query(1, 0, n - 1, l, r); } int query(int id, int start, int end, int l, int r) { if (end < l || r < start) return 0; distribute(id, start, end); if (start == end) return tree[id]; else if (l <= start && end <= r) return tree[id]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r); } } void distribute(int id, int start, int end) { if (start == end) tree[id] += lazy[id]; else { tree[id] += lazy[id] * (end - start + 1); lazy[(id << 1)] += lazy[id]; lazy[(id << 1) + 1] += lazy[id]; } lazy[id] = 0; } } // ==================== TRIE ================================ static class Trie { class Node { Node[] children; boolean isEnd; Node() { children = new Node[26]; } } Node root; Trie() { root = new Node(); } public void insert(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) curr.children[ch - 'a'] = new Node(); curr = curr.children[ch - 'a']; } curr.isEnd = true; } public boolean find(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) return false; curr = curr.children[ch - 'a']; } return curr.isEnd; } } // ==================== FENWICK TREE ================================ static class FT { long[] tree; int n; FT(int[] arr, int n) { this.n = n; this.tree = new long[n + 1]; for (int i = 1; i <= n; i++) { update(i, arr[i - 1]); } } void update(int idx, int val) { while (idx <= n) { tree[idx] += val; idx += idx & -idx; } } long query(int l, int r) { return getSum(r) - getSum(l - 1); } long getSum(int idx) { long ans = 0L; while (idx > 0) { ans += tree[idx]; idx -= idx & -idx; } return ans; } } // ==================== BINARY INDEX TREE ================================ static class BIT { long[][] tree; int n, m; BIT(int[][] mat, int n, int m) { this.n = n; this.m = m; tree = new long[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { update(i, j, mat[i - 1][j - 1]); } } } void update(int x, int y, int val) { while (x <= n) { int t = y; while (t <= m) { tree[x][t] += val; t += t & -t; } x += x & -x; } } long query(int x1, int y1, int x2, int y2) { return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1); } long getSum(int x, int y) { long ans = 0L; while (x > 0) { int t = y; while (t > 0) { ans += tree[x][t]; t -= t & -t; } x -= x & -x; } return ans; } } // ==================== OTHER CLASSES ================================ static class Pair implements Comparable<Pair> { int first, second; Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair o) { return this.first - o.first; } } static class DequeNode { DequeNode prev, next; int val; DequeNode(int val) { this.val = val; } DequeNode(int val, DequeNode prev, DequeNode next) { this.val = val; this.prev = prev; this.next = 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 11
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
658bf395cbab80cbdda35aee01077fe9
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 CodeForces { /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/ public static void solve(int tCase) throws IOException { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int q = sc.nextInt(); int[][] arr = new int[q][2]; for(int i=0;i<q;i++)arr[i] = new int[]{sc.nextInt(),sc.nextInt()}; Set<Integer> row = new HashSet<>(); Set<Integer> col = new HashSet<>(); int dist = 0; for(int i=q-1;i>=0;i--){ int x = arr[i][0],y = arr[i][1]; boolean isRowCovered = false; boolean isColCovered = false; if(row.contains(x) || col.size()>=m)isRowCovered = true; if(col.contains(y) || row.size()>=n)isColCovered = true; if(isColCovered && isRowCovered)continue; dist++; row.add(x); col.add(y); } out.println(_modExpo(k,dist)); } public static void main(String[] args) throws IOException { openIO(); int testCase = 1; testCase = sc. nextInt(); for (int i = 1; i <= testCase; i++) solve(i); closeIO(); } /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/ /*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/ // public static int mod = (int) 1e9 + 7; public static int mod = 998244353; public static int inf_int = (int) 2e9; public static long inf_long = (long) 2e18; public static void _sort(int[] arr, boolean isAscending) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } public static void _sort(long[] arr, boolean isAscending) { int n = arr.length; List<Long> list = new ArrayList<>(); for (long ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // time : O(1), space : O(1) public static int _digitCount(long num,int base){ // this will give the # of digits needed for a number num in format : base return (int)(1 + Math.log(num)/Math.log(base)); } // time : O(n), space: O(n) public static long _fact(int n){ // simple factorial calculator long ans = 1; for(int i=2;i<=n;i++) ans = ans * i % mod; return ans; } // time for pre-computation of factorial and inverse-factorial table : O(nlog(mod)) public static long[] factorial , inverseFact; public static void _ncr_precompute(int n){ factorial = new long[n+1]; inverseFact = new long[n+1]; factorial[0] = inverseFact[0] = 1; for (int i = 1; i <=n; i++) { factorial[i] = (factorial[i - 1] * i) % mod; inverseFact[i] = _modExpo(factorial[i], mod - 2); } } // time of factorial calculation after pre-computation is O(1) public static int _ncr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod); } public static int _npr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[n - r] % mod); } // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { while (a>0){ long x = a; a = b % a; b = x; } return b; // if (a == 0) // return b; // return _gcd(b % a, a); } // lcm(a,b) * gcd(a,b) = a * b public static long _lcm(long a, long b) { return (a / _gcd(a, b)) * b; } // binary exponentiation time O(logn) public static long _modExpo(long x, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans *= x; ans %= mod; n--; } else { x *= x; x %= mod; n >>= 1; } } return ans; } // function to find a/b under modulo mod. time : O(logn) public static long _modInv(long a,long b){ return (a * _modExpo(b,mod-2)) % mod; } //sieve or first divisor time : O(mx * log ( log (mx) ) ) public static int[] _seive(int mx){ int[] firstDivisor = new int[mx+1]; for(int i=0;i<=mx;i++)firstDivisor[i] = i; for(int i=2;i*i<=mx;i++) if(firstDivisor[i] == i) for(int j = i*i;j<=mx;j+=i) firstDivisor[j] = i; return firstDivisor; } // check if x is a prime # of not. time : O( n ^ 1/2 ) private static boolean _isPrime(long x){ for(long i=2;i*i<=x;i++) if(x%i==0)return false; return true; } static class Pair<K, V>{ K ff; V ss; public Pair(K ff, V ss) { this.ff = ff; this.ss = ss; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return ff.equals(pair.ff) && ss.equals(pair.ss); } @Override public int hashCode() { return Objects.hash(ff, ss); } @Override public String toString(){ return ff.toString()+" "+ss.toString(); } } /*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/ /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/ static FastestReader sc; static PrintWriter out; private static void openIO() throws IOException { sc = new FastestReader(); out = new PrintWriter(System.out); } public static void closeIO() throws IOException { out.flush(); out.close(); sc.close(); } private static final class FastestReader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public FastestReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastestReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() throws IOException { int b; //noinspection StatementWithEmptyBody while ((b = read()) != -1 && isSpaceChar(b)) { } return b; } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final 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(); } final 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(); } final 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 { din.close(); } } /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/ }
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 11
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
15653e67189cc56562048c9175550294
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
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Just have Patience + 1... */ import java.util.*; import java.lang.*; import java.io.*; public class Solution { static class Query { int row; int col; Query(int row, int col) { this.row = row; this.col = col; } } static int MOD = 998244353; public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = sc.nextInt(); for (int t = 1; t <= test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); int m = sc.nextInt(); long k = sc.nextLong(); int q = sc.nextInt(); List<Query> queries = new ArrayList<>(); for (int i = 0; i < q; i++) { int row = sc.nextInt(); int col = sc.nextInt(); queries.add(new Query(row, col)); } Collections.reverse(queries); Map<Integer, Integer> mapX = new HashMap<>(); Map<Integer, Integer> mapY = new HashMap<>(); long count = 0; for (int i = 0; i < q; i++) { int currRow = queries.get(i).row; int currCol = queries.get(i).col; if (mapX.containsKey(currRow) && mapY.containsKey(currCol)) { continue; } if (mapX.size() == n || mapY.size() == m) { continue; } count++; mapX.put(currRow, mapX.getOrDefault(currRow, 0) + 1); mapY.put(currCol, mapY.getOrDefault(currCol, 0) + 1); } out.println(power(k, count)); } private static long power(long a ,long b) { long res = 1; a %= MOD; if (a == 0) { return 0; } while (b > 0) { if ((b & 1) == 1) { res *= a; res %= MOD; } b >>= 1; a *= a; a %= MOD; } return res; } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.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 lastMonthOfVacation) { lastMonthOfVacation.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 11
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
bb6cab901e374d61b2ea16d605643b3e
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 Solution { private static class FastIO { private static class FastReader { BufferedReader br; StringTokenizer st; 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; } } private static PrintWriter out = new PrintWriter(System.out); private static FastReader in = new FastReader(); public void print(String s) {out.print(s);} public void println(String s) {out.println(s);} public void println() { println(""); } public void print(int i) {out.print(i);} public void print(long i) {out.print(i);} public void print(char i) {out.print(i);} public void print(double i) {out.print(i);} public void println(int i) {out.println(i);} public void println(long i) {out.println(i);} public void println(char i) {out.println(i);} public void println(double i) {out.println(i);} public void printIntArrayWithoutSpaces(int[] a) { for(int i : a) { out.print(i); } out.println(); } public void printIntArrayWithSpaces(int[] a) { for(int i : a) { out.print(i + " "); } out.println(); } public int[] getIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public static List<Integer> getIntList(int n) { List<Integer> list = new ArrayList<>(); for(int i = 0; i < n; i++) { list.add(in.nextInt()); } return list; } public static void printKickstartCase(int i) { out.print("Case #" + i + ": "); } public String next() {return in.next();} int nextInt() { return in.nextInt(); } char nextChar() {return in.next().charAt(0);} long nextLong() { return in.nextLong(); } double nextDouble() { return in.nextDouble(); } String nextLine() {return in.nextLine();} public void close() { out.flush(); out.close(); } } private static final FastIO io = new FastIO(); private static class MathUtil { public static final int MOD = 1000000007; public static int gcd(int a, int b) { if(b == 0) { return a; } return gcd(b, a % b); } public static int gcd(int[] a) { if(a.length == 0) { return 0; } int res = a[0]; for(int i = 1; i < a.length; i++) { res = gcd(res, a[i]); } return res; } public static int gcd(List<Integer> a) { if(a.size() == 0) { return 0; } int res = a.get(0); for(int i = 1; i < a.size(); i++) { res = gcd(res, a.get(i)); } return res; } public static int modular_mult(int a, int b, int M) { long res = (long)a * b; return (int)(res % M); } public static int modular_mult(int a, int b) { return modular_mult(a, b, MOD); } public static int modular_add(int a, int b, int M) { long res = (long)a + b; return (int)(res % M); } public static int modular_add(int a, int b) { return modular_add(a, b, MOD); } public static int modular_sub(int a, int b, int M) { long res = ((long)a - b) + M; return (int)(res % M); } public static int modular_sub(int a, int b) { return modular_mult(a, b, MOD); } //public static int modular_div(int a, int b, int M) {} //public static int modular_div(int a, int b) {return modular_div(a, b, MOD);} public static int pow(int a, int b, int M) { int res = 1; while (b > 0) { if ((b & 1) == 1) { res = modular_mult(res, a, M); } a = modular_mult(a, a, M); b = b >> 1; } return res; } public static int pow(int a, int b) { return pow(a, b, MOD); } /*public static int fact(int i, int M) { } public static int fact(int i) { } public static void preComputeFact(int i) { } public static int mod_mult_inverse(int den, int mod) { } public static void C(int n, int r) { }*/ } private static final int M = 1000000007; private static final String yes = "YES"; private static final String no = "NO"; private static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } public static void main(String[] args) { int t = io.nextInt(); //int t = 1; for(int z = 0; z < t; z ++) { int n = io.nextInt(); int m = io.nextInt(); int k = io.nextInt(); int q = io.nextInt(); List<Pair> list = new ArrayList<>(); for(int i = 0; i < q; i++) { list.add(new Pair(io.nextInt(), io.nextInt())); } Set<Integer> x_set = new HashSet<>(); Set<Integer> y_set = new HashSet<>(); int count = q; Pair last_pair = list.get(q - 1); x_set.add(last_pair.x); y_set.add(last_pair.y); for(int i = q - 2; i >= 0; i--) { int cur_x = list.get(i).x; int cur_y = list.get(i).y; boolean row_blocked = false; boolean column_blocked = false; //checking if row is blocked if(x_set.contains(cur_x) || y_set.size() == m) { row_blocked = true; } //checking if column is blocked if(y_set.contains(cur_y) || x_set.size() == n) { column_blocked = true; } if(row_blocked && column_blocked) { count --; } x_set.add(cur_x); y_set.add(cur_y); } //io.println("k: " + k + " count: " + count); io.println(MathUtil.pow(k, count, 998244353)); } io.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 11
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
62b63a824cd5338e9a9eb338b2cabb8f
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 { public static void main(String[] args) throws IOException { Scanner scn = new Scanner(System.in); OutputWriter out = new OutputWriter(System.out); // Always print a trailing "\n" and close the OutputWriter as shown at the end of your output // example: int t = scn.nextInt();long p=998244353; for(int i1=0;i1<t;i1++){ int n=scn.nextInt();int m=scn.nextInt();long k=scn.nextInt();int q=scn.nextInt(); int[] a=new int[q]; int[] b=new int[q]; for(int i=0;i<q;i++){ a[i]=scn.nextInt();b[i]=scn.nextInt(); } int cnt=0; Set<Integer> sr=new HashSet<Integer>(); Set<Integer> sc=new HashSet<Integer>(); for(int i=q-1;i>=0;i--){ int tog1=0;int tog2=0; if((sr.contains(a[i]))||(sc.size()==m)){ tog1=1; } if((sc.contains(b[i]))||(sr.size()==n)){ tog2=1; } if((tog1+tog2)<2){ cnt++; } sr.add(a[i]);sc.add(b[i]); } long ans=power(k,cnt,p); out.print(ans+"\n"); } out.close(); } static long power(long x, int y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // fast input static class Scanner { public BufferedReader reader; public StringTokenizer tokenizer; public Scanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) return null; tokenizer = new StringTokenizer(line); } catch (Exception e) { throw(new RuntimeException()); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } // fast output static class OutputWriter { BufferedWriter writer; public OutputWriter(OutputStream stream) { writer = new BufferedWriter(new OutputStreamWriter(stream)); } public void print(int i) throws IOException { writer.write(i); } public void print(String s) throws IOException { writer.write(s); } public void print(char[] c) throws IOException { writer.write(c); } public void close() throws IOException { writer.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 11
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
b954a4f397177a8382f511c0cb071aa7
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.*; public class Main{ static class Node{ int x, y; Node(int x, int y){ this.x = x; this.y = y; } } public static void process(int t)throws IOException { int n = ni(); int m = ni(); int k = ni(); int q = ni(); Node[]col = new Node[q]; HashSet<Integer> hor = new HashSet<>(); HashSet<Integer> ver = new HashSet<>(); for(int i=0;i<q;i++){ col[i] = new Node(ni(), ni()); } int cnt = q; for(int i=q-1;i>=0;i--){ int x = col[i].x; int y = col[i].y; int flag = 0; if(hor.size() == n || ver.size() == m){ flag = 1; } if(hor.contains(x) && ver.contains(y)){ flag = 1; } if(flag == 1) cnt--; hor.add(x); ver.add(y); } long ans = 1; for(int i=0;i<cnt;i++){ ans = (ans * k) % mod; } pn(ans); } static long mod = 998244353l; static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; t=ni(); while(t-- > 0) {process(t);} out.flush();out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ 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 11
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
c6ce6e1b26ef248a336c657a5c782565
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 _1644_D { static final long MOD = 998244353; 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 line = new StringTokenizer(in.readLine()); int n = Integer.parseInt(line.nextToken()); int m = Integer.parseInt(line.nextToken()); int k = Integer.parseInt(line.nextToken()); int q = Integer.parseInt(line.nextToken()); int[][] ops = new int[q][2]; for(int i = 0; i < q; i++) { line = new StringTokenizer(in.readLine()); ops[i][0] = Integer.parseInt(line.nextToken()); ops[i][1] = Integer.parseInt(line.nextToken()); } HashSet<Integer> x = new HashSet<Integer>(); HashSet<Integer> y = new HashSet<Integer>(); long res = 1; for(int i = q - 1; i >= 0; i--) { if(x.size() == n || y.size() == m) { break; } boolean visible = false; if(!x.contains(ops[i][0])) { x.add(ops[i][0]); visible = true; } if(!y.contains(ops[i][1])) { y.add(ops[i][1]); visible = true; } if(visible) { res = modmult(res, k); } } out.println(res); } in.close(); out.close(); } static long modadd(long a, long b) { return (a + b + MOD) % MOD; } static long modmult(long a, long b) { return a * b % MOD; } }
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 11
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
4d4324b466db9f675f8631876caed321
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 FastScanner sc = new FastScanner(System.in); static PrintWriter pw = new PrintWriter(System.out); static StringBuilder sb = new StringBuilder(); static long mod = 998244353; public static void main(String[] args) throws Exception { int t = sc.nextInt(); for(int i = 0; i < t; i++) solve(); pw.flush(); } public static void solve() { long n = sc.nextLong(); long m = sc.nextLong(); long k = sc.nextLong(); int q = sc.nextInt(); ArrayList<int[]> arr = new ArrayList<>(); for(int i = 0; i < q; i++){ arr.add(new int[]{sc.nextInt(),sc.nextInt()}); } HashSet<Integer> setR = new HashSet<>(); HashSet<Integer> setC = new HashSet<>(); long ans = 1; for(int i = q-1; i >= 0; i--){ int[] now = arr.get(i); int R = now[0]; int C = now[1]; boolean ok = false; if(setR.size() != n && !setC.contains(C)){ ok = true; } if(setC.size() != m && !setR.contains(R)){ ok = true; } if(ok){ ans *= k; ans %= mod; } setR.add(R); setC.add(C); } pw.println(ans); } static class GeekInteger { public static void save_sort(int[] array) { shuffle(array); Arrays.sort(array); } public static int[] shuffle(int[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); int randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } public static void save_sort(long[] array) { shuffle(array); Arrays.sort(array); } public static long[] shuffle(long[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); long randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } } } class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public FastScanner(FileReader in) { reader = new BufferedReader(in); tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String[] nextArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } }
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 11
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
3ae7f9feac49857c7fe89959cd1a3955
train_108.jsonl
1645540500
Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves: D — move one cell down; R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
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(); String s = s(); int x2 = 0; int y2 = 0; boolean hasd = false; boolean hasr = false; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'R') { x2++; hasr = true; } else { y2++; hasd = true; } } if (hasr && hasd) { hasd = false; hasr = false; long ans = s.length(); for (int i = 0; i < s.length(); i++) { int rrem = n - 1 - x2; int drem = n - 1 - y2; if (s.charAt(i) == 'R') { hasr = true; } else { hasd = true; } if (i == s.length() - 1) { ans += (long) (rrem + 1) * (drem + 1); } else if (s.charAt(i) == s.charAt(i + 1)) { if (s.charAt(i) == 'R') { if (hasd) { ans += drem; } } else { if (hasr) { ans += rrem; } } } else { if (s.charAt(i) == 'R') { ans += rrem; } else { ans += drem; } } } out.println(ans); } else { out.println(n); } } // (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
["3\n\n4\n\nRD\n\n5\n\nDRDRDRDR\n\n3\n\nD"]
2 seconds
["13\n9\n3"]
NoteIn the first testcase, it's enough to consider the following modified paths: RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$; RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$; RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:
Java 8
standard input
[ "brute force", "combinatorics", "data structures", "implementation", "math" ]
113a43af2f1c5303f83eb842ef532040
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
standard output
PASSED
74c968afa993cda37964f17067171dbb
train_108.jsonl
1645540500
Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves: D — move one cell down; R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
256 megabytes
import java.util.*; import java.io.*; import javafx.util.*; public class Solution { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { 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(); } } static int st[]; static int sz = 1; static int max(int l , int r) { return max(0,sz-1,l,r,0); } static int max(int lx , int rx , int l , int r , int x) { if(lx > r || rx < l) return -1; if(lx >= l && rx <= r) return st[x]; int mid = (lx+rx)/2; return Math.max(max(lx,mid,l,r,2*x+1),max(mid+1,rx,l,r,2*x+2)); } static void update(int i , int v) { update(0,sz-1,i,v,0); } static void update(int lx , int rx , int i , int v , int x) { if(i < lx || i > rx) return; if(lx == rx) { st[x] = v; return; } int mid = (lx+rx)/2; update(lx,mid,i,v,2*x+1); update(mid+1,rx,i,v,2*x+2); st[x] = Math.max(st[2*x+1],st[2*x+2]); } static void change(int l , int r , int v, long ans[]) { if(l > r) return; ans[l] += v; if(r+1 > ans.length-1) return; ans[r+1] -= v; } static long mod = 1000000007; static long pow(long a , long b) { if(b == 0) return 1; long ans = pow(a,b/2); if(b%2 == 0) return ans*ans%mod; return ans*ans%mod*a%mod; } //static int dp[][]; //static int public static void main(String []args) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); sc.nextLine(); String s = sc.nextLine(); // s += '#'; boolean bl = true; for(int i = 1 ; i < s.length() ; i++) { if(s.charAt(i) != s.charAt(0)) bl = false; } if(bl) System.out.println(n); else { int x = 1 , y = 1; int eq[] = new int[s.length()]; int pos = 0; while(pos < s.length()) { int j = pos; while(j+1 < s.length() && s.charAt(j) == s.charAt(j+1)) { j++; } for(int k = pos ; k <= j ; k++) { eq[k] = j; } pos = j+1; } int postx[] = new int[s.length()]; int posty[] = new int[s.length()]; for(int i = s.length()-1 ; i >= 0 ; i--) { if(i != s.length()-1) { postx[i] = postx[i+1]; posty[i] = posty[i+1]; } if(s.charAt(i) == 'D') postx[i]++; else posty[i]++; } long ans = s.length()+1; for(int i = 0 ; i < s.length()-1 ; i++) { if(s.charAt(i) == 'D') x++; else y++; if(s.charAt(i) == s.charAt(i+1)) continue; if(s.charAt(i) == 'D') ans += (long)(n-(x+postx[i+1]))*(long)(eq[i+1]-i); else ans += (long)(n-(y+posty[i+1]))*(long)(eq[i+1]-i); } if(s.charAt(s.length()-1) == 'R') y++; else x++; ans += -1+(long)(n-x+1)*(long)(n-y+1); System.out.println(ans); } } } }
Java
["3\n\n4\n\nRD\n\n5\n\nDRDRDRDR\n\n3\n\nD"]
2 seconds
["13\n9\n3"]
NoteIn the first testcase, it's enough to consider the following modified paths: RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$; RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$; RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:
Java 8
standard input
[ "brute force", "combinatorics", "data structures", "implementation", "math" ]
113a43af2f1c5303f83eb842ef532040
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
standard output
PASSED
f7478bba38643bc61326733484fd4cf6
train_108.jsonl
1645540500
Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves: D — move one cell down; R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { mod=998244353; int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); char[] s=sc.next().toCharArray(); int d=0; int r=0; for(char i:s){ if(i=='D'){ d++; }else{ r++; } } if(r*d==0){ pw.println(n); }else{ boolean found1=false; boolean found2=false; long ans=0; int x=1; int y=1; int incx=0; int incy=0; for(char i:s){ if(i=='D'){ x++; ans-=y-1; if(i=='D'&&!found1){ found1=true; incx=n-1-d; x+=incx; ans-=(incx)*1l*(y-1); } }else{ y++; } } x=1; y=1; for(char i:s){ if(i=='D'){ x++; ans+=(y); }else{ y++; if(i=='R'&&!found2){ found2=true; incy=n-1-r; y+=incy; } } } ans+=(n-x+1)*1l*(y); pw.println(ans); } } pw.close(); } static long Pow(long a, long e, long mod) // O(log e) { a %= mod; long res = 1l; while (e > 0) { if ((e & 1) == 1) res = (res * a) % mod; a = (a * a) % mod; e >>= 1l; } return res; } 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(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
Java
["3\n\n4\n\nRD\n\n5\n\nDRDRDRDR\n\n3\n\nD"]
2 seconds
["13\n9\n3"]
NoteIn the first testcase, it's enough to consider the following modified paths: RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$; RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$; RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:
Java 8
standard input
[ "brute force", "combinatorics", "data structures", "implementation", "math" ]
113a43af2f1c5303f83eb842ef532040
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
standard output
PASSED
6df0138ee40ddb9ec6c523fe80d590d9
train_108.jsonl
1645540500
Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves: D — move one cell down; R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
256 megabytes
import java.io.*; import java.util.*; public class Main { static Main2 admin = new Main2(); public static void main(String[] args) { admin.start(); } } class Main2 { //---------------------------------INPUT READER-----------------------------------------// public BufferedReader br; StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine());} catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long n) {int[]ret=new int[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} long[] nal(long n) {long[]ret=new long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} Integer[] nA(long n) {Integer[]ret=new Integer[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} Long[] nAl(long n) {Long[]ret=new Long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} //--------------------------------------PRINTER------------------------------------------// PrintWriter w; void p(int i) {w.println(i);} void p(long l) {w.println(l);} void p(double d) {w.println(d);} void p(String s) { w.println(s);} void pr(int i) {w.print(i);} void pr(long l) {w.print(l);} void pr(double d) {w.print(d);} void pr(String s) { w.print(s);} void pl() {w.println();} //--------------------------------------VARIABLES-----------------------------------------// long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; long mod = 1000000007; { w = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); try {if(new File(System.getProperty("user.dir")).getName().equals("LOCAL")) { w = new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))); br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));} } catch (Exception ignore) { } } //----------------------START---------------------// void start() { int t = ni(); while(t-- > 0) solve(); w.close(); } long sum(long a, long n, long d) { return ((n)*((2*a)+(n-1)*d))/2; } void solve() { int n = ni(); String str = ns(); char[] strr = str.toCharArray(); int len = strr.length; int r_ct = 0, d_ct = 0; for(char ch: strr) if(ch == 'R') r_ct++; else d_ct++; int rem_r = n-1-r_ct, rem_d = n-1-d_ct; if(r_ct == 0 || d_ct == 0) {p(n); return;} long ans = (long)n*n; int[] d_pre = new int[len]; int[] r_pre = new int[len]; for(int i = 0; i < len; i++) { if(i == 0) { if(strr[i] == 'R') r_pre[i]++; else d_pre[i]++; } else { r_pre[i] = r_pre[i-1]; d_pre[i] = d_pre[i-1]; if(strr[i] == 'R') r_pre[i]++; else d_pre[i]++; } } for(int i = len-1; i >= 0; i--) { if(strr[i] == 'R') { if(i!=0 && r_pre[i-1] == 0) { ans -= (long)d_pre[i]*rem_r; } ans -= d_pre[i]; } else { if(i!=0 && d_pre[i-1] == 0) { ans -= (long)r_pre[i]*rem_d; } ans -= r_pre[i]; } } p(ans); } }
Java
["3\n\n4\n\nRD\n\n5\n\nDRDRDRDR\n\n3\n\nD"]
2 seconds
["13\n9\n3"]
NoteIn the first testcase, it's enough to consider the following modified paths: RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$; RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$; RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:
Java 8
standard input
[ "brute force", "combinatorics", "data structures", "implementation", "math" ]
113a43af2f1c5303f83eb842ef532040
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
standard output
PASSED
6bb87a90d7d39db38a1cc02947c50723
train_108.jsonl
1645540500
Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves: D — move one cell down; R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
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 x1644E { 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 X = Integer.parseInt(st.nextToken()); char[] arr = infile.readLine().trim().toCharArray(); int N = arr.length; boolean same = true; for(int i=1; i < N; i++) same &= arr[i] == arr[0]; if(same) { sb.append(X+"\n"); continue; } long res = (long)X*X; //bottom left res -= calc(N, arr, X); //System.out.println("! "+calc(N, arr, X)); //top right for(int i=0; i < N; i++) arr[i] = (char)('R'+'D'-arr[i]); res -= calc(N, arr, X); //System.out.println("! "+calc(N, arr, X)); sb.append(res+"\n"); } System.out.print(sb); } public static long calc(int N, char[] arr, int X) { long res = 0L; int dex = -1; for(int i=0; i < N; i++) { if(arr[i] == 'D') { dex = i; break; } res += X-1; } int rcnt = 0; for(int i=dex; i < N; i++) if(arr[i] == 'R') rcnt++; for(int i=N-1; i >= dex; i--) { if(arr[i] == 'R') rcnt--; else res += rcnt; } return res; } }
Java
["3\n\n4\n\nRD\n\n5\n\nDRDRDRDR\n\n3\n\nD"]
2 seconds
["13\n9\n3"]
NoteIn the first testcase, it's enough to consider the following modified paths: RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$; RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$; RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:
Java 8
standard input
[ "brute force", "combinatorics", "data structures", "implementation", "math" ]
113a43af2f1c5303f83eb842ef532040
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
standard output
PASSED
337d89695eab9bd9ac569d759f205779
train_108.jsonl
1645540500
Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves: D — move one cell down; R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
256 megabytes
import java.util.*; import java.io.*; // BEFORE 31ST MARCH 2022 !! //MAX RATING EVER ACHIEVED-1622(LETS SEE WHEN WILL I GET TO CHANGE THIS) ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class E_Expand_the_Path{ public static void main(String[] args) { FastScanner s= new FastScanner(); //PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ long n=s.nextLong(); String str=s.nextToken(); ArrayList<Long> list = new ArrayList<Long>(); int start=0; //0=> for D //1 => for R if(str.charAt(0)=='R'){ start=1; } long rcount=0; long dcount=0; char ch='D'; if(start==1){ ch='R'; } long yo=0; long x=1; long y=1; for(int i=0;i<str.length();i++){ char ch2=str.charAt(i); if(ch2=='R'){ rcount++; x++; } else{ dcount++; y++; } if(ch2==ch){ yo++; } else{ // System.out.println("yo "+ yo); list.add(yo); ch=ch2; yo=1; } } // System.out.println("yo "+yo); list.add(yo); long length=str.length(); long r=n-rcount-1; long d=n-dcount-1; long ans=length; if(list.size()==1){ res.append(n+" \n"); } else{ if(str.charAt(str.length()-1)=='R'){ x-=list.get(list.size()-1); } else{ y-=list.get(list.size()-1); } long yoyo=(n-x+1L)*(n-y+1L); ans+=yoyo; for(int i=list.size()-3;i>=0;i--){ if(start==0){ // D is present at even index //R is present at odd index if(i%2==0){ long hh=(d*list.get(i+1)); ans+=hh; } else{ long hh=(r*list.get(i+1)); ans+=hh; } } else{ // R is present at even index //D is present at odd index if(i%2==0){ long hh=(r*list.get(i+1)); ans+=hh; } else{ long hh=(d*list.get(i+1)); ans+=hh; } } } long well=list.get(list.size()-1); ans-=well; res.append(ans+" \n"); } p++; } System.out.println(res); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> 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 * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
Java
["3\n\n4\n\nRD\n\n5\n\nDRDRDRDR\n\n3\n\nD"]
2 seconds
["13\n9\n3"]
NoteIn the first testcase, it's enough to consider the following modified paths: RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$; RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$; RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:
Java 8
standard input
[ "brute force", "combinatorics", "data structures", "implementation", "math" ]
113a43af2f1c5303f83eb842ef532040
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
standard output
PASSED
9e78ba22a46286e2bb58049c7b588144
train_108.jsonl
1645540500
Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves: D — move one cell down; R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
256 megabytes
import java.util.*; import java.io.*; public class E1644 { 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(); char[] s = sc.next().toCharArray(); int sumR = 0; int sumD = 0; for (char c : s) { if (c == 'R') sumR++; else sumD++; } long ans = s.length + 1; for (int i = 0; i < s.length; i++) { if (s[i] == 'R') { ans += 1l * (n - sumR - 1) * (sumD + 1 - i); break; } } // pw.println(ans); for (int i = 0; i < s.length; i++) { if (s[i] == 'D') { ans += 1l * (n - sumD - 1) * (sumR + 1 - i); break; } } // pw.println(ans); if (sumD != 0 && sumR != 0) ans += 1l * (n - sumR - 1) * (n - sumD - 1); pw.println(ans); } 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
["3\n\n4\n\nRD\n\n5\n\nDRDRDRDR\n\n3\n\nD"]
2 seconds
["13\n9\n3"]
NoteIn the first testcase, it's enough to consider the following modified paths: RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$; RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$; RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:
Java 8
standard input
[ "brute force", "combinatorics", "data structures", "implementation", "math" ]
113a43af2f1c5303f83eb842ef532040
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
standard output
PASSED
9bf9cb31e1a254327841fc49d3a2e25a
train_108.jsonl
1645540500
Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves: D — move one cell down; R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
256 megabytes
import java.util.*; import java.io.*; public class E { 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 t = Integer.parseInt(br.readLine()); while (t --> 0) { long n = Long.parseLong(br.readLine()); String s = br.readLine(); int r = 0; int d = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'R') r++; else d++; } if (r == 0 || d == 0) pw.println(n); else { int fr = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'D') break; fr++; } int fd = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'R') break; fd++; } long ans = (r + d + 1) + (n - r - 1) * (n - d - 1); ans += (r - fr + 1) * (n - d - 1) + (d - fd + 1) * (n - r - 1); pw.println(ans); } } pw.close(); } }
Java
["3\n\n4\n\nRD\n\n5\n\nDRDRDRDR\n\n3\n\nD"]
2 seconds
["13\n9\n3"]
NoteIn the first testcase, it's enough to consider the following modified paths: RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$; RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$; RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:
Java 8
standard input
[ "brute force", "combinatorics", "data structures", "implementation", "math" ]
113a43af2f1c5303f83eb842ef532040
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
standard output