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
e116ef8eb2f12c9abe945a05369dfb33
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { static long fans[] = new long[200001]; static long inv[] = new long[200001]; static long mod = 1000000007; static void init() { fans[0] = 1; inv[0] = 1; fans[1] = 1; inv[1] = 1; for (int i = 2; i < 200001; i++) { fans[i] = ((long) i * fans[i - 1]) % mod; inv[i] = power(fans[i], mod - 2); } } static long ncr(int n, int r) { return (((fans[n] * inv[n - r]) % mod) * (inv[r])) % mod; } public static void main(String[] args) throws java.lang.Exception { FastReader in = new FastReader(System.in); StringBuilder sb = new StringBuilder(); int t = 1; t = in.nextInt(); while (t > 0) { --t; int n = in.nextInt(); int arr[][] = new int[n][3]; for(int i = 0;i<n;i++) { arr[i][0] = in.nextInt(); } for(int i = 0;i<n;i++) { arr[i][1] = in.nextInt(); arr[i][2] = i; } Arrays.sort(arr,(a,b)->{ return Integer.compare(a[0], b[0]); }); int ans[] = new int[n]; int max[] = new int[n]; for(int i = 0;i<n;i++) { if(i == 0) max[i] = arr[i][1]; else max[i] = Math.max(max[i-1], arr[i][1]); } ans[arr[n-1][2]] = 1; int cur = arr[n-1][1]; for(int i = n-2;i>=0;i--) { if(max[i]>cur) { ans[arr[i][2]] = 1; cur = Math.min(cur, arr[i][1]); } } for(int i = 0;i<n;i++) sb.append(ans[i]+""); sb.append("\n"); } System.out.print(sb); } static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = ((res % mod) * (x % mod)) % mod; // y must be even now y = y >> 1; // y = y/2 x = ((x % mod) * (x % mod)) % mod; // Change x to x^2 } return res; } static long[] generateArray(FastReader in, int n) throws IOException { long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = in.nextLong(); return arr; } static long[][] generatematrix(FastReader in, int n, int m) throws IOException { long arr[][] = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = in.nextLong(); } } return arr; } static long gcd(long a, long b) { if (a == 0) return b; else return gcd(b % a, a); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } String nextLine() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c != 10 && c != 13; c = scan()) { sb.append((char) c); } return sb.toString(); } char nextChar() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; return (char) c; } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
7512cc5be7959faad991785828d75bd6
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.*; public class S { public static int surv = 0; public static void main(String args[])throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int test = Integer.parseInt(br.readLine()); while(test > 0){ test--; int n = Integer.parseInt(br.readLine()); int a[] = new int[n]; int b[] = new int[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++){ a[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++){ b[i] = Integer.parseInt(st.nextToken()); } solve(a, b, n); } } final static int MOD = 1000000007; public static void solve(int a[], int b[], int n){ List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < n; i++){ list.add(i); } Collections.sort(list, new Comparator<Integer>(){ public int compare(Integer i1, Integer i2){ return a[i2] - a[i1]; } }); Map<Integer, List<Integer>> g = new HashMap<Integer, List<Integer>>(); for(int i = 1; i < n; i++){ if(!g.containsKey(list.get(i)))g.put(list.get(i), new ArrayList<Integer>()); g.get(list.get(i)).add(list.get(i-1)); } Collections.sort(list, new Comparator<Integer>(){ public int compare(Integer i1, Integer i2){ return b[i2] - b[i1]; } }); for(int i = 1; i < n; i++){ if(!g.containsKey(list.get(i)))g.put(list.get(i), new ArrayList<Integer>()); g.get(list.get(i)).add(list.get(i-1)); } int ans[] = new int[n]; ans[list.get(0)] = 1; dfs(g, list.get(0), ans); StringBuilder sb = new StringBuilder(); for(int i = 0; i < n; i++){ sb.append(ans[i]); } System.out.println(sb.toString()); } public static void dfs(Map<Integer, List<Integer>> g, int curr, int visited[]){ if(!g.containsKey(curr))return; for(int child : g.get(curr)){ if(visited[child] == 0){ visited[child] = 1; dfs(g, child, visited); } } } public static long powerr(long base, long exp){ if(exp < 2)return base; if(exp % 2 == 0){ long ans = powerr(base, exp/2) % MOD; ans *= ans; ans %= MOD; return ans; }else{ return (((powerr(base, exp-1)) % MOD) * base) % MOD; } } public static long power(long a, long b){ if(b == 0)return 1l; long ans = power(a, b/2); ans *= ans; ans %= MOD; if(b % 2 != 0){ ans *= a; } return ans % MOD; } public static int logLong(long a){ int ans = 0; long b = 1; while(b < a){ b*=2; ans++; } return ans; } public static void rec(int a[], int l, int r, int d, int d_map[]){ if(l > r)return; if(l == r){ d_map[a[l]] = d; return; } int max = 0; int max_ind = -1; for(int i = l; i <= r; i++){ if(a[i] > max){ max_ind = i; max = a[i]; } } d_map[a[max_ind]] = d; rec(a, l, max_ind - 1, d+1, d_map); rec(a, max_ind + 1, r, d+1, d_map); } public static void sort(int a[]){ List<Integer> l = new ArrayList<Integer>(); for(int val : a){ l.add(val); } Collections.sort(l); int k = 0; for(int val : l){ a[k++] = val; } } public static void sortLong(long a[]){ List<Long> l = new ArrayList<Long>(); for(long val : a){ l.add(val); } Collections.sort(l); int k = 0; for(long val : l){ a[k++] = val; } } public static boolean isPal(String s){ int l = 0; int r = s.length() - 1; while(l <= r){ if(s.charAt(l) != s.charAt(r)){ return false; } l++; r--; } return true; } /*public static int gcd(int a, int b){ if(b > a){ int temp = a; a = b; b = temp; } if(b == 0)return a; return gcd(b, a%b); }*/ public static long gcd(long a, long b){ if(b > a){ long temp = a; a = b; b = temp; } if(b == 0)return a; return gcd(b, a%b); } // public static long lcm(long a, long b){ // return a * b/gcd(a, b); // } /*public static class DJSet{ public int a[]; public DJSet(int n){ this.a = new int[n]; Arrays.fill(a, -1); } public int find(int val){ if(a[val] >= 0){ a[val] = find(a[val]); return a[val]; }else{ return val; } } public boolean union(int val1, int val2){ int p1 = find(val1); int p2 = find(val2); if(p1 == p2){ return false; } int size1 = Math.abs(a[p1]); int size2 = Math.abs(a[p2]); if(size1 >= size2){ a[p2] = p1; a[p1] = (size1 + size2) * -1; }else{ a[p1] = p2; a[p2] = (size1 + size2) * -1; } return true; }*/ /* public static class DSU{ public int a[]; public DSU(int size){ this.a = new int[size]; Arrays.fill(a, -1); } public int find(int u){ if(a[u] < 0)return u; a[u] = find(a[u]); return a[u]; } public boolean union(int u, int v){ int p1 = find(u); int p2 = find(v); if(p1 == p2)return false; int size1 = a[p1] * -1; int size2 = a[p2] * -1; if(size1 >= size2){ a[p2] = p1; a[p1] = (size1 + size2) * -1; }else{ a[p1] = p2; a[p2] = (size1 + size2) * -1; } return true; } }*/ }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
bc5860681110c0927b20265d6e4517c0
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static ArrayList<ArrayList<Integer>> adjacencyList; private static boolean[] visited; private static void dfs(int u) { visited[u] = true; for(int v: adjacencyList.get(u)) { if(!visited[v]) { dfs(v); } } } public static void main(String[] args) throws IOException{ //BufferedReader f = new BufferedReader(new FileReader("uva.in")); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("cowjump.out"))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int t = Integer.parseInt(f.readLine()); while(t-- > 0) { int n = Integer.parseInt(f.readLine()); StringTokenizer st = new StringTokenizer(f.readLine()); Integer[] sortedByA = new Integer[n]; int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = Integer.parseInt(st.nextToken()); sortedByA[i] = i; } st = new StringTokenizer(f.readLine()); Integer[] sortedByB = new Integer[n]; int[] b = new int[n]; for(int i = 0; i < n; i++) { b[i] = Integer.parseInt(st.nextToken()); sortedByB[i] = i; } Arrays.sort(sortedByA, new Comparator<Integer>() { @Override public int compare(Integer integer, Integer t1) { return a[integer]-a[t1]; } }); Arrays.sort(sortedByB, new Comparator<Integer>() { @Override public int compare(Integer integer, Integer t1) { return b[integer]-b[t1]; } }); adjacencyList = new ArrayList<>(); for(int i = 0; i < n; i++) { adjacencyList.add(new ArrayList<>()); } for(int i = 0; i < n-1; i++) { adjacencyList.get(sortedByA[i]).add(sortedByA[i+1]); adjacencyList.get(sortedByB[i]).add(sortedByB[i+1]); } visited = new boolean[n]; dfs(sortedByA[n-1]); for(int i = 0; i < n; i++) { out.print(visited[i] ? "1" : "0"); } out.println(); } f.close(); out.close(); } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
58f6eb3e995b45e45f36ab18217a5ce2
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
//Game Master import java.io.*; import java.util.*; public class C1608{ public static void main(String[] args)throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(f.readLine()); for(int q = 1; q <= t; q++){ int n = Integer.parseInt(f.readLine()); StringTokenizer st1 = new StringTokenizer(f.readLine()); StringTokenizer st2 = new StringTokenizer(f.readLine()); int[] a = new int[n]; int[] b = new int[n]; Integer[] sort = new Integer[n]; for(int k = 0; k < n; k++){ a[k] = Integer.parseInt(st1.nextToken()); b[k] = Integer.parseInt(st2.nextToken()); sort[k] = k; } Arrays.sort(sort, new Comparator<Integer>(){ public int compare(Integer i1, Integer i2){ return a[(int)i1] - a[(int)i2]; } }); int[] answer = new int[n]; int min = b[sort[n-1]]; int curmin = min; int last = n-1; for(int k = n-2; k >= 0; k--){ curmin = Math.min(curmin,b[sort[k]]); if(b[sort[k]] > min){ min = curmin; last = k; } } for(int k = last; k < n; k++){ answer[sort[k]] = 1; } StringJoiner sj = new StringJoiner(""); for(int k = 0; k < n; k++){ sj.add("" + answer[k]); } out.println(sj.toString()); } out.close(); } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
46ee40899bce5e85acde5f1a7f4f87c4
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class C{ static class Pair implements Comparable<Pair>{ int a, b, i; public Pair(int x, int y, int z) { a=x; b=y; i=z; } public int compareTo(Pair o) { if (i == o.i) return 0; return a-o.a; } } static int[] ans; static void solve(int[]a , int[] b) { int n=a.length; Pair[] p = new Pair[n]; for (int i = 0; i < n; i++) p[i] = new Pair(a[i], b[i], i); Arrays.sort(p); long[] sufmax = new long[n]; Arrays.fill(sufmax, Long.MIN_VALUE/30); for (int i = n-1; i >= 0; i--) { if (i==n-1) sufmax[i] = p[i].b; else sufmax[i] = max(sufmax[i+1], p[i].b); } //for (int i = 0; i < n; i++) out.println(p[i].a + " " + p[i].b); long max = 0; for (int i = 0; i < n; i++) { max = max(p[i].b, max); if (i == n-1) ans[p[i].i] = 1; else { System.out.println(max + " " + sufmax[i+1]); if (max > sufmax[i+1]) ans[p[i].i] = 1; } } } static TreeSet<Pair> ts; static TreeSet<Pair> ts2; static void solve2(int maxa, int maxb) { // ts = (a,b), ts2 = (b,a) int na = maxa; int nb = maxb; TreeSet<Pair> remove = new TreeSet<Pair>(); while (ts.size() > 0 && ts.last().a >= maxa) { nb = min(nb,ts.last().b); ans[ts.last().i]=1; remove.add(ts.pollLast()); } while (ts2.size() > 0 && ts2.last().a >= maxb) { na = min(na,ts2.last().b); ans[ts2.last().i]=1; remove.add(ts2.pollLast()); } if (na == maxa && nb == maxb) return; solve2(na,nb); } public static void main(String[] args) throws IOException{ // br = new BufferedReader(new FileReader(".in")); // out = new PrintWriter(new FileWriter(".out")); // new Thread(null, new (), "fisa balls", 1<<28).start(); int t =readInt(); while(t-->0) { int n =readInt(); int[] a = new int[n]; int[] b = new int[n]; ans = new int[n]; for (int i = 0; i < n; i++) a[i]=readInt(); for (int i = 0; i < n; i++) b[i]=readInt(); int maxa = 0; int maxb = 0; for (int i = 0; i < n; i++) { maxa = max(a[i], maxa); maxb = max(b[i],maxb); } ts = new TreeSet<Pair>(); ts2 = new TreeSet<Pair>(); for (int i = 0; i < n; i++) { ts.add(new Pair(a[i],b[i],i)); ts2.add(new Pair(b[i], a[i], i)); } solve2(maxa,maxb); for (int x: ans) out.print(x); out.println(); } out.close(); } 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{ while (!st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public static int readInt() throws IOException{return Integer.parseInt(read());} public static long readLong() throws IOException{return Long.parseLong(read());} }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
c36567238e5b7eead07d1ec88c40049a
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /** * @author Naitik * */ public class Main { static FastReader sc=new FastReader(); static long dp[]; //static int v[][]; // static int mod=998244353;; static int mod=1000000007; static int max; static int bit[]; //static long fact[]; // static long A[]; // static TreeMap<Integer,Integer> map; //static StringBuffer sb=new StringBuffer(""); static HashMap<Integer,Integer> map; static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) { // StringBuffer sb=new StringBuffer(""); int ttt=1; ttt =i(); outer :while (ttt-- > 0) { int n=i(); int A[]=input(n); int B[]=input(n); Pair P[]=new Pair[n]; for(int i=0;i<n;i++) { P[i]=new Pair(A[i],B[i],i); } int D[]=new int[n]; int min=Integer.MAX_VALUE; Arrays.sort(P); for(int i=n-1;i>=0;i--) { int y=P[i].y; min=min(min,y); D[i]=min; } int E[]=new int[n]; int max1=Integer.MIN_VALUE; for(int i=n-1;i>=0;i--) { int y=P[i].y; if(y>max1) { E[i]=D[i]; max1=E[i]; } else { E[i]=max1; } } int R[]=new int[n]; int max=0; int l=P[n-1].y; R[P[n-1].z]=1; for(int i=0;i<n-1;i++) { max=max(P[i].y,max); if(E[i+1]<max) { R[P[i].z]=1; } } for(int i=0;i<n;i++) { P[i]=new Pair(B[i],A[i],i); } Arrays.sort(P); min=Integer.MAX_VALUE; for(int i=n-1;i>=0;i--) { int y=P[i].y; min=min(min,y); D[i]=min; } max1=Integer.MIN_VALUE; for(int i=n-1;i>=0;i--) { int y=P[i].y; if(y>max1) { E[i]=D[i]; max1=E[i]; } else { E[i]=max1; } } R[P[n-1].z]=1; max=0; l=P[n-1].y; for(int i=0;i<n-1;i++) { max=max(P[i].y,max); if(E[i+1]<max) { R[P[i].z]=1; } } for(int i : R) { out.print(i); } out.println(); } //System.out.println(sb.toString()); out.close(); //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 } static class Pair implements Comparable<Pair> { int x; int y; int z; Pair(int x,int y,int z){ this.x=x; this.y=y; this.z=z; } @Override public int compareTo(Pair o) { if(this.x>o.x) return 1; else if(this.x<o.x) return -1; else { if(this.y>o.y) return 1; else if(this.y<o.y) return -1; else return 0; } } // public int hashCode() // { // final int temp = 14; // int ans = 1; // ans =x*31+y*13; // return ans; // } // @Override // public boolean equals(Object o) // { // if (this == o) { // return true; // } // if (o == null) { // return false; // } // if (this.getClass() != o.getClass()) { // return false; // } // Pair other = (Pair)o; // if (this.x != other.x || this.y!=other.y) { // return false; // } // return true; // } // /* FOR TREE MAP PAIR USE */ // public int compareTo(Pair o) { // if (x > o.x) { // return 1; // } // if (x < o.x) { // return -1; // } // if (y > o.y) { // return 1; // } // if (y < o.y) { // return -1; // } // return 0; // } } static int find(int A[],int a) { if(A[a]==a) return a; return A[a]=find(A, A[a]); } //static int find(int A[],int a) { // if(A[a]==a) // return a; // return find(A, A[a]); //} //FENWICK TREE static void update(int i, int x){ for(; i < bit.length; i += (i&-i)) bit[i] += x; } static int sum(int i){ int ans = 0; for(; i > 0; i -= (i&-i)) ans += bit[i]; return ans; } //END static void add(int v) { if(!map.containsKey(v)) { map.put(v, 1); } else { map.put(v, map.get(v)+1); } } static void remove(int v) { if(map.containsKey(v)) { map.put(v, map.get(v)-1); if(map.get(v)==0) map.remove(v); } } public static int upper(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { ans=mid; l=mid+1; } else { u=mid-1; } } return ans; } public static int lower(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { l=mid+1; } else { ans=mid; u=mid-1; } } return ans; } static int[] copy(int A[]) { int B[]=new int[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static long[] copy(long A[]) { long B[]=new long[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void reverse(long A[]) { int n=A.length; long B[]=new long[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void reverse(int A[]) { int n=A.length; int B[]=new int[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static int[][] input(int n,int m){ int A[][]=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { A[i][j]=i(); } } return A; } static char[][] charinput(int n,int m){ char A[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=s(); for(int j=0;j<m;j++) { A[i][j]=s.charAt(j); } } return A; } static int nextPowerOf2(int n) { n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n; } static int highestPowerof2(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static long highestPowerof2(long x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long [] prefix(long A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] prefix(int A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] suffix(long A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static long [] suffix(int A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static void fill(int dp[]) { Arrays.fill(dp, -1); } static void fill(int dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(int dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(int dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static void fill(long dp[]) { Arrays.fill(dp, -1); } static void fill(long dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(long dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(long dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long power(long x, long y, long p) { if(y==0) return 1; if(x==0) return 0; long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long power(long x, long y) { if(y==0) return 1; if(x==0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void print(int A[]) { for(int i : A) { System.out.print(i+" "); } System.out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { return ((x%mod + mod)%mod); } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static String sort(String s) { Character ch[]=new Character[s.length()]; for(int i=0;i<s.length();i++) { ch[i]=s.charAt(i); } Arrays.sort(ch); StringBuffer st=new StringBuffer(""); for(int i=0;i<s.length();i++) { st.append(ch[i]); } return st.toString(); } static HashMap<Integer,Integer> hash(int A[]){ HashMap<Integer,Integer> map=new HashMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static HashMap<Long,Integer> hash(long A[]){ HashMap<Long,Integer> map=new HashMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Integer,Integer> tree(int A[]){ TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Long,Integer> tree(long A[]){ TreeMap<Long,Integer> map=new TreeMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
32d4ca27a243bb0f4cebf70b67be2990
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.*; public class Main { static InputReader2 sc=new InputReader2(System.in); /* static int MAXN=200005,n,m,a[]=new int[MAXN],dp[]=new int[MAXN],edge[][]=new int[MAXN][2]; static long k; static boolean vis[]=new boolean[MAXN],ok=false; static Vector<Integer> G[]=new Vector[MAXN],g[]=new Vector[MAXN];*/ static int MAXN=100005,ans[]=new int[MAXN]; static Vector<Integer> G[]=new Vector[MAXN]; public static void main(String args[]){ solve(); } private static void solve() { for(int i=1;i<=100000;i++){ G[i]=new Vector<>(); } int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); for(int i=1;i<=n;i++){ G[i].clear(); ans[i]=0; } int a[][]=new int[n+1][2]; int b[][]=new int[n+1][2]; int maxa[]={0,0},maxb[]={0,0}; for(int i=1;i<=n;i++){ a[i][0]=sc.nextInt(); a[i][1]=i; if(a[i][0]>maxa[0]){ maxa[1]=i; maxa[0]=a[i][0]; } } for(int i=1;i<=n;i++){ b[i][0]=sc.nextInt(); b[i][1]=i; if(b[i][0]>maxb[0]){ maxb[1]=i; maxb[0]=b[i][0]; } } Arrays.sort(a, (o1, o2) -> o1[0]-o2[0]); Arrays.sort(b, (o1, o2) -> o1[0]-o2[0]); for(int i=n;i>=2;i--){ G[a[i-1][1]].add(a[i][1]); G[b[i-1][1]].add(b[i][1]); } //System.out.println(maxa[1]+" "+maxb[1]); ans[maxa[1]]=ans[maxb[1]]=1; dfs(maxa[1]); dfs(maxb[1]); for(int i=1;i<=n;i++){ System.out.print(ans[i]); } System.out.println(); } } private static void dfs(int x) { for(int v:G[x]){ if(ans[v]==1)continue; //System.out.println(x+" "+v); ans[v]=1; dfs(v); } } } class InputReader2 { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader2(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
8274982a377e4ced4a5358e0883ef4ad
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.util.*; import java.io.*; public class Solution { static void dfs(int n , ArrayList<Integer> g[] , boolean vis[]) { vis[n] = true; for(Integer v : g[n]) { if(!vis[v]) { dfs(v,g,vis); } } } public static void main(String []args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int a[] = new int[n]; int b[] = new int[n]; pair arr[] = new pair[n]; ArrayList<Integer> g[] = new ArrayList[n]; for(int i = 0 ; i < n ; i++) { g[i] = new ArrayList<Integer>(); } int pos = -1; int maxx = 0; for(int i = 0 ; i < n ; i++) { int x = sc.nextInt(); arr[i] = new pair(x,i); if(x > maxx) { maxx = x; pos = i; } } Arrays.sort(arr , new Compare()); for(int i = 0 ; i < n-1 ; i++) { g[arr[i].id].add(arr[i+1].id); } for(int i = 0 ; i < n ; i++) { int x = sc.nextInt(); arr[i] = new pair(x,i); } Arrays.sort(arr , new Compare()); for(int i = 0 ; i < n-1 ; i++) { g[arr[i].id].add(arr[i+1].id); } boolean vis[] = new boolean[n]; dfs(pos,g,vis); StringBuffer str = new StringBuffer(""); for(int i = 0 ; i < n ; i++) { if(vis[i]) str.append(1); else str.append(0); } System.out.println(str); } } } class pair { int val , id; public pair(int val , int id) { this.val = val; this.id = id; } } class Compare implements Comparator<pair> { public int compare(pair a , pair b) { return a.val-b.val; } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
fbd14f00e3f658cb2ac613eb65fbf1e2
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class code{ public static int GCD(int a, int b) { if (b == 0) return a; return GCD(b, a % b); } public static void shuffle(int a[], int n) { for (int i = 0; i < n; i++) { // getting the random index int t = (int)Math.random() * a.length; // and swapping values a random index // with the current index int x = a[t]; a[t] = a[i]; a[i] = x; } } @SuppressWarnings("unchecked") public static void main(String[] arg) throws IOException{ //Reader in=new Reader(); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(System.in); int t=in.nextInt(); while(t-- > 0){ int n=in.nextInt(); int[][] arr=new int[n][3]; int[] b=new int[n]; int[] res=new int[n]; Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++){ arr[i][0]=i; arr[i][1]=in.nextInt(); } for(int i=0;i<n;i++) { arr[i][2]=in.nextInt(); b[i]=arr[i][2]; } shuffle(b,n); Arrays.sort(b); for(int i=0;i<n;i++) map.put(b[i],i+1); Arrays.sort(arr,(a,c)->a[1]-c[1]); for(int i=0;i<n;i++){ arr[i][1]=i+1; arr[i][2]=map.get(arr[i][2]); } int min=Math.min(arr[n-1][1],arr[n-1][2]); res[arr[n-1][0]]=1; for(int i=n-2;i>=0;i--){ if(arr[i][1]<min) break; res[arr[i][0]]=1; min=Math.min(min,Math.min(arr[i][1],arr[i][2])); } for(int i=0;i<n;i++) out.print(res[i]); out.println(); } out.flush(); } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
52a624f7369e660d0f30ec617da8e378
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.awt.Container; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class Main { public static ArrayList<ArrayList<Integer>> ar; public static boolean visited[]; public static void DFS(int i) { visited[i] = true; for (Integer integer : ar.get(i)) { if(!visited[integer]) { DFS(integer); } } } public static class pair { int value,index; public pair(int value, int index) { this.value = value; this.index = index; } } public static void main(String[] args) { FastScanner input = new FastScanner(); int tc = input.nextInt(); work: while (tc-- > 0) { int n = input.nextInt(); pair[] a = new pair[n]; pair[] b = new pair[n]; ar = new ArrayList<>(); visited = new boolean[n]; for (int i = 0; i < n; i++) { ar.add(new ArrayList<>()); } for (int i = 0; i < n; i++) { a[i] = new pair(input.nextInt(), i); } for (int i = 0; i < n; i++) { b[i] = new pair(input.nextInt(), i); } Arrays.sort(a, new Comparator<pair>() { @Override public int compare(pair t, pair t1) { return t.value - t1.value; } }); Arrays.sort(b, new Comparator<pair>() { @Override public int compare(pair t, pair t1) { return t.value - t1.value; } }); // for (pair object : a) { // System.out.println(object.value+" "+object.index); // } // for (pair object : b) { // System.out.println(object.value+" "+object.index); // } for (int i = 0; i < n-1; i++) { ar.get(a[i].index).add(a[i+1].index); ar.get(b[i].index).add(b[i+1].index); } DFS(a[n-1].index); StringBuilder result = new StringBuilder(); for (boolean c : visited) { if(c) { result.append("1"); } else result.append("0"); } System.out.println(result); } } 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) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
bc76b2af67923c1909e46f86fc9f9c60
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.awt.Container; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class Main { public static class pair { int a,b,index; public pair(int a, int b, int index) { this.a = a; this.b = b; this.index = index; } } public static void main(String[] args) { FastScanner input = new FastScanner(); int tc = input.nextInt(); work: while (tc-- > 0) { int n = input.nextInt(); pair p[] = new pair[n]; int a[] = new int[n]; int b[] = new int[n]; for (int i = 0; i <n; i++) { a[i] = input.nextInt(); } for (int i = 0; i < n; i++) { b[i] = input.nextInt(); } for (int i = 0; i <n; i++) { p[i] = new pair(a[i], b[i],i); } Arrays.sort(p,new Comparator<pair>() { @Override public int compare(pair t, pair t1) { return t.a-t1.a; } }); int min = p[n-1].b; int id = n-1; int cmin = Integer.MAX_VALUE; for (int i = n-2; i >=0; i--) { if(p[i].b>min) { min = Math.min(min, cmin); id = i; } cmin = Math.min(cmin, p[i].b); } int ans[] = new int[n]; for (int i = id; i <n; i++) { ans[p[i].index] = 1; } StringBuilder result = new StringBuilder(); for (int i = 0; i <n; i++) { result.append(ans[i]); } System.out.println(result); } } 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) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
ba9719f55b3c76ecac62027847491791
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.util.InputMismatchException; import java.io.InputStreamReader; import java.io.Writer; import java.io.BufferedReader; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Nipuna Samarasekara */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, FastPrinter out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int[] a = in.readIntArray(n); int[] b = in.readIntArray(n); ArrayUtils.compress(a); ArrayUtils.compress(b); int amax = 0, mi = 0; MinSegmentTree mstA = new MinSegmentTree(n + 10); MinSegmentTree mstB = new MinSegmentTree(n + 10); for (int i = 0; i < n; i++) { if (a[i] > amax) { amax = a[i]; mi = i; } mstA.set(a[i], b[i]); mstB.set(b[i], a[i]); } int ab = 1; int amin = amax; int bmin = mstA.getMin(amin, n + 1); boolean good = true; while (good) { good = false; if (ab == 1) { int na = mstB.getMin(bmin, n + 1); if (na < amin) { amin = na; good = true; } } else { int na = mstA.getMin(amin, n + 1); if (na < bmin) { bmin = na; good = true; } } ab = 1 - ab; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if (a[i] >= amin || b[i] >= bmin) { sb.append("1"); } else { sb.append("0"); } } out.println(sb.toString()); } } } static interface IntIterator { public int value() throws NoSuchElementException; public void advance() throws NoSuchElementException; public boolean isValid(); } static class IntSortedArray extends IntSortedList { private final int[] array; public IntSortedArray(int[] array) { this(array, IntComparator.DEFAULT); } public IntSortedArray(IntCollection collection) { this(collection, IntComparator.DEFAULT); } public IntSortedArray(int[] array, IntComparator comparator) { super(comparator); this.array = array; ensureSorted(); } public IntSortedArray(IntCollection collection, IntComparator comparator) { super(comparator); array = new int[collection.size()]; int i = 0; for (IntIterator iterator = collection.iterator(); iterator.isValid(); iterator.advance()) array[i++] = iterator.value(); ensureSorted(); } public int get(int index) { return array[index]; } public int size() { return array.length; } } static abstract class IntSortedList extends IntList { protected final IntComparator comparator; protected IntSortedList(IntComparator comparator) { this.comparator = comparator; } public void set(int index, int value) { throw new UnsupportedOperationException(); } public IntSortedList inPlaceSort(IntComparator comparator) { if (comparator == this.comparator) { return this; } throw new UnsupportedOperationException(); } protected void ensureSorted() { int size = size(); if (size == 0) { return; } int last = get(0); for (int i = 1; i < size; i++) { int current = get(i); if (comparator.compare(last, current) > 0) { throw new IllegalArgumentException(); } last = current; } } public IntSortedList subList(final int from, final int to) { return new IntSortedList(comparator) { private int size = to - from; public int get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } return IntSortedList.this.get(index + from); } public int size() { return size; } }; } } static class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } static class MinSegmentTree { int[] min; int[] minId; int n; public MinSegmentTree(int n) { this.n = Integer.highestOneBit(n) << 1; min = new int[this.n * 2]; minId = new int[this.n * 2]; for (int i = 0; i < n; i++) { minId[i + n] = i; } for (int i = 0; i < n; i++) { set(i, Integer.MAX_VALUE); } } public void set(int x, int y) { x += n; min[x] = y; while (x > 1) { x >>= 1; int left = min[x << 1]; int right = min[(x << 1) | 1]; if (left <= right) { min[x] = left; minId[x] = minId[x << 1]; } else { min[x] = right; minId[x] = minId[(x << 1) | 1]; } } } public int getMin(int left, int right) { --right; left += n; right += n; int ret = Integer.MAX_VALUE; while (left <= right) { if ((left & 1) == 1) { ret = Math.min(ret, min[left]); left++; } if ((right & 1) == 0) { ret = Math.min(ret, min[right]); right--; } left >>= 1; right >>= 1; } return ret; } } static interface IntComparator { public static final IntComparator DEFAULT = new IntComparator() { public int compare(int first, int second) { if (first < second) { return -1; } if (first > second) { return 1; } return 0; } }; public int compare(int first, int second); } static class ArrayUtils { public static int[] sort(int[] array, IntComparator comparator) { return sort(array, 0, array.length, comparator); } public static int[] sort(int[] array, int from, int to, IntComparator comparator) { if (from == 0 && to == array.length) { new IntArray(array).inPlaceSort(comparator); } else { new IntArray(array).subList(from, to).inPlaceSort(comparator); } return array; } public static int[] unique(int[] array) { return unique(array, 0, array.length); } public static int[] unique(int[] array, int from, int to) { if (from == to) { return new int[0]; } int count = 1; for (int i = from + 1; i < to; i++) { if (array[i] != array[i - 1]) { count++; } } int[] result = new int[count]; result[0] = array[from]; int index = 1; for (int i = from + 1; i < to; i++) { if (array[i] != array[i - 1]) { result[index++] = array[i]; } } return result; } public static int[] compress(int[]... arrays) { int totalLength = 0; for (int[] array : arrays) totalLength += array.length; int[] all = new int[totalLength]; int delta = 0; for (int[] array : arrays) { System.arraycopy(array, 0, all, delta, array.length); delta += array.length; } sort(all, IntComparator.DEFAULT); all = unique(all); for (int[] array : arrays) { for (int i = 0; i < array.length; i++) array[i] = Arrays.binarySearch(all, array[i]); } return all; } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } static abstract class IntList extends IntCollection implements Comparable<IntList> { private static final int INSERTION_THRESHOLD = 16; public abstract int get(int index); public abstract void set(int index, int value); public IntIterator iterator() { return new IntIterator() { private int size = size(); private int index = 0; public int value() throws NoSuchElementException { if (!isValid()) { throw new NoSuchElementException(); } return get(index); } public void advance() throws NoSuchElementException { if (!isValid()) { throw new NoSuchElementException(); } index++; } public boolean isValid() { return index < size; } }; } public IntList subList(final int from, final int to) { return new SubList(from, to); } private void swap(int first, int second) { if (first == second) { return; } int temp = get(first); set(first, get(second)); set(second, temp); } public IntSortedList inPlaceSort(IntComparator comparator) { quickSort(0, size() - 1, (Integer.bitCount(Integer.highestOneBit(size()) - 1) * 5) >> 1, comparator); return new IntSortedArray(this, comparator); } private void quickSort(int from, int to, int remaining, IntComparator comparator) { if (to - from < INSERTION_THRESHOLD) { insertionSort(from, to, comparator); return; } if (remaining == 0) { heapSort(from, to, comparator); return; } remaining--; int pivotIndex = (from + to) >> 1; int pivot = get(pivotIndex); swap(pivotIndex, to); int storeIndex = from; int equalIndex = to; for (int i = from; i < equalIndex; i++) { int value = comparator.compare(get(i), pivot); if (value < 0) { swap(storeIndex++, i); } else if (value == 0) { swap(--equalIndex, i--); } } quickSort(from, storeIndex - 1, remaining, comparator); for (int i = equalIndex; i <= to; i++) swap(storeIndex++, i); quickSort(storeIndex, to, remaining, comparator); } private void heapSort(int from, int to, IntComparator comparator) { for (int i = (to + from - 1) >> 1; i >= from; i--) siftDown(i, to, comparator, from); for (int i = to; i > from; i--) { swap(from, i); siftDown(from, i - 1, comparator, from); } } private void siftDown(int start, int end, IntComparator comparator, int delta) { int value = get(start); while (true) { int child = ((start - delta) << 1) + 1 + delta; if (child > end) { return; } int childValue = get(child); if (child + 1 <= end) { int otherValue = get(child + 1); if (comparator.compare(otherValue, childValue) > 0) { child++; childValue = otherValue; } } if (comparator.compare(value, childValue) >= 0) { return; } swap(start, child); start = child; } } private void insertionSort(int from, int to, IntComparator comparator) { for (int i = from + 1; i <= to; i++) { int value = get(i); for (int j = i - 1; j >= from; j--) { if (comparator.compare(get(j), value) <= 0) { break; } swap(j, j + 1); } } } public int hashCode() { int hashCode = 1; for (IntIterator i = iterator(); i.isValid(); i.advance()) hashCode = 31 * hashCode + i.value(); return hashCode; } public boolean equals(Object obj) { if (!(obj instanceof IntList)) { return false; } IntList list = (IntList) obj; if (list.size() != size()) { return false; } IntIterator i = iterator(); IntIterator j = list.iterator(); while (i.isValid()) { if (i.value() != j.value()) { return false; } i.advance(); j.advance(); } return true; } public int compareTo(IntList o) { IntIterator i = iterator(); IntIterator j = o.iterator(); while (true) { if (i.isValid()) { if (j.isValid()) { if (i.value() != j.value()) { if (i.value() < j.value()) { return -1; } else { return 1; } } } else { return 1; } } else { if (j.isValid()) { return -1; } else { return 0; } } i.advance(); j.advance(); } } private class SubList extends IntList { private final int to; private final int from; private int size; public SubList(int from, int to) { this.to = to; this.from = from; size = to - from; } public int get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } return IntList.this.get(index + from); } public void set(int index, int value) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } IntList.this.set(index + from, value); } public int size() { return size; } } } static abstract class IntCollection { public abstract IntIterator iterator(); public abstract int size(); } static class IntArray extends IntList { private final int[] array; public IntArray(int[] array) { this.array = array; } public IntArray(IntCollection collection) { array = new int[collection.size()]; int i = 0; for (IntIterator iterator = collection.iterator(); iterator.isValid(); iterator.advance()) array[i++] = iterator.value(); } public int get(int index) { return array[index]; } public void set(int index, int value) { array[index] = value; } public int size() { return array.length; } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
aa8a380ffee4fea238f1c060551fcf29
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class Player implements Comparable<Player> { int strength; int idx; Player(int strength, int idx) { this.strength = strength; this.idx = idx; } @Override public int compareTo(Player other) { return this.strength - other.strength; } } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int T = Integer.parseInt(in.readLine()); int[] aidx = new int[100100]; int[] bidx = new int[100100]; char[] ans = new char[100100]; for (int ts=1; ts<=T; ts++) { int N = Integer.parseInt(in.readLine()); List<Player> ap = new ArrayList<>(); { String[] line = in.readLine().split(" "); int idx = 1; for (final String str : line) { ap.add(new Player(Integer.parseInt(str), idx)); idx++; } } List<Player> bp = new ArrayList<>(); { String[] line = in.readLine().split(" "); int idx = 1; for (final String str : line) { bp.add(new Player(Integer.parseInt(str), idx)); ans[idx] = '0'; idx++; } } Collections.sort(ap); Collections.sort(bp); for (int i=0; i<ap.size(); i++) { aidx[ap.get(i).idx] = i; } for (int i=0; i<bp.size(); i++) { bidx[bp.get(i).idx] = i; } List<Integer> winners = new ArrayList<>(); winners.add(ap.get(ap.size()-1).idx); winners.add(bp.get(bp.size()-1).idx); int aindex = ap.size()-1; int bindex = bp.size()-1; while (!winners.isEmpty()) { int winner = winners.remove(winners.size()-1); if (aidx[winner] < aindex) { for (int i=aidx[winner]; i<aindex; i++) { winners.add(ap.get(i).idx); } aindex = aidx[winner]; } if (bidx[winner] < bindex) { for (int i=bidx[winner]; i<bindex; i++) { winners.add(bp.get(i).idx); } bindex = bidx[winner]; } } for (int i=aindex; i<ap.size(); i++) { ans[ap.get(i).idx] = '1'; } for (int i=bindex; i<bp.size(); i++) { ans[bp.get(i).idx] = '1'; } StringBuilder sb = new StringBuilder(); for (int i=1; i<=N; i++) { sb.append(ans[i]); } out.write(sb.toString() + "\n"); } in.close(); out.close(); } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
3ff9efefb5e01e36c45dbcaea16c630c
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.util.*; import java.io.*; public class C { public static void inc(int[] vis, int[] cnt, int idx, boolean first) { cnt[vis[idx]]--; vis[idx] |= (first ? 1 : 2); cnt[vis[idx]]++; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { b[i] = sc.nextInt(); } PriorityQueue<Pair> pqa = new PriorityQueue<>((u, v) -> u.y - v.y); PriorityQueue<Pair> pqb = new PriorityQueue<>((u, v) -> u.y - v.y); for (int i = 0; i < n; i++) { pqa.add(new Pair(i, a[i])); pqb.add(new Pair(i, b[i])); } int[] vis = new int[n]; int[] cnt = new int[4]; cnt[0] = n; boolean[] good = new boolean[n]; while (!pqa.isEmpty() && !pqb.isEmpty()) { Pair cur = pqa.poll(); ArrayList<Integer> al = new ArrayList<>(); al.add(cur.x); if (vis[cur.x] == 0) { inc(vis, cnt, cur.x, true); while (true) { if (cnt[2] != 0) { Pair temp = pqa.poll(); al.add(temp.x); inc(vis, cnt, temp.x, true); } else if (cnt[1] != 0) { Pair temp = pqb.poll(); al.add(temp.x); inc(vis, cnt, temp.x, false); } else break; } } if (cnt[0] == 0) { for (int x : al) { good[x] = true; } } } for (int i = 0; i < n; i++) { pw.print(good[i] ? '1' : '0'); } pw.println(); } pw.close(); } static class Pair { int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } 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()); } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
257474130813463b468ed61618a1ca0c
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter pr = new PrintWriter(System.out); static String readLine() throws IOException { return br.readLine(); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } static int readInt() throws IOException { return Integer.parseInt(next()); } static long readLong() throws IOException { return Long.parseLong(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readChar() throws IOException { return next().charAt(0); } static class Pair implements Comparable<Pair> { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } public int compareTo(Pair other) { if (this.f != other.f) return this.f - other.f; return this.s - other.s; } } static class Player implements Comparable<Player> { int a, b, idx; Player(int a, int b, int idx) { this.a = a; this.b = b; this.idx = idx; } public int compareTo(Player other) { return this.a - other.a; } } final static int inf = (int)2e9; static void solve() throws IOException { int n = readInt(); Player p[] = new Player[n + 1]; for (int i = 1; i <= n; ++i) p[i] = new Player(readInt(), 0, i); for (int i = 1; i <= n; ++i) p[i].b = readInt(); Arrays.sort(p, 1, n + 1); char ans[] = new char[n + 1]; int dp[] = new int[n + 1], pre[] = new int[n + 1], suf[] = new int[n + 2]; for (int i = 1; i <= n; ++i) pre[i] = Math.max(p[i].b, pre[i - 1]); suf[n + 1] = inf; for (int i = n; i >= 1; --i) { suf[i] = Math.min(p[i].b, suf[i + 1]); int lo = i, hi = n; while (lo < hi) { int mid = (lo + hi + 1)>>1; if (suf[mid] <= pre[i]) lo = mid; else hi = mid - 1; } if (lo == i) dp[i] = i; else dp[i] = dp[lo]; if (dp[i] == n) ans[p[i].idx] = '1'; else ans[p[i].idx] = '0'; } for (int i = 1; i <= n; ++i) pr.print(ans[i]); pr.println(); } public static void main(String[] args) throws IOException { //solve(); for (int t = readInt(); t > 0; --t) solve(); pr.close(); } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
569d71ddb7bd2fa349d0b1dbcc0427a1
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class tr2 { static PrintWriter out; static StringBuilder sb; static long mod = (long) 1e9 + 7; static long inf = (long) 1e16; static int n, m, k; static ArrayList<Integer>[] ad; static int[][] remove, add; static long[][] memo; static boolean[] vis, vis1; static long[] inv, ncr[]; static HashMap<Integer, Integer> hm; static int[] pre, suf, Smax[], Smin[]; static int idmax, idmin; static ArrayList<Integer> av; static HashMap<Integer, Integer> mm; static int[] lazy[], lazyCount; static int[] dist; static int[] g; static int st, ed, edges; static HashSet<Integer> gl; static int[] coms, ox; static long ans; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } TreeSet<Integer> ts = new TreeSet<>((x, y) -> a[y] - a[x]); TreeMap<Integer, Integer> tm = new TreeMap<>(); TreeSet<Integer> ts1 = new TreeSet<>(); for (int i = 0; i < n; i++) { ts.add(i); b[i] = sc.nextInt(); tm.put(i, b[i]); ts1.add(b[i]); } char[] s = new char[n]; TreeSet<Integer> win = new TreeSet<>(); for (int i = 0; i < n; i++) { int id = ts.pollFirst(); int g = ts1.last(); Integer k = win.lower(g); if (i == 0 || k != null) s[id] = '1'; else s[id] = '0'; ts1.remove(tm.get(id)); tm.remove(id); if (s[id] == '1') { win.add(b[id]); } } out.println(new String(s)); } out.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextArrIntSorted(int n) throws IOException { int[] a = new int[n]; Integer[] a1 = new Integer[n]; for (int i = 0; i < n; i++) a1[i] = nextInt(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].intValue(); return a; } public long[] nextArrLongSorted(int n) throws IOException { long[] a = new long[n]; Long[] a1 = new Long[n]; for (int i = 0; i < n; i++) a1[i] = nextLong(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].longValue(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
ff966bee9a012c2bef02e6388f4055f0
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import java.util.StringTokenizer; public class C1608 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); StringTokenizer st; for (int t = Integer.parseInt(br.readLine()); t-- > 0; ) { int n = Integer.parseInt(br.readLine()); Player[] playersA = new Player[n]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { playersA[i] = new Player(i, Integer.parseInt(st.nextToken())); } Player[] playersB = new Player[n]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { playersB[i] = new Player(i, Integer.parseInt(st.nextToken())); } int[][] sortedPos = new int[n][2]; Arrays.sort(playersA); Arrays.sort(playersB); for (int i = 0; i < n; i++) { sortedPos[playersA[i].id][0] = i; sortedPos[playersB[i].id][1] = i; } Queue<Integer> queue = new ArrayDeque<>(2 * n); queue.add(playersA[n - 1].id); queue.add(playersB[n - 1].id); int endA = n - 1; int endB = n - 1; char[] canWin = new char[n]; Arrays.fill(canWin, '0'); while (!queue.isEmpty()) { int current = queue.poll(); canWin[current] = '1'; for (int i = sortedPos[current][0] + 1; i < endA; i++) { if (canWin[playersA[i].id] == '0') { queue.add(playersA[i].id); } } endA = Math.min(endA, sortedPos[current][0]); for (int i = sortedPos[current][1] + 1; i < endB; i++) { if (canWin[playersB[i].id] == '0') { queue.add(playersB[i].id); } } endB = Math.min(endB, sortedPos[current][1]); } out.println(canWin); } out.close(); } private static class Player implements Comparable<Player> { private int id; private int v; private Player(int id, int v) { this.id = id; this.v = v; } @Override public int compareTo(Player o) { return this.v - o.v; } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
8bda2da67caa77a32cbaedfeca6f45b7
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.util.*; public class C1608{ public static void main(String[] args)throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(f.readLine()); for(int q = 1; q <= t; q++){ int n = Integer.parseInt(f.readLine()); StringTokenizer st1 = new StringTokenizer(f.readLine()); StringTokenizer st2 = new StringTokenizer(f.readLine()); int[] a = new int[n]; int[] b = new int[n]; Integer[] sort = new Integer[n]; for(int k = 0; k < n; k++){ a[k] = Integer.parseInt(st1.nextToken()); b[k] = Integer.parseInt(st2.nextToken()); sort[k] = k; } Arrays.sort(sort, new Comparator<Integer>(){ public int compare(Integer i1, Integer i2){ return a[(int)i1] - a[(int)i2]; } }); int[] answer = new int[n]; int min = b[sort[n-1]]; int curmin = min; int last = n-1; for(int k = n-2; k >= 0; k--){ curmin = Math.min(curmin,b[sort[k]]); if(b[sort[k]] > min){ min = curmin; last = k; } } for(int k = last; k < n; k++){ answer[sort[k]] = 1; } StringJoiner sj = new StringJoiner(""); for(int k = 0; k < n; k++){ sj.add("" + answer[k]); } out.println(sj.toString()); } out.close(); } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
8e06fb8085e69de7d45a86351bf1fd7c
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.util.*; public class C1608{ public static void main(String[] args)throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(f.readLine()); for(int q = 1; q <= t; q++){ int n = Integer.parseInt(f.readLine()); StringTokenizer st1 = new StringTokenizer(f.readLine()); StringTokenizer st2 = new StringTokenizer(f.readLine()); int[] a = new int[n]; int[] b = new int[n]; Integer[] sort = new Integer[n]; for(int k = 0; k < n; k++){ a[k] = Integer.parseInt(st1.nextToken()); b[k] = Integer.parseInt(st2.nextToken()); sort[k] = k; } Arrays.sort(sort, new Comparator<Integer>(){ public int compare(Integer i1, Integer i2){ return a[(int)i1] - a[(int)i2]; } }); int[] answer = new int[n]; int min = b[sort[n-1]]; int curmin = min; int last = n-1; for(int k = n-2; k >= 0; k--){ curmin = Math.min(curmin,b[sort[k]]); if(b[sort[k]] > min){ min = curmin; last = k; } } for(int k = last; k < n; k++){ answer[sort[k]] = 1; } StringJoiner sj = new StringJoiner(""); for(int k = 0; k < n; k++){ sj.add("" + answer[k]); } out.println(sj.toString()); } out.close(); } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
ed48e53d67b2c9d1448731dbdad6adfa
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
/* * Everything is Hard * Before Easy * Jai Mata Dii */ import java.util.*; import java.io.*; public class Main { 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 long mod = (long)(1e9+7); // static long mod = 998244353; // static Scanner sc = new Scanner(System.in); static FastReader sc = new FastReader(); static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { int ttt = 1; ttt = sc.nextInt(); z :for(int tc=1;tc<=ttt;tc++){ int n = sc.nextInt(); ArrayList<int[]> a = new ArrayList<>(); ArrayList<int[]> b = new ArrayList<>(); for(int i=0;i<n;i++) { int x = sc.nextInt(); a.add(new int[] {x, i}); } for(int i=0;i<n;i++) { int x = sc.nextInt(); b.add(new int[] {x, i}); } Collections.sort(a, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }); Collections.sort(b, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }); Set<Integer> g[] = new HashSet[n]; for(int i=0;i<n;i++) { g[i] = new HashSet<>(); } Queue<Integer> q = new LinkedList<>(); q.add(a.get(a.size()-1)[1]); if(a.get(a.size()-1)[1]!=b.get(b.size()-1)[1]) { q.add(b.get(b.size()-1)[1]); } for(int i=0;i<n-1;i++) { if(!g[a.get(i)[1]].contains(a.get(i+1)[1])) { g[a.get(i)[1]].add(a.get(i+1)[1]); } if(!g[b.get(i)[1]].contains(b.get(i+1)[1])) { g[b.get(i)[1]].add(b.get(i+1)[1]); } } HashSet<Integer> hs = new HashSet<>(); while(!q.isEmpty()) { int cur = q.poll(); hs.add(cur); for(int adj : g[cur]) { if(!hs.contains(adj)) { hs.add(adj); q.add(adj); } } } StringBuilder form = new StringBuilder(); for(int i=0;i<n;i++) { if(hs.contains(i)) form.append("1"); else form.append("0"); } out.write(form+"\n"); } out.close(); } static long pow(long a, long b){long ret = 1;while(b>0){if(b%2 == 0){a = (a*a)%mod;b /= 2;}else{ret = (ret*a)%mod;b--;}}return ret%mod;} static long gcd(long a,long b){if(b==0) return a; return gcd(b,a%b); } private static void sort(int[] a) {List<Integer> k = new ArrayList<>();for(int val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);} private static void ini(List<Integer>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}} private static void init(List<int[]>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}} private static void sort(long[] a) {List<Long> k = new ArrayList<>();for(long val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);} }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
59a9c59eac0c23ac82b267d6bf4fdf17
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static class DSU { private int[] parent; private int[] size; private int totalGroup; private int maxSize = 1; public DSU(int n) { parent = new int[n]; totalGroup = n; for (int i = 0; i < n; i++) { parent[i] = i; } size = new int[n]; Arrays.fill(size, 1); } public boolean union(int a, int b) { int parentA = findParent(a); int parentB = findParent(b); if (parentA == parentB) { return false; } totalGroup--; if (parentA < parentB) { this.parent[parentB] = parentA; this.size[parentA] += this.size[parentB]; maxSize = Math.max(this.size[parentA], maxSize); } else { this.parent[parentA] = parentB; this.size[parentB] += this.size[parentA]; maxSize = Math.max(this.size[parentB], maxSize); } return true; } public int findParent(int a) { if (parent[a] != a) { parent[a] = findParent(parent[a]); } return parent[a]; } public int getGroupSize(int a) { return this.size[findParent(a)]; } public int getTotalGroup() { return totalGroup; } } public static void main(String[] args) throws Exception { int tc = io.nextInt(); for (int i = 0; i < tc; i++) { solve(); } io.close(); } private static void solve() throws Exception { int n = io.nextInt(); int[] a = io.nextInts(n); int[] b = io.nextInts(n); int[][] data = new int[n][5]; for (int i = 0; i < n; i++) { data[i][0] = a[i]; data[i][1] = b[i]; data[i][2] = i; } Arrays.sort(data, (o1, o2) -> Integer.compare(o2[0], o1[0])); for (int i = 0; i < n; i++) { data[i][3] = i; } Arrays.sort(data, (o1, o2) -> Integer.compare(o2[1], o1[1])); for (int i = 0; i < n; i++) { data[i][4] = i; } Arrays.sort(data, (o1, o2) -> Integer.compare(o1[2], o2[2])); Queue<int[]> queue = new PriorityQueue<>((o1, o2) -> { return o1[0] - o2[0]; }); for (int i = 0; i < n; i++) { queue.add(new int[]{data[i][3], data[i][2]}); queue.add(new int[]{data[i][4], data[i][2]}); } int worstRank = 0; while (queue.size() > 0) { int[] curr = queue.poll(); if (worstRank >= curr[0]) { worstRank = Math.max(worstRank, Math.max(data[curr[1]][3], data[curr[1]][4])); } else { break; } } char[] output = new char[n]; for (int i = 0; i < n; i++) { int playerBestRank = Math.min(data[i][3], data[i][4]); if (playerBestRank <= worstRank) { output[i] = '1'; } else { output[i] = '0'; } } for (int i = 0; i < n; i++) { io.print(output[i]); } io.println(); } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(a.length); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } //-----------PrintWriter for faster output--------------------------------- public static FastIO io = new FastIO(); //-----------MyScanner class for faster input---------- static class FastIO extends PrintWriter { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar, numChars; // standard input public FastIO() { this(System.in, System.out); } public FastIO(InputStream i, OutputStream o) { super(o); stream = i; } // file input public FastIO(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } // to read in entire lines, replace c <= ' ' // with a function that checks whether c is a line break public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public String nextLine() { int c; do { c = nextByte(); } while (c < '\n'); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n'); return res.toString(); } public int nextInt() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } public long nextLong() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } int[] nextInts(int n) { int[] data = new int[n]; for (int i = 0; i < n; i++) { data[i] = io.nextInt(); } return data; } public double nextDouble() { return Double.parseDouble(next()); } } //-------------------------------------------------------- }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
46a6f98446fb113e8286eed97876e836
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.StringTokenizer; public class C { static ArrayList<Integer>[] adj; static boolean vis[]; 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(); adj= new ArrayList[n]; vis= new boolean[n]; for(int i =0;i<n;i++){ adj[i]=new ArrayList(); } int [] a = sc.nextIntArray(n); int [] b = sc.nextIntArray(n); ArrayList<Pair>x = new ArrayList<>(); ArrayList<Pair>y= new ArrayList<>(); for(int i =0;i<n;i++){ int [] tmp = new int [2]; tmp[0]=a[i]; tmp[1]=b[i]; x.add(new Pair(i , tmp , 0)); y.add(new Pair(i , tmp , 1)); } Collections.sort(x); // we will have it sorted according to the values of x Collections.sort(y); // we will have it sorted according to the values of y // System.out.println("checking if the sorting is correct"); // for(int i =0;i<n;i++){ // System.out.print(x.get(i).a[0]+" "); // } // System.out.println(); // for(int i =0;i<n;i++){ // System.out.print(y.get(i).a[1]+" "); // } // we need to start building the graph // 44 12 11 10 // 20 19 15 10 for(int i=0;i<n-1;i++){ int u = x.get(i).idx; int v = x.get(i+1).idx; adj[v].add(u); u = y.get(i).idx; v = y.get(i+1).idx; adj[v].add(u); } if(x.get(0).a[0]>=y.get(0).a[1]){ dfs(x.get(0).idx); }else{ dfs(y.get(0).idx); } StringBuilder ans = new StringBuilder(); for(int i =0;i<n;i++){ ans.append((vis[i]?"1":"0")); } pw.println(ans); // we will call dfs from the maximum possible indx } pw.close(); } static void dfs(int u){ vis[u]=true; for(int x : adj[u]){ if(!vis[x]){ dfs(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 { 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>{ int idx; int [] a; int sort; Pair(int idx , int [] a , int sort){ this.idx=idx; this.a=a; this.sort=sort; } @Override public int compareTo(Pair p) { if(sort==0){ // sort according to the x return p.a[0]-this.a[0]; } return p.a[1]-this.a[1]; } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
29fd198a4e1fcc8f3df5e43770cce878
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class C_Round_758 { public static int MOD = 998244353; static double[][][] dp; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int T = in.nextInt(); for (int z = 0; z < T; z++) { int n = in.nextInt(); int[][] data = new int[n][3]; for (int j = 0; j < 2; j++) { for (int i = 0; i < n; i++) { data[i][j] = in.nextInt(); } } for (int i = 0; i < n; i++) { data[i][2] = i; } boolean[] check = new boolean[n]; TreeMap<Integer, Integer>[] map = new TreeMap[2]; for (int i = 0; i < map.length; i++) { map[i] = new TreeMap<>(); } for (int i = 0; i < n; i++) { for (int j = 0; j < map.length; j++) { map[j].put(data[i][j], i); } } LinkedList<Integer> q = new LinkedList<>(); int one = map[0].lastEntry().getValue(); int two = map[1].lastEntry().getValue(); check[one] = true; check[two] = true; map[1].remove(data[one][1]); q.add(one); if (one != two) { q.add(two); map[0].remove(data[two][0]); } //System.out.println(q); while (!q.isEmpty()) { int v = q.poll(); for (int i = 0; i < map.length; i++) { while (!map[i].isEmpty()) { Integer tmp = map[i].higherKey(data[v][i]); if (tmp == null) { break; } int index = map[i].get(tmp); check[index] = true; q.add(index); map[1 - i].remove(data[index][1 - i]); map[i].remove(tmp); } } } for (int i = 0; i < n; i++) { out.print(check[i] ? 1 : 0); } out.println(); } out.close(); } static int abs(int a) { return a < 0 ? -a : a; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point { int x; int y; public Point(int start, int end) { this.x = start; this.y = end; } public String toString() { return x + " " + y; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return (val * val); } else { return (val * ((val * a))); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
b07073dbc073cc53944928e9a1e28fed
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.reflect.Array; import java.util.*; import java.util.stream.Stream; public class Program { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws NumberFormatException, IOException { int cases = Integer.parseInt(reader.readLine()); int mod = 998244353; while(cases-- > 0) { String[] firstLine = reader.readLine().split(" "); int n = Integer.parseInt(firstLine[0]); int[] A = convertToIntPrimitiveArray(reader.readLine().split(" ")); int[] B = convertToIntPrimitiveArray(reader.readLine().split(" ")); int[] copyA = new int[n]; int[] copyB = new int[n]; Map<Integer, Integer> mapA = new HashMap<>(); Map<Integer, Integer> mapB = new HashMap<>(); for(int i=0;i<n;i++) { mapA.put(A[i], B[i]); mapB.put(B[i], A[i]); copyA[i] = A[i]; copyB[i] = B[i]; } Arrays.sort(A); Arrays.sort(B); int i=n-1; int j=n-1; int minA = A[n-1]; int minB = B[n-1]; while(true) { int pi=i; int pj=j; while(i>=0 && A[i] >= minA) { minB = Math.min(minB, mapA.get(A[i])); i--; } while(j>=0 && B[j] >= minB) { minA = Math.min(minA, mapB.get(B[j])); j--; } if(pi==i&&pj==j) { break; } } for(int k=0;k<n;k++) { if(copyA[k] >= minA || copyB[k] >= minB) { out.append("1"); }else { out.append("0"); } } out.append("\n"); } out.flush(); } public static int[] convertToIntPrimitiveArray(String[] str) { return Stream.of(str).mapToInt(Integer::parseInt).toArray(); } public static Integer[] convertToIntArray(String[] str) { Integer[] arr = new Integer[str.length]; for(int i=0;i<str.length;i++) { arr[i] = Integer.parseInt(str[i]); } return arr; } public static Long[] convertToLongArray(String[] str) { Long[] arr = new Long[str.length]; for(int i=0;i<str.length;i++) { arr[i] = Long.parseLong(str[i]); } return arr; } public static long[] convertToLongPrimitiveArray(String[] str) { return Stream.of(str).mapToLong(Long::parseLong).toArray(); } public static void printYes() throws IOException { out.append("YES" + "\n"); } public static void printNo() throws IOException { out.append("NO" + "\n"); } public static void printNumber(long num) throws IOException { out.append(num + "\n"); } public static long hcf(long a, long b) { if(b==0) return a; return hcf(b, a%b); } public static int findSet(int[] parent, int[] rank, int v) { if(v==parent[v]) { return v; } parent[v] = findSet(parent, rank, parent[v]); return parent[v]; } public static void unionSet(int[] parent, int[] rank, int a, int b) { a = findSet(parent, rank, a); b = findSet(parent, rank, b); if(a == b) { return; } if(rank[a] < rank[b]) { int temp = a; a = b; b = temp; } parent[b] = a; if(rank[a] == rank[b]) { rank[a]++; } } public static void makeSet(int[] parent, int[] rank, int v) { parent[v] = v; rank[v] = 0; } public static long modularDivision(long a, long b, int mod) { if(a==0) return 1; a %= mod; long res = 1L; while(b > 0) { if((b&1)==1) { res = (res * a)%mod; } a = (a*a)%mod; b >>= 1; } return res; } public static void customSort(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); return; } public static long[] factorial(int n, int mod) { long[] fact = new long[n+1]; fact[0] = 1; for(int i=1;i<fact.length;i++) { fact[i] = (i*fact[i-1] + mod)%mod; } return fact; } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
5934b66077b12389f067a0b1cfd28e4c
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import static java.lang.Math.*; // Sachin_2961 submission // public class CodeforcesA { public void solve() { int n = fs.nInt(); PairI[]players = new PairI[n+1]; players[0] = new PairI(0,0,0); for(int i=1;i<=n;i++){ players[i] = new PairI(fs.nInt(),0,i); } for(int i=1;i<=n;i++){ players[i].s = fs.nInt(); } Arrays.sort(players,Comparator.comparingInt(o -> o.f)); char[]ans = new char[n+1]; int[]dp = new int[n+1],pre = new int[n+1],suf = new int[n+2]; for(int i=1;i<=n;i++) pre[i] = max(players[i].s,pre[i-1]); suf[n+1] = Integer.MAX_VALUE; for(int i=n;i>=1;i--){ suf[i] = min(players[i].s,suf[i+1]); int lo = i, hi = n; while( lo < hi ){ int mid = (lo+hi+1)>>1; if(suf[mid] <= pre[i])lo = mid; else hi = mid-1; } if( lo == i)dp[i] = i; else dp[i] = dp[lo]; if( dp[i] == n )ans[players[i].ind] = '1'; else ans[players[i].ind] = '0'; } for(int i=1;i<=n;i++) out.print(ans[i]); out.println(); } static class Pair{ int f,s; Pair(int f,int s){ this.f = f; this.s = s; } } static class PairI{ int f,s,ind; PairI(int f,int s,int ind){ this.f = f; this.s = s; this.ind = ind; } } static boolean multipleTestCase = true; static FastScanner fs; static PrintWriter out; public void run(){ fs = new FastScanner(); out = new PrintWriter(System.out); int tc = (multipleTestCase)?fs.nInt():1; while (tc-->0)solve(); out.flush(); out.close(); } public static void main(String[]args){ try{ new CodeforcesA().run(); }catch (Exception e){ e.printStackTrace(); } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String n() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String Line() { String str = ""; try { str = br.readLine(); }catch (IOException e) { e.printStackTrace(); } return str; } int nInt() {return Integer.parseInt(n()); } long nLong() {return Long.parseLong(n());} double nDouble(){return Double.parseDouble(n());} int[]aI(int n){ int[]ar = new int[n]; for(int i=0;i<n;i++) ar[i] = nInt(); return ar; } } public static void sort(int[] arr){ ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } public static void sort(long[] arr){ ArrayList<Long> ls = new ArrayList<>(); for(long x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
f9af26377471d901ecc243ee95e61441
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import org.omg.PortableInterceptor.INACTIVE; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class gamemaster { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); int tcasenum = Integer.parseInt(f.readLine()); StringBuilder sb = new StringBuilder(); for(int g=0; g<tcasenum; g++) { int n = Integer.parseInt(f.readLine()); StringTokenizer st1 = new StringTokenizer(f.readLine()); StringTokenizer st2 = new StringTokenizer(f.readLine()); Player[] p1 = new Player[n]; Player[] p2 = new Player[n]; for(int i=0; i<n; i++){ Player player = new Player(i, Integer.parseInt(st1.nextToken()),Integer.parseInt(st2.nextToken())); p1[i]=player; p2[i]=player; } Arrays.sort(p1, new Comparator<Player>() { @Override public int compare(Player o1, Player o2) { return Integer.compare(o1.x, o2.x); } }); Arrays.sort(p2, new Comparator<Player>() { @Override public int compare(Player o1, Player o2) { return Integer.compare(o1.y, o2.y); } }); ArrayList<HashSet<Integer>> adjlist = new ArrayList<>(); for (int i = 0; i < p1.length; i++) { adjlist.add(new HashSet<>()); } for (int i = 0; i < p1.length - 1; i++) { adjlist.get(p1[i].ind).add(p1[i + 1].ind); adjlist.get(p2[i].ind).add(p2[i + 1].ind); } HashSet<Integer> vals = new HashSet<>(); dfs(p1[p1.length - 1].ind, adjlist, vals); for (int i = 0; i<n; i++){ if(vals.contains(i)){ sb.append(1); }else{ sb.append(0); } } sb.append("\n"); } System.out.print(sb); } public static void dfs (int pos,ArrayList<HashSet<Integer>> adjlist, HashSet<Integer> vals){ if(!vals.contains(pos)){ vals.add(pos); for(Integer x: adjlist.get(pos)){ dfs(x,adjlist,vals); } } } } class Player{ int ind; int x; int y; public Player(int ind, int x, int y){ this.ind = ind; this.x = x; this.y = y; } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
ab888150f7fa7d8ae8f154d37988a6ea
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static Scanner sc = new Scanner(System.in); // static Reader sc = new Reader(); static StringBuilder out = new StringBuilder(); static String testCase = "Case #"; static long mod = 998244353; public static void main(String[] args) throws IOException { // TODO Auto-generated method stub int t = sc.nextInt(); int tc = 0; while (tc++ < t) { Solution run = new Solution(); run.run(); } System.out.println(out); } static ArrayList<Integer> gr[]; public void run() throws IOException { int n=sc.nextInt(); int a[][]=new int [n][2]; int b[][]=new int [n][2]; gr=new ArrayList[n]; for(int i=0;i<n;i++) { a[i][0]=sc.nextInt(); a[i][1]=i; gr[i]=new ArrayList<Integer>(); } for(int i=0;i<n;i++) { b[i][0]=sc.nextInt(); b[i][1]=i; } Arrays.sort(a,(c,d)-> (d[0]-c[0])); Arrays.sort(b,(c,d)-> (d[0]-c[0])); for(int i=1;i<n;i++) { gr[a[i][1]].add(a[i-1][1]); gr[b[i][1]].add(b[i-1][1]); } int root=0; if(a[0][0]>=b[0][0]) { root=a[0][1]; } else root= b[0][1]; visit =new boolean [n]; dfs(root); for(int i=0;i<n;i++) { if(visit[i])out.append(1); else out.append(0); } out.append("\n"); } static boolean visit[]; static void dfs(int u) { visit[u]=true; for(int ch : gr[u]) { if(!visit[ch]) { dfs(ch); } } } static int bit[]; static void modify(int x, int val) { for (; x < bit.length; x += (x & -x)) bit[x] += val; } static int get(int x) { int sum = 0; for (; x > 0; x -= (x & -x)) sum += bit[x]; return sum; } static long modInverse(long a, long m) { long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient long q = a / m; long t = m; m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } 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(); } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
c6407506e1e93412160b9484aad274ae
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; public class C_758 { public static final long[] POWER2 = generatePOWER2(); public static final IteratorBuffer<Long> ITERATOR_BUFFER_PRIME = new IteratorBuffer<>(streamPrime(1000000).iterator()); public static long BIG = 1000000000 + 7; private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer stringTokenizer = null; private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static class Array<Type> implements Iterable<Type> { private final Object[] array; public Array(int size) { this.array = new Object[size]; } public Array(int size, Type element) { this(size); Arrays.fill(this.array, element); } public Array(Array<Type> array, Type element) { this(array.size() + 1); for (int index = 0; index < array.size(); index++) { set(index, array.get(index)); } set(size() - 1, element); } public Array(List<Type> list) { this(list.size()); int index = 0; for (Type element: list) { set(index, element); index += 1; } } public Type get(int index) { return (Type) this.array[index]; } @Override public Iterator<Type> iterator() { return new Iterator<Type>() { int index = 0; @Override public boolean hasNext() { return this.index < size(); } @Override public Type next() { Type result = Array.this.get(index); index += 1; return result; } }; } public Array set(int index, Type value) { this.array[index] = value; return this; } public int size() { return this.array.length; } public List<Type> toList() { List<Type> result = new ArrayList<>(); for (Type element: this) { result.add(element); } return result; } @Override public String toString() { return "[" + C_758.toString(this, ", ") + "]"; } } static class BIT { private static int lastBit(int index) { return index & -index; } private final long[] tree; public BIT(int size) { this.tree = new long[size]; } public void add(int index, long delta) { index += 1; while (index <= this.tree.length) { tree[index - 1] += delta; index += lastBit(index); } } public long prefix(int end) { long result = 0; while (end > 0) { result += this.tree[end - 1]; end -= lastBit(end); } return result; } public int size() { return this.tree.length; } public long sum(int start, int end) { return prefix(end) - prefix(start); } } static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> { public final TypeVertex vertex0; public final TypeVertex vertex1; public final boolean bidirectional; public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional) { this.vertex0 = vertex0; this.vertex1 = vertex1; this.bidirectional = bidirectional; this.vertex0.edges.add(getThis()); if (this.bidirectional) { this.vertex1.edges.add(getThis()); } } public abstract TypeEdge getThis(); public TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex) { TypeVertex result; if (vertex0 == vertex) { result = vertex1; } else { result = vertex0; } return result; } public void remove() { this.vertex0.edges.remove(getThis()); if (this.bidirectional) { this.vertex1.edges.remove(getThis()); } } @Override public String toString() { return this.vertex0 + "->" + this.vertex1; } } public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>> { public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional) { super(vertex0, vertex1, bidirectional); } @Override public EdgeDefault<TypeVertex> getThis() { return this; } } public static class EdgeDefaultDefault extends Edge<VertexDefaultDefault, EdgeDefaultDefault> { public EdgeDefaultDefault(VertexDefaultDefault vertex0, VertexDefaultDefault vertex1, boolean bidirectional) { super(vertex0, vertex1, bidirectional); } @Override public EdgeDefaultDefault getThis() { return this; } } public static class FIFO<Type> { public SingleLinkedList<Type> start; public SingleLinkedList<Type> end; public FIFO() { this.start = null; this.end = null; } public boolean isEmpty() { return this.start == null; } public Type peek() { return this.start.element; } public Type pop() { Type result = this.start.element; this.start = this.start.next; return result; } public void push(Type element) { SingleLinkedList<Type> list = new SingleLinkedList<>(element, null); if (this.start == null) { this.start = list; this.end = list; } else { this.end.next = list; this.end = list; } } } static class Fraction implements Comparable<Fraction> { public static final Fraction ZERO = new Fraction(0, 1); public static Fraction fraction(long whole) { return fraction(whole, 1); } public static Fraction fraction(long numerator, long denominator) { Fraction result; if (denominator == 0) { throw new ArithmeticException(); } if (numerator == 0) { result = Fraction.ZERO; } else { int sign; if (numerator < 0 ^ denominator < 0) { sign = -1; numerator = Math.abs(numerator); denominator = Math.abs(denominator); } else { sign = 1; } long gcd = gcd(numerator, denominator); result = new Fraction(sign * numerator / gcd, denominator / gcd); } return result; } public final long numerator; public final long denominator; private Fraction(long numerator, long denominator) { this.numerator = numerator; this.denominator = denominator; } public Fraction add(Fraction fraction) { return fraction(this.numerator * fraction.denominator + fraction.numerator * this.denominator, this.denominator * fraction.denominator); } @Override public int compareTo(Fraction that) { return Long.compare(this.numerator * that.denominator, that.numerator * this.denominator); } public Fraction divide(Fraction fraction) { return multiply(fraction.inverse()); } public boolean equals(Fraction that) { return this.compareTo(that) == 0; } public boolean equals(Object that) { return this.compareTo((Fraction) that) == 0; } public Fraction getRemainder() { return fraction(this.numerator - getWholePart() * denominator, denominator); } public long getWholePart() { return this.numerator / this.denominator; } public Fraction inverse() { return fraction(this.denominator, this.numerator); } public Fraction multiply(Fraction fraction) { return fraction(this.numerator * fraction.numerator, this.denominator * fraction.denominator); } public Fraction neg() { return fraction(-this.numerator, this.denominator); } public Fraction sub(Fraction fraction) { return add(fraction.neg()); } @Override public String toString() { String result; if (getRemainder().equals(Fraction.ZERO)) { result = "" + this.numerator; } else { result = this.numerator + "/" + this.denominator; } return result; } } static class IteratorBuffer<Type> { private Iterator<Type> iterator; private List<Type> list; public IteratorBuffer(Iterator<Type> iterator) { this.iterator = iterator; this.list = new ArrayList<Type>(); } public Iterator<Type> iterator() { return new Iterator<Type>() { int index = 0; @Override public boolean hasNext() { return this.index < list.size() || IteratorBuffer.this.iterator.hasNext(); } @Override public Type next() { if (list.size() <= this.index) { list.add(iterator.next()); } Type result = list.get(index); index += 1; return result; } }; } } public static class MapCount<Type> extends SortedMapAVL<Type, Long> { private int count; public MapCount(Comparator<? super Type> comparator) { super(comparator); this.count = 0; } public long add(Type key, Long delta) { long result; if (delta > 0) { Long value = get(key); if (value == null) { value = delta; } else { value += delta; } put(key, value); result = delta; } else { result = 0; } this.count += result; return result; } public int count() { return this.count; } public List<Type> flatten() { List<Type> result = new ArrayList<>(); for (Entry<Type, Long> entry: entrySet()) { for (long index = 0; index < entry.getValue(); index++) { result.add(entry.getKey()); } } return result; } @Override public SortedMapAVL<Type, Long> headMap(Type keyEnd) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends Type, ? extends Long> map) { throw new UnsupportedOperationException(); } public long remove(Type key, Long delta) { long result; if (delta > 0) { Long value = get(key) - delta; if (value <= 0) { result = delta + value; remove(key); } else { result = delta; put(key, value); } } else { result = 0; } this.count -= result; return result; } @Override public Long remove(Object key) { Long result = super.remove(key); this.count -= result; return result; } @Override public SortedMapAVL<Type, Long> subMap(Type keyStart, Type keyEnd) { throw new UnsupportedOperationException(); } @Override public SortedMapAVL<Type, Long> tailMap(Type keyStart) { throw new UnsupportedOperationException(); } } public static class MapSet<TypeKey, TypeValue> extends SortedMapAVL<TypeKey, SortedSetAVL<TypeValue>> implements Iterable<TypeValue> { private Comparator<? super TypeValue> comparatorValue; public MapSet(Comparator<? super TypeKey> comparatorKey, Comparator<? super TypeValue> comparatorValue) { super(comparatorKey); this.comparatorValue = comparatorValue; } public MapSet(Comparator<? super TypeKey> comparatorKey, SortedSetAVL<Entry<TypeKey, SortedSetAVL<TypeValue>>> entrySet, Comparator<? super TypeValue> comparatorValue) { super(comparatorKey, entrySet); this.comparatorValue = comparatorValue; } public boolean add(TypeKey key, TypeValue value) { SortedSetAVL<TypeValue> set = computeIfAbsent(key, k -> new SortedSetAVL<>(comparatorValue)); return set.add(value); } public TypeValue firstValue() { TypeValue result; Entry<TypeKey, SortedSetAVL<TypeValue>> firstEntry = firstEntry(); if (firstEntry == null) { result = null; } else { result = firstEntry.getValue().first(); } return result; } @Override public MapSet<TypeKey, TypeValue> headMap(TypeKey keyEnd) { return new MapSet<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)), this.comparatorValue); } public Iterator<TypeValue> iterator() { return new Iterator<TypeValue>() { Iterator<SortedSetAVL<TypeValue>> iteratorValues = values().iterator(); Iterator<TypeValue> iteratorValue = null; @Override public boolean hasNext() { return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext()); } @Override public TypeValue next() { if (iteratorValue == null || !iteratorValue.hasNext()) { iteratorValue = iteratorValues.next().iterator(); } return iteratorValue.next(); } }; } public TypeValue lastValue() { TypeValue result; Entry<TypeKey, SortedSetAVL<TypeValue>> lastEntry = lastEntry(); if (lastEntry == null) { result = null; } else { result = lastEntry.getValue().last(); } return result; } public boolean removeSet(TypeKey key, TypeValue value) { boolean result; SortedSetAVL<TypeValue> set = get(key); if (set == null) { result = false; } else { result = set.remove(value); if (set.size() == 0) { remove(key); } } return result; } @Override public MapSet<TypeKey, TypeValue> tailMap(TypeKey keyStart) { return new MapSet<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)), this.comparatorValue); } } public static class Matrix { public final int rows; public final int columns; public final Fraction[][] cells; public Matrix(int rows, int columns) { this.rows = rows; this.columns = columns; this.cells = new Fraction[rows][columns]; for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { set(row, column, Fraction.ZERO); } } } public void add(int rowSource, int rowTarget, Fraction fraction) { for (int column = 0; column < columns; column++) { this.cells[rowTarget][column] = this.cells[rowTarget][column].add(this.cells[rowSource][column].multiply(fraction)); } } private int columnPivot(int row) { int result = this.columns; for (int column = this.columns - 1; 0 <= column; column--) { if (this.cells[row][column].compareTo(Fraction.ZERO) != 0) { result = column; } } return result; } public void reduce() { for (int rowMinimum = 0; rowMinimum < this.rows; rowMinimum++) { int rowPivot = rowPivot(rowMinimum); if (rowPivot != -1) { int columnPivot = columnPivot(rowPivot); Fraction current = this.cells[rowMinimum][columnPivot]; Fraction pivot = this.cells[rowPivot][columnPivot]; Fraction fraction = pivot.inverse().sub(current.divide(pivot)); add(rowPivot, rowMinimum, fraction); for (int row = rowMinimum + 1; row < this.rows; row++) { if (columnPivot(row) == columnPivot) { add(rowMinimum, row, this.cells[row][columnPivot(row)].neg()); } } } } } private int rowPivot(int rowMinimum) { int result = -1; int pivotColumnMinimum = this.columns; for (int row = rowMinimum; row < this.rows; row++) { int pivotColumn = columnPivot(row); if (pivotColumn < pivotColumnMinimum) { result = row; pivotColumnMinimum = pivotColumn; } } return result; } public void set(int row, int column, Fraction value) { this.cells[row][column] = value; } public String toString() { String result = ""; for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { result += this.cells[row][column] + "\t"; } result += "\n"; } return result; } } public static class Node<Type> { public static <Type> Node<Type> balance(Node<Type> result) { while (result != null && 1 < Math.abs(height(result.left) - height(result.right))) { if (height(result.left) < height(result.right)) { Node<Type> right = result.right; if (height(right.right) < height(right.left)) { result = new Node<>(result.value, result.left, right.rotateRight()); } result = result.rotateLeft(); } else { Node<Type> left = result.left; if (height(left.left) < height(left.right)) { result = new Node<>(result.value, left.rotateLeft(), result.right); } result = result.rotateRight(); } } return result; } public static <Type> Node<Type> clone(Node<Type> result) { if (result != null) { result = new Node<>(result.value, clone(result.left), clone(result.right)); } return result; } public static <Type> Node<Type> delete(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { if (node.left == null) { result = node.right; } else { if (node.right == null) { result = node.left; } else { Node<Type> first = first(node.right); result = new Node<>(first.value, node.left, delete(node.right, first.value, comparator)); } } } else { if (compare < 0) { result = new Node<>(node.value, delete(node.left, value, comparator), node.right); } else { result = new Node<>(node.value, node.left, delete(node.right, value, comparator)); } } result = balance(result); } return result; } public static <Type> Node<Type> first(Node<Type> result) { while (result.left != null) { result = result.left; } return result; } public static <Type> Node<Type> get(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = node; } else { if (compare < 0) { result = get(node.left, value, comparator); } else { result = get(node.right, value, comparator); } } } return result; } public static <Type> Node<Type> head(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = node.left; } else { if (compare < 0) { result = head(node.left, value, comparator); } else { result = new Node<>(node.value, node.left, head(node.right, value, comparator)); } } result = balance(result); } return result; } public static int height(Node node) { return node == null ? 0 : node.height; } public static <Type> Node<Type> insert(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = new Node<>(value, null, null); } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = new Node<>(value, node.left, node.right); ; } else { if (compare < 0) { result = new Node<>(node.value, insert(node.left, value, comparator), node.right); } else { result = new Node<>(node.value, node.left, insert(node.right, value, comparator)); } } result = balance(result); } return result; } public static <Type> Node<Type> last(Node<Type> result) { while (result.right != null) { result = result.right; } return result; } public static int size(Node node) { return node == null ? 0 : node.size; } public static <Type> Node<Type> tail(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = new Node<>(node.value, null, node.right); } else { if (compare < 0) { result = new Node<>(node.value, tail(node.left, value, comparator), node.right); } else { result = tail(node.right, value, comparator); } } result = balance(result); } return result; } public static <Type> void traverseOrderIn(Node<Type> node, Consumer<Type> consumer) { if (node != null) { traverseOrderIn(node.left, consumer); consumer.accept(node.value); traverseOrderIn(node.right, consumer); } } public final Type value; public final Node<Type> left; public final Node<Type> right; public final int size; private final int height; public Node(Type value, Node<Type> left, Node<Type> right) { this.value = value; this.left = left; this.right = right; this.size = 1 + size(left) + size(right); this.height = 1 + Math.max(height(left), height(right)); } public Node<Type> rotateLeft() { Node<Type> left = new Node<>(this.value, this.left, this.right.left); return new Node<>(this.right.value, left, this.right.right); } public Node<Type> rotateRight() { Node<Type> right = new Node<>(this.value, this.left.right, this.right); return new Node<>(this.left.value, this.left.left, right); } } public static class SingleLinkedList<Type> { public final Type element; public SingleLinkedList<Type> next; public SingleLinkedList(Type element, SingleLinkedList<Type> next) { this.element = element; this.next = next; } public void toCollection(Collection<Type> collection) { if (this.next != null) { this.next.toCollection(collection); } collection.add(this.element); } } public static class SmallSetIntegers { public static final int SIZE = 20; public static final int[] SET = generateSet(); public static final int[] COUNT = generateCount(); public static final int[] INTEGER = generateInteger(); private static int count(int set) { int result = 0; for (int integer = 0; integer < SIZE; integer++) { if (0 < (set & set(integer))) { result += 1; } } return result; } private static final int[] generateCount() { int[] result = new int[1 << SIZE]; for (int set = 0; set < result.length; set++) { result[set] = count(set); } return result; } private static final int[] generateInteger() { int[] result = new int[1 << SIZE]; Arrays.fill(result, -1); for (int integer = 0; integer < SIZE; integer++) { result[SET[integer]] = integer; } return result; } private static final int[] generateSet() { int[] result = new int[SIZE]; for (int integer = 0; integer < result.length; integer++) { result[integer] = set(integer); } return result; } private static int set(int integer) { return 1 << integer; } } public static class SortedMapAVL<TypeKey, TypeValue> implements SortedMap<TypeKey, TypeValue> { public final Comparator<? super TypeKey> comparator; public final SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet; public SortedMapAVL(Comparator<? super TypeKey> comparator) { this(comparator, new SortedSetAVL<>((entry0, entry1) -> comparator.compare(entry0.getKey(), entry1.getKey()))); } private SortedMapAVL(Comparator<? super TypeKey> comparator, SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet) { this.comparator = comparator; this.entrySet = entrySet; } @Override public void clear() { this.entrySet.clear(); } @Override public Comparator<? super TypeKey> comparator() { return this.comparator; } @Override public boolean containsKey(Object key) { return this.entrySet().contains(new AbstractMap.SimpleEntry<>((TypeKey) key, null)); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } @Override public SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet() { return this.entrySet; } public Entry<TypeKey, TypeValue> firstEntry() { return this.entrySet.first(); } @Override public TypeKey firstKey() { return firstEntry().getKey(); } @Override public TypeValue get(Object key) { Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null); entry = this.entrySet.get(entry); return entry == null ? null : entry.getValue(); } @Override public SortedMapAVL<TypeKey, TypeValue> headMap(TypeKey keyEnd) { return new SortedMapAVL<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null))); } @Override public boolean isEmpty() { return this.entrySet.isEmpty(); } @Override public Set<TypeKey> keySet() { return new SortedSet<TypeKey>() { @Override public boolean add(TypeKey typeKey) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends TypeKey> collection) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Comparator<? super TypeKey> comparator() { throw new UnsupportedOperationException(); } @Override public boolean contains(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public TypeKey first() { throw new UnsupportedOperationException(); } @Override public SortedSet<TypeKey> headSet(TypeKey typeKey) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return size() == 0; } @Override public Iterator<TypeKey> iterator() { final Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator(); return new Iterator<TypeKey>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public TypeKey next() { return iterator.next().getKey(); } }; } @Override public TypeKey last() { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public int size() { return SortedMapAVL.this.entrySet.size(); } @Override public SortedSet<TypeKey> subSet(TypeKey typeKey, TypeKey e1) { throw new UnsupportedOperationException(); } @Override public SortedSet<TypeKey> tailSet(TypeKey typeKey) { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Override public <T> T[] toArray(T[] ts) { throw new UnsupportedOperationException(); } }; } public Entry<TypeKey, TypeValue> lastEntry() { return this.entrySet.last(); } @Override public TypeKey lastKey() { return lastEntry().getKey(); } @Override public TypeValue put(TypeKey key, TypeValue value) { TypeValue result = get(key); Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>(key, value); this.entrySet().add(entry); return result; } @Override public void putAll(Map<? extends TypeKey, ? extends TypeValue> map) { map.entrySet() .forEach(entry -> put(entry.getKey(), entry.getValue())); } @Override public TypeValue remove(Object key) { TypeValue result = get(key); Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null); this.entrySet.remove(entry); return result; } @Override public int size() { return this.entrySet().size(); } @Override public SortedMapAVL<TypeKey, TypeValue> subMap(TypeKey keyStart, TypeKey keyEnd) { return new SortedMapAVL<>(this.comparator, this.entrySet.subSet(new AbstractMap.SimpleEntry<>(keyStart, null), new AbstractMap.SimpleEntry<>(keyEnd, null))); } @Override public SortedMapAVL<TypeKey, TypeValue> tailMap(TypeKey keyStart) { return new SortedMapAVL<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null))); } @Override public String toString() { return this.entrySet().toString(); } @Override public Collection<TypeValue> values() { return new Collection<TypeValue>() { @Override public boolean add(TypeValue typeValue) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends TypeValue> collection) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean contains(Object value) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return SortedMapAVL.this.entrySet.isEmpty(); } @Override public Iterator<TypeValue> iterator() { return new Iterator<TypeValue>() { Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator(); @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public TypeValue next() { return this.iterator.next().getValue(); } }; } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public int size() { return SortedMapAVL.this.entrySet.size(); } @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Override public <T> T[] toArray(T[] ts) { throw new UnsupportedOperationException(); } }; } } public static class SortedSetAVL<Type> implements SortedSet<Type> { public Comparator<? super Type> comparator; public Node<Type> root; private SortedSetAVL(Comparator<? super Type> comparator, Node<Type> root) { this.comparator = comparator; this.root = root; } public SortedSetAVL(Comparator<? super Type> comparator) { this(comparator, null); } public SortedSetAVL(Collection<? extends Type> collection, Comparator<? super Type> comparator) { this(comparator, null); this.addAll(collection); } public SortedSetAVL(SortedSetAVL<Type> sortedSetAVL) { this(sortedSetAVL.comparator, Node.clone(sortedSetAVL.root)); } @Override public boolean add(Type value) { int sizeBefore = size(); this.root = Node.insert(this.root, value, this.comparator); return sizeBefore != size(); } @Override public boolean addAll(Collection<? extends Type> collection) { return collection.stream() .map(this::add) .reduce(true, (x, y) -> x | y); } @Override public void clear() { this.root = null; } @Override public Comparator<? super Type> comparator() { return this.comparator; } @Override public boolean contains(Object value) { return Node.get(this.root, (Type) value, this.comparator) != null; } @Override public boolean containsAll(Collection<?> collection) { return collection.stream() .allMatch(this::contains); } @Override public Type first() { return Node.first(this.root).value; } public Type get(Type value) { Node<Type> node = Node.get(this.root, value, this.comparator); return node == null ? null : node.value; } @Override public SortedSetAVL<Type> headSet(Type valueEnd) { return new SortedSetAVL<>(this.comparator, Node.head(this.root, valueEnd, this.comparator)); } @Override public boolean isEmpty() { return this.root == null; } @Override public Iterator<Type> iterator() { Stack<Node<Type>> path = new Stack<>(); return new Iterator<Type>() { { push(SortedSetAVL.this.root); } @Override public boolean hasNext() { return !path.isEmpty(); } @Override public Type next() { if (path.isEmpty()) { throw new NoSuchElementException(); } else { Node<Type> node = path.peek(); Type result = node.value; if (node.right != null) { push(node.right); } else { do { node = path.pop(); } while (!path.isEmpty() && path.peek().right == node); } return result; } } public void push(Node<Type> node) { while (node != null) { path.push(node); node = node.left; } } }; } @Override public Type last() { return Node.last(this.root).value; } @Override public boolean remove(Object value) { int sizeBefore = size(); this.root = Node.delete(this.root, (Type) value, this.comparator); return sizeBefore != size(); } @Override public boolean removeAll(Collection<?> collection) { return collection.stream() .map(this::remove) .reduce(true, (x, y) -> x | y); } @Override public boolean retainAll(Collection<?> collection) { SortedSetAVL<Type> set = new SortedSetAVL<>(this.comparator); collection.stream() .map(element -> (Type) element) .filter(this::contains) .forEach(set::add); boolean result = size() != set.size(); this.root = set.root; return result; } @Override public int size() { return this.root == null ? 0 : this.root.size; } @Override public SortedSetAVL<Type> subSet(Type valueStart, Type valueEnd) { return tailSet(valueStart).headSet(valueEnd); } @Override public SortedSetAVL<Type> tailSet(Type valueStart) { return new SortedSetAVL<>(this.comparator, Node.tail(this.root, valueStart, this.comparator)); } @Override public Object[] toArray() { return toArray(new Object[0]); } @Override public <T> T[] toArray(T[] ts) { List<Object> list = new ArrayList<>(); Node.traverseOrderIn(this.root, list::add); return list.toArray(ts); } @Override public String toString() { return "{" + C_758.toString(this, ", ") + "}"; } } public static class Tree2D { public static final int SIZE = 1 << 30; public static final Tree2D[] TREES_NULL = new Tree2D[]{null, null, null, null}; public static boolean contains(int x, int y, int left, int bottom, int size) { return left <= x && x < left + size && bottom <= y && y < bottom + size; } public static int count(Tree2D[] trees) { int result = 0; for (int index = 0; index < 4; index++) { if (trees[index] != null) { result += trees[index].count; } } return result; } public static int count ( int rectangleLeft, int rectangleBottom, int rectangleRight, int rectangleTop, Tree2D tree, int left, int bottom, int size ) { int result; if (tree == null) { result = 0; } else { int right = left + size; int top = bottom + size; int intersectionLeft = Math.max(rectangleLeft, left); int intersectionBottom = Math.max(rectangleBottom, bottom); int intersectionRight = Math.min(rectangleRight, right); int intersectionTop = Math.min(rectangleTop, top); if (intersectionRight <= intersectionLeft || intersectionTop <= intersectionBottom) { result = 0; } else { if (intersectionLeft == left && intersectionBottom == bottom && intersectionRight == right && intersectionTop == top) { result = tree.count; } else { size = size >> 1; result = 0; for (int index = 0; index < 4; index++) { result += count ( rectangleLeft, rectangleBottom, rectangleRight, rectangleTop, tree.trees[index], quadrantLeft(left, size, index), quadrantBottom(bottom, size, index), size ); } } } } return result; } public static int quadrantBottom(int bottom, int size, int index) { return bottom + (index >> 1) * size; } public static int quadrantLeft(int left, int size, int index) { return left + (index & 1) * size; } public final Tree2D[] trees; public final int count; private Tree2D(Tree2D[] trees, int count) { this.trees = trees; this.count = count; } public Tree2D(Tree2D[] trees) { this(trees, count(trees)); } public Tree2D() { this(TREES_NULL); } public int count(int rectangleLeft, int rectangleBottom, int rectangleRight, int rectangleTop) { return count ( rectangleLeft, rectangleBottom, rectangleRight, rectangleTop, this, 0, 0, SIZE ); } public Tree2D setPoint ( int x, int y, Tree2D tree, int left, int bottom, int size ) { Tree2D result; if (contains(x, y, left, bottom, size)) { if (size == 1) { result = new Tree2D(TREES_NULL, 1); } else { size = size >> 1; Tree2D[] trees = new Tree2D[4]; for (int index = 0; index < 4; index++) { trees[index] = setPoint ( x, y, tree == null ? null : tree.trees[index], quadrantLeft(left, size, index), quadrantBottom(bottom, size, index), size ); } result = new Tree2D(trees); } } else { result = tree; } return result; } public Tree2D setPoint(int x, int y) { return setPoint ( x, y, this, 0, 0, SIZE ); } } public static class Tuple2<Type0, Type1> { public final Type0 v0; public final Type1 v1; public Tuple2(Type0 v0, Type1 v1) { this.v0 = v0; this.v1 = v1; } @Override public String toString() { return "(" + this.v0 + ", " + this.v1 + ")"; } } public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>> { public Tuple2Comparable(Type0 v0, Type1 v1) { super(v0, v1); } @Override public int compareTo(Tuple2Comparable<Type0, Type1> that) { int result = this.v0.compareTo(that.v0); if (result == 0) { result = this.v1.compareTo(that.v1); } return result; } } public static class Tuple3<Type0, Type1, Type2> { public final Type0 v0; public final Type1 v1; public final Type2 v2; public Tuple3(Type0 v0, Type1 v1, Type2 v2) { this.v0 = v0; this.v1 = v1; this.v2 = v2; } @Override public String toString() { return "(" + this.v0 + ", " + this.v1 + ", " + this.v2 + ")"; } } public static class Vertex < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>> { public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult > TypeResult breadthFirstSearch ( TypeVertex vertex, TypeEdge edge, BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function, Array<Boolean> visited, FIFO<TypeVertex> verticesNext, FIFO<TypeEdge> edgesNext, TypeResult result ) { if (!visited.get(vertex.index)) { visited.set(vertex.index, true); result = function.apply(vertex, edge, result); for (TypeEdge edgeNext: vertex.edges) { TypeVertex vertexNext = edgeNext.other(vertex); if (!visited.get(vertexNext.index)) { verticesNext.push(vertexNext); edgesNext.push(edgeNext); } } } return result; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult > TypeResult breadthFirstSearch ( Array<TypeVertex> vertices, int indexVertexStart, BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function, TypeResult result ) { Array<Boolean> visited = new Array<>(vertices.size(), false); FIFO<TypeVertex> verticesNext = new FIFO<>(); verticesNext.push(vertices.get(indexVertexStart)); FIFO<TypeEdge> edgesNext = new FIFO<>(); edgesNext.push(null); while (!verticesNext.isEmpty()) { result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result); } return result; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > boolean cycle ( TypeVertex start, SortedSet<TypeVertex> result ) { boolean cycle = false; Stack<TypeVertex> stackVertex = new Stack<>(); Stack<TypeEdge> stackEdge = new Stack<>(); stackVertex.push(start); stackEdge.push(null); while (!stackVertex.isEmpty()) { TypeVertex vertex = stackVertex.pop(); TypeEdge edge = stackEdge.pop(); if (!result.contains(vertex)) { result.add(vertex); for (TypeEdge otherEdge: vertex.edges) { if (otherEdge != edge) { TypeVertex otherVertex = otherEdge.other(vertex); if (result.contains(otherVertex)) { cycle = true; } else { stackVertex.push(otherVertex); stackEdge.push(otherEdge); } } } } } return cycle; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > SortedSet<TypeVertex> depthFirstSearch ( TypeVertex start, BiConsumer<TypeVertex, TypeEdge> functionVisitPre, BiConsumer<TypeVertex, TypeEdge> functionVisitPost ) { SortedSet<TypeVertex> result = new SortedSetAVL<>(Comparator.naturalOrder()); Stack<TypeVertex> stackVertex = new Stack<>(); Stack<TypeEdge> stackEdge = new Stack<>(); stackVertex.push(start); stackEdge.push(null); while (!stackVertex.isEmpty()) { TypeVertex vertex = stackVertex.pop(); TypeEdge edge = stackEdge.pop(); if (result.contains(vertex)) { functionVisitPost.accept(vertex, edge); } else { result.add(vertex); stackVertex.push(vertex); stackEdge.push(edge); functionVisitPre.accept(vertex, edge); for (TypeEdge otherEdge: vertex.edges) { TypeVertex otherVertex = otherEdge.other(vertex); if (!result.contains(otherVertex)) { stackVertex.push(otherVertex); stackEdge.push(otherEdge); } } } } return result; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > SortedSet<TypeVertex> depthFirstSearch ( TypeVertex start, Consumer<TypeVertex> functionVisitPreVertex, Consumer<TypeVertex> functionVisitPostVertex ) { BiConsumer<TypeVertex, TypeEdge> functionVisitPreVertexEdge = (vertex, edge) -> { functionVisitPreVertex.accept(vertex); }; BiConsumer<TypeVertex, TypeEdge> functionVisitPostVertexEdge = (vertex, edge) -> { functionVisitPostVertex.accept(vertex); }; return depthFirstSearch(start, functionVisitPreVertexEdge, functionVisitPostVertexEdge); } public final int index; public final List<TypeEdge> edges; public Vertex(int index) { this.index = index; this.edges = new ArrayList<>(); } @Override public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that) { return Integer.compare(this.index, that.index); } @Override public String toString() { return "" + this.index; } } public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge> { public VertexDefault(int index) { super(index); } } public static class VertexDefaultDefault extends Vertex<VertexDefaultDefault, EdgeDefaultDefault> { public static Array<VertexDefaultDefault> vertices(int n) { Array<VertexDefaultDefault> result = new Array<>(n); for (int index = 0; index < n; index++) { result.set(index, new VertexDefaultDefault(index)); } return result; } public VertexDefaultDefault(int index) { super(index); } } public static class Wrapper<Type> { public Type value; public Wrapper(Type value) { this.value = value; } public Type get() { return this.value; } public void set(Type value) { this.value = value; } @Override public String toString() { return this.value.toString(); } } public static void add(int delta, int[] result) { for (int index = 0; index < result.length; index++) { result[index] += delta; } } public static void add(int delta, int[]... result) { for (int index = 0; index < result.length; index++) { add(delta, result[index]); } } public static long add(long x, long y) { return (x + y) % BIG; } public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end) { return -binarySearchMinimum(x -> filter.apply(-x), -end, -start); } public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end) { int result; if (start == end) { result = end; } else { int middle = start + (end - start) / 2; if (filter.apply(middle)) { result = binarySearchMinimum(filter, start, middle); } else { result = binarySearchMinimum(filter, middle + 1, end); } } return result; } public static void close() { out.close(); } private static void combinations(int n, int k, int start, SortedSet<Integer> combination, List<SortedSet<Integer>> result) { if (k == 0) { result.add(new SortedSetAVL<>(combination, Comparator.naturalOrder())); } else { for (int index = start; index < n; index++) { if (!combination.contains(index)) { combination.add(index); combinations(n, k - 1, index + 1, combination, result); combination.remove(index); } } } } public static List<SortedSet<Integer>> combinations(int n, int k) { List<SortedSet<Integer>> result = new ArrayList<>(); combinations(n, k, 0, new SortedSetAVL<>(Comparator.naturalOrder()), result); return result; } public static <Type> int compare(Iterator<Type> iterator0, Iterator<Type> iterator1, Comparator<Type> comparator) { int result = 0; while (result == 0 && iterator0.hasNext() && iterator1.hasNext()) { result = comparator.compare(iterator0.next(), iterator1.next()); } if (result == 0) { if (iterator1.hasNext()) { result = -1; } else { if (iterator0.hasNext()) { result = 1; } } } return result; } public static <Type> int compare(Iterable<Type> iterable0, Iterable<Type> iterable1, Comparator<Type> comparator) { return compare(iterable0.iterator(), iterable1.iterator(), comparator); } public static long divideCeil(long x, long y) { return (x + y - 1) / y; } public static Set<Long> divisors(long n) { SortedSetAVL<Long> result = new SortedSetAVL<>(Comparator.naturalOrder()); result.add(1L); for (Long factor: factors(n)) { SortedSetAVL<Long> divisors = new SortedSetAVL<>(result); for (Long divisor: result) { divisors.add(divisor * factor); } result = divisors; } return result; } public static LinkedList<Long> factors(long n) { LinkedList<Long> result = new LinkedList<>(); Iterator<Long> primes = ITERATOR_BUFFER_PRIME.iterator(); Long prime; while (n > 1 && (prime = primes.next()) * prime <= n) { while (n % prime == 0) { result.add(prime); n /= prime; } } if (n > 1) { result.add(n); } return result; } public static long faculty(int n) { long result = 1; for (int index = 2; index <= n; index++) { result *= index; } return result; } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public static long[] generatePOWER2() { long[] result = new long[63]; for (int x = 0; x < result.length; x++) { result[x] = 1L << x; } return result; } public static boolean isPrime(long x) { boolean result = x > 1; Iterator<Long> iterator = ITERATOR_BUFFER_PRIME.iterator(); Long prime; while ((prime = iterator.next()) * prime <= x) { result &= x % prime > 0; } return result; } public static long knapsack(List<Tuple3<Long, Integer, Integer>> itemsValueWeightCount, int weightMaximum) { long[] valuesMaximum = new long[weightMaximum + 1]; for (Tuple3<Long, Integer, Integer> itemValueWeightCount: itemsValueWeightCount) { long itemValue = itemValueWeightCount.v0; int itemWeight = itemValueWeightCount.v1; int itemCount = itemValueWeightCount.v2; for (int weight = weightMaximum; 0 <= weight; weight--) { for (int index = 1; index <= itemCount && 0 <= weight - index * itemWeight; index++) { valuesMaximum[weight] = Math.max(valuesMaximum[weight], valuesMaximum[weight - index * itemWeight] + index * itemValue); } } } long result = 0; for (long valueMaximum: valuesMaximum) { result = Math.max(result, valueMaximum); } return result; } public static boolean knapsackPossible(List<Tuple2<Integer, Integer>> itemsWeightCount, int weightMaximum) { boolean[] weightPossible = new boolean[weightMaximum + 1]; weightPossible[0] = true; int weightLargest = 0; for (Tuple2<Integer, Integer> itemWeightCount: itemsWeightCount) { int itemWeight = itemWeightCount.v0; int itemCount = itemWeightCount.v1; for (int weightStart = 0; weightStart < itemWeight; weightStart++) { int count = 0; for (int weight = weightStart; weight <= weightMaximum && (0 < count || weight <= weightLargest); weight += itemWeight) { if (weightPossible[weight]) { count = itemCount; } else { if (0 < count) { weightPossible[weight] = true; weightLargest = weight; count -= 1; } } } } } return weightPossible[weightMaximum]; } public static long lcm(int a, int b) { return a * b / gcd(a, b); } public static void main(String[] args) { try { solve(); } catch (IOException exception) { exception.printStackTrace(); } close(); } public static long mul(long x, long y) { return (x * y) % BIG; } public static double nextDouble() throws IOException { return Double.parseDouble(nextString()); } public static int nextInt() throws IOException { return Integer.parseInt(nextString()); } public static void nextInts(int n, int[]... result) throws IOException { for (int index = 0; index < n; index++) { for (int value = 0; value < result.length; value++) { result[value][index] = nextInt(); } } } public static int[] nextInts(int n) throws IOException { int[] result = new int[n]; nextInts(n, result); return result; } public static String nextLine() throws IOException { return bufferedReader.readLine(); } public static long nextLong() throws IOException { return Long.parseLong(nextString()); } public static void nextLongs(int n, long[]... result) throws IOException { for (int index = 0; index < n; index++) { for (int value = 0; value < result.length; value++) { result[value][index] = nextLong(); } } } public static long[] nextLongs(int n) throws IOException { long[] result = new long[n]; nextLongs(n, result); return result; } public static String nextString() throws IOException { while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens())) { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } return stringTokenizer.nextToken(); } public static String[] nextStrings(int n) throws IOException { String[] result = new String[n]; { for (int index = 0; index < n; index++) { result[index] = nextString(); } } return result; } public static <T> List<T> permutation(long p, List<T> x) { List<T> copy = new ArrayList<>(); for (int index = 0; index < x.size(); index++) { copy.add(x.get(index)); } List<T> result = new ArrayList<>(); for (int indexTo = 0; indexTo < x.size(); indexTo++) { int indexFrom = (int) p % copy.size(); p = p / copy.size(); result.add(copy.remove(indexFrom)); } return result; } public static <Type> List<List<Type>> permutations(List<Type> list) { List<List<Type>> result = new ArrayList<>(); result.add(new ArrayList<>()); for (Type element: list) { List<List<Type>> permutations = result; result = new ArrayList<>(); for (List<Type> permutation: permutations) { for (int index = 0; index <= permutation.size(); index++) { List<Type> permutationNew = new ArrayList<>(permutation); permutationNew.add(index, element); result.add(permutationNew); } } } return result; } public static long[][] sizeGroup2CombinationsCount(int maximum) { long[][] result = new long[maximum + 1][maximum + 1]; for (int length = 0; length <= maximum; length++) { result[length][0] = 1; for (int group = 1; group <= length; group++) { result[length][group] = add(result[length - 1][group - 1], result[length - 1][group]); } } return result; } public static Stream<BigInteger> streamFibonacci() { return Stream.generate(new Supplier<BigInteger>() { private BigInteger n0 = BigInteger.ZERO; private BigInteger n1 = BigInteger.ONE; @Override public BigInteger get() { BigInteger result = n0; n0 = n1; n1 = result.add(n0); return result; } }); } public static Stream<Long> streamPrime(int sieveSize) { return Stream.generate(new Supplier<Long>() { private boolean[] isPrime = new boolean[sieveSize]; private long sieveOffset = 2; private List<Long> primes = new ArrayList<>(); private int index = 0; public void filter(long prime, boolean[] result) { if (prime * prime < this.sieveOffset + sieveSize) { long remainingStart = this.sieveOffset % prime; long start = remainingStart == 0 ? 0 : prime - remainingStart; for (long index = start; index < sieveSize; index += prime) { result[(int) index] = false; } } } public void generatePrimes() { Arrays.fill(this.isPrime, true); this.primes.forEach(prime -> filter(prime, isPrime)); for (int index = 0; index < sieveSize; index++) { if (isPrime[index]) { this.primes.add(this.sieveOffset + index); filter(this.sieveOffset + index, isPrime); } } this.sieveOffset += sieveSize; } @Override public Long get() { while (this.primes.size() <= this.index) { generatePrimes(); } Long result = this.primes.get(this.index); this.index += 1; return result; } }); } public static <Type> String toString(Iterator<Type> iterator, String separator) { StringBuilder stringBuilder = new StringBuilder(); if (iterator.hasNext()) { stringBuilder.append(iterator.next()); } while (iterator.hasNext()) { stringBuilder.append(separator); stringBuilder.append(iterator.next()); } return stringBuilder.toString(); } public static <Type> String toString(Iterator<Type> iterator) { return toString(iterator, " "); } public static <Type> String toString(Iterable<Type> iterable, String separator) { return toString(iterable.iterator(), separator); } public static <Type> String toString(Iterable<Type> iterable) { return toString(iterable, " "); } public static long totient(long n) { Set<Long> factors = new SortedSetAVL<>(factors(n), Comparator.naturalOrder()); long result = n; for (long p: factors) { result -= result / p; } return result; } interface BiFunctionResult<Type0, Type1, TypeResult> { TypeResult apply(Type0 x0, Type1 x1, TypeResult x2); } public static int min(int[] x) { int result = 2000000000; for (int i = 0; i < x.length; i++) { result = Math.min(x[i], result); } return result; } static class Player { public final int a; public final int b; public Player(int a, int b) { this.a = a; this.b = b; } } public static void solve() throws IOException { int t = nextInt(); for (int test = 0; test < t; test++) { int n = nextInt(); int[] as = nextInts(n); int[] bs = nextInts(n); List<Player> players = new ArrayList<>(); for (int i = 0; i < n; i++) { players.add(new Player(as[i], bs[i])); } SortedSet<Player> playersA = new TreeSet<>(new Comparator<Player>() { @Override public int compare(Player p0, Player p1) { return Integer.compare(p1.a, p0.a); } }); playersA.addAll(players); SortedSet<Player> playersB = new TreeSet<>(new Comparator<Player>() { @Override public int compare(Player p0, Player p1) { return Integer.compare(p1.b, p0.b); } }); playersB.addAll(players); int minA = playersA.first().a; int minB = playersB.first().b; while (!playersA.isEmpty() && (minA <= playersA.first().a || minB <= playersB.first().b)) { if (minA <= playersA.first().a) { minB = Math.min(minB, playersA.first().b); playersA.remove(playersA.first()); } else { minA = Math.min(minA, playersB.first().a); playersB.remove(playersB.first()); } } for (Player player: players) { System.out.print(minA <= player.a || minB <= player.b ? 1 : 0); } System.out.println(); } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
6651cf32958b2724cd522344b85cf3c0
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
//package Div2.C; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class GameMaster { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t>0){ int n=Integer.parseInt(br.readLine()); String[] str = br.readLine().split(" "); int []a=new int[n]; for(int i=0;i<n;i++) a[i]=Integer.parseInt(str[i]); str = br.readLine().split(" "); int []b=new int[n]; for(int i=0;i<n;i++) b[i]=Integer.parseInt(str[i]); TreeSet<Node> atree = new TreeSet<>((n1,n2)->{ return Integer.compare(n1.aval, n2.aval); }); for(int i=0;i<n;i++) { atree.add(new Node(a[i], b[i], i)); } TreeSet<Node> btree = new TreeSet<>((n1,n2)->{ return Integer.compare(n1.bval, n2.bval); }); for(int i=0;i<n;i++) { btree.add(new Node(a[i], b[i], i)); } boolean []visited=new boolean[n]; bfs(atree, btree, visited); StringBuilder ans=new StringBuilder(); for(int i=0;i<n;i++){ ans.append(visited[i]?'1':'0'); } System.out.println(ans); t--; } } private static class Node{ int aval; int bval; int pos; Node(int aval, int bval, int pos){ this.aval=aval; this.bval=bval; this.pos=pos; } } private static void bfs(TreeSet<Node> a, TreeSet<Node> b, boolean []visited){ Queue<Node> q = new LinkedList<>(); Node lastOfA = a.last(); q.add(lastOfA); visited[lastOfA.pos] = true; a.remove(lastOfA); Node lastOfB = b.last(); if (!visited[lastOfB.pos]) { q.add(lastOfB); visited[lastOfB.pos] = true; b.remove(lastOfB); } while(!q.isEmpty()){ Node nd=q.poll(); Node higher = a.higher(nd); while(higher!=null && !visited[higher.pos]){ q.add(higher); visited[higher.pos]=true; a.remove(higher); higher = a.higher(nd); } higher = b.higher(nd); while(higher !=null && !visited[higher.pos]){ q.add(higher); visited[higher.pos]=true; b.remove(higher); higher = b.higher(nd); } } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
1b45350a122a0df2bd386f5da37d177b
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.util.*; import java.io.*; ////*************************************************************************** /* 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 C_Game_Master{ 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){ int n=s.nextInt(); long array1[]= new long[n]; yoyo obj5 = new yoyo(); PriorityQueue<pair> nice1 = new PriorityQueue<pair>(obj5); long array2[]= new long[n]; PriorityQueue<pair> nice2 = new PriorityQueue<pair>(obj5); for(int i=0;i<n;i++){ array1[i]=s.nextLong(); pair obj2 = new pair(array1[i],i); nice1.add(obj2); } for(int i=0;i<n;i++){ array2[i]=s.nextLong(); pair obj2 = new pair(array2[i],i); nice2.add(obj2); } ArrayList<pair> well1 = new ArrayList<pair>(n+4); long array3[]= new long[n]; ArrayList<pair> well2 = new ArrayList<pair>(n+4); long array4[]= new long[n]; for(int i=0;i<n;i++){ pair obj= nice1.poll(); well1.add(obj); array3[(int)obj.b]=i; } for(int i=0;i<n;i++){ pair obj= nice2.poll(); well2.add(obj); array4[(int)obj.b]=i; } long yes[]= new long[n]; solve(well1,array3,well2,array4,yes,n); long yes1[]= new long[n]; solve(well2,array4,well1,array3,yes1,n); for(int i=0;i<n;i++){ long hh=(yes[i]|yes1[i]); res.append(hh); } res.append(" \n"); p++; } System.out.println(res); } private static void solve(ArrayList<pair> well1, long[] array3, ArrayList<pair> well2, long[] array4, long[] yes, int n) { Queue<Long> nice = new LinkedList<Long>(); long visited1[]= new long[n]; long visited2[]= new long[n]; nice.add(well1.get(n-1).b); int check=1; while(!nice.isEmpty()){ Queue<Long> nice2 = new LinkedList<Long>(); if(check==1){ // i have well1 ke numbers while(!nice.isEmpty()){ long num=nice.poll(); yes[(int)num]=1; long index=array4[(int)num]; visited2[(int)(index)]=1; for(long j=index+1;j<n;j++){ if(visited2[(int)j]==1){ break; } pair obj3 = well2.get((int)j); nice2.add(obj3.b); visited2[(int)j]=1; } } check=0; } else{ /// while(!nice.isEmpty()){ long num=nice.poll(); yes[(int)num]=1; long index=array3[(int)num]; visited1[(int)(index)]=1; for(long j=index+1;j<n;j++){ if(visited1[(int)j]==1){ break; } pair obj3 = well1.get((int)j); nice2.add(obj3.b); visited1[(int)j]=1; } } check=1; /// } nice=nice2; } } 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; } static class pair{ long a; long b; pair(long c, long d){ a=c; b=d; } } static class yoyo implements Comparator<pair>{ public int compare(pair o1, pair o2) { // TODO Auto-generated method stub if(o1.a<o2.a){ return -1; } else{ return 1; } } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
bb709ab8df79213904b395d62ff176db
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.*;import java.util.*;import java.math.*;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 a[]=ari(n); int b[]=ari(n); int f[]=new int[n]; Integer aa[][]=new Integer[2][n]; for(int x=0;x<n;x++)aa[0][x]=aa[1][x]=x; sort(aa[0],(aaa,bbb)->-(a[aaa]-a[bbb])); sort(aa[1],(aaa,bbb)->-(b[aaa]-b[bbb])); LinkedList<int[]> l=new LinkedList<>(); l.add(new int[]{aa[0][0],0}); l.add(new int[]{aa[1][0],1}); int i[][]=new int[2][n]; for(int x=0;x<n;x++) { i[0][aa[0][x]]=x; i[1][aa[1][x]]=x; } boolean bo[][]=new boolean[2][n]; bo[0][0]=bo[1][0]=true; while(l.size()>0) { int r[]=l.remove(); int e=r[0]; f[e]=1; int ii=r[1]; int oi=-1; int it=1-ii; if(ii==0)oi=i[1][e]; else oi=i[0][e]; for(int x=oi;x>=0;x--) { if(bo[it][x])break; bo[it][x]=true; l.add(new int[]{aa[it][x],it}); } } s(f); } p(sb); } void f(){out.flush();} 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}}; long mod=1000000007l;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[] 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 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){sb.append(s);sb.append("\n");}void sl(int s){sb.append(s);sb.append("\n");}void sl(long s){sb .append(s);sb.append("\n");}void sl(char s) {sb.append(s);sb.append("\n");}void sl(double s){sb.append(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);}long gcd(long a,long b){while(b>0l){long c=a%b;a=b;b=c;}return a;}int gcd(int a,int b) {while(b>0){int c=a%b;a=b;b=c;}return a;}boolean pa(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]=true;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 p(Object p){out.print(p);}void p(String p){out.print(p);}void p(int p) {out.print(p);}void p(double p){out.print(p);}void p(long p){out.print(p);}void p(char p){out.print(p);}void p(boolean p){out.print(p);}void pl(Object p){out.println(p);}void pl(String p){out.println(p);}void pl(int p) {out.println(p);}void pl(char p){out.println(p);}void pl(double p){out.println(p);}void pl(long p){out. println(p);}void pl(boolean p) {out.println(p);}void pl(){out.println();}void s(int a[]){for(int e:a) {sb.append(e);}sb.append("\n");} void s(long a[]) {for(long e:a){sb.append(e);sb.append(' ') ;}sb.append("\n");}void s(int ar[][]){for(int a[]:ar){for(int 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(char ar[][]) {for(char a[]:ar){for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");}}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;}int[][] ari(int n,int m)throws IOException {int ar[][]=new int[n][m];for(int x=0;x<n;x++){if (!st.hasMoreTokens())st=new StringTokenizer (bq.readLine());for(int y=0;y<m;y++)ar[x][y]=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;}long[][] arl(int n,int m)throws IOException {long ar[][]=new long[n][m];for(int x=0;x<n;x++) {if(!st.hasMoreTokens()) st=new StringTokenizer(bq.readLine());for(int y=0;y<m;y++)ar[x][y]=Long.parseLong(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;}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;}double[][] ard (int n,int m)throws IOException{double ar[][]=new double[n][m];for(int x=0;x<n;x++) {if(!st.hasMoreTokens()) st=new StringTokenizer(bq.readLine());for(int y=0;y<m;y++) ar[x][y]=Double.parseDouble(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;}char[][] arc(int n,int m)throws IOException {char ar[][]=new char[n][m];for(int x=0;x<n;x++){String s=bq.readLine(); for(int y=0;y<m;y++)ar[x][y]=s.charAt(y);}return ar;}void p(int ar[]) {StringBuilder sb=new StringBuilder (2*ar.length);for(int a:ar){sb.append(a);sb.append(' ');}out.println(sb);}void p(int ar[][]) {StringBuilder sb=new StringBuilder(2*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 (2*ar.length);for(long a:ar){ sb.append(a);sb.append(' ');}out.println(sb);} void p(long ar[][]) {StringBuilder sb=new StringBuilder(2*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(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(double ar[]) {StringBuilder sb=new StringBuilder(2*ar.length);for(double a:ar){sb.append(a); sb.append(' ');}out.println(sb);}void p (double ar[][]){StringBuilder sb=new StringBuilder(2* 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);for(char aa:ar){sb.append(aa); sb.append(' ');}out.println(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 (int... ar){for(int e:ar)p(e+" ");pl();}void pl(long... ar){for(long e:ar)p(e+" ");pl();} }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
c68f5a324f40cc7e7ae49bfac43f6433
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class C { static BufferedReader br; static StringTokenizer st; static PrintWriter pw; static String nextToken() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } static int nextInt() { return Integer.parseInt(nextToken()); } static long nextLong() { return Long.parseLong(nextToken()); } static double nextDouble() { return Double.parseDouble(nextToken()); } static String nextLine() { try { return br.readLine(); } catch (IOException e) { throw new IllegalArgumentException(); } } static char nextChar() { try { return (char) br.read(); } catch (IOException e) { throw new IllegalArgumentException(e); } } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); int t = 1; t = nextInt(); while (t-- > 0) { solve(); } pw.close(); } private static void solve() { int n = nextInt(); int[][] arr = new int[n][4]; for (int i = 0; i < n; i++) { arr[i][0] = i; arr[i][1] = nextInt(); } for (int i = 0; i < n; i++) { arr[i][2] = nextInt(); } Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o2[1]-o1[1]; } }); arr[0][3] = 1; int id = 0; int m2 = arr[0][2]; int m2loc = arr[0][2]; for (int i = 1; i < n; i++) { if (arr[i][2] > m2) { id = i; m2 = m2loc; } else { if (arr[i][2] < m2loc) { m2loc = arr[i][2]; } } } for (int i = 0; i <= id; i++) { arr[i][3] = 1; } Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0]-o2[0]; } }); for (int i = 0; i < n; i++) { pw.print(arr[i][3]); } pw.println(); } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
e36d187d18fefe1e60405f923576b8e1
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; 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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { int numTests = in.nextInt(); for (int test = 0; test < numTests; test++) { int n = in.nextInt(); SCCGraph g = new SCCGraph(n); for (int step = 0; step < 2; step++) { Person[] a = new Person[n]; for (int i = 0; i < n; i++) { a[i] = new Person(); a[i].strength = in.nextInt(); a[i].id = i; } Arrays.sort(a); for (int i = 1; i < n; i++) { g.addEdge(a[i].id, a[i - 1].id); } } g.findSCC(); char[] ans = new char[n]; Arrays.fill(ans, '0'); for (int i = 0; i < n; i++) { if (g.comp[i] == g.numComps - 1) { ans[i] = '1'; } } out.println(new String(ans)); } } class Person implements Comparable<Person> { int strength; int id; public int compareTo(Person o) { if (strength != o.strength) { return strength < o.strength ? -1 : 1; } return 0; } } class SCCGraph { int n; int numComps; int[] low; int[] vis; int[] comp; boolean[] onStack; int[] stack; int sp; int globalTime; int numEdges; int[] firstEdge; int[] edgeDst = new int[10]; int[] edgeNxt = new int[10]; SCCGraph(int n) { this.n = n; vis = new int[n]; low = new int[n]; stack = new int[n]; comp = new int[n]; onStack = new boolean[n]; firstEdge = new int[n]; clear(); } public void clear() { Arrays.fill(firstEdge, -1); numEdges = 0; } private void addEdge(int a, int b) { int e = numEdges++; if (e >= edgeDst.length) { int k = edgeDst.length; edgeDst = Arrays.copyOf(edgeDst, k * 3 / 2 + 1); edgeNxt = Arrays.copyOf(edgeNxt, k * 3 / 2 + 1); } edgeDst[e] = b; edgeNxt[e] = firstEdge[a]; firstEdge[a] = e; } public void findSCC() { Arrays.fill(vis, -1); Arrays.fill(onStack, false); sp = 0; globalTime = 0; numComps = 0; for (int i = 0; i < n; i++) { if (vis[i] < 0) { dfsTarjan(i); } } } void dfsTarjan(int v) { vis[v] = globalTime; low[v] = globalTime; ++globalTime; stack[sp++] = v; onStack[v] = true; for (int e = firstEdge[v]; e >= 0; e = edgeNxt[e]) { int u = edgeDst[e]; if (vis[u] < 0) { dfsTarjan(u); if (low[v] > low[u]) { low[v] = low[u]; } } else if (onStack[u] && low[v] > vis[u]) { low[v] = vis[u]; } } if (low[v] == vis[v]) { while (true) { int u = stack[--sp]; onStack[u] = false; comp[u] = numComps; if (u == v) { break; } } ++numComps; } } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { try { in = new BufferedReader(new InputStreamReader(stream, "UTF-8")); } catch (Exception e) { throw new AssertionError(); } } public String next() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 8
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
9a1a64c6733256a636a898aecc29b682
train_109.jsonl
1639217100
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
256 megabytes
import java.util.*; import java.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class Round758C { MyPrintWriter out; MyScanner in; // final static long FIXED_RANDOM; // static { // FIXED_RANDOM = System.currentTimeMillis(); // } final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void initIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); Round758C sol = new Round758C(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; boolean hasMultipleTests = true; initIO(isFileIO); int t = hasMultipleTests? in.nextInt() : 1; for (int i = 1; i <= t; ++i) { if(isDebug){ out.printf("Test %d\n", i); } getInput(); solve(); printOutput(); } in.close(); out.close(); } // use suitable one between matrix(2, n) or matrix(n, 2) for graph edges, pairs, ... int n; int[] a, b; void getInput() { n = in.nextInt(); a = in.nextIntArray(n); b = in.nextIntArray(n); } void printOutput() { out.println(ans); } String ans; void solve(){ // for i to win, // he can win all j s.t. a[i] > a[j] or b[i] > b[j] // other player j must be losable to some another player j' // suppose a[max_a] and b[max_b] have largest value, resp. // if b[i] > b[max_a] // we can elim all other players: use max_a to eliminate all the other players // if a[i] > a[max_b] // we can elim all other players: use max_b to eliminate all the other players // if b[i] < b[max_a] and a[i] < a[max_b] // a[i] < a[max_a], b[i] < b[max_b] // i cannot battle with max_a nor max_b // however, max_a or max_b can be eliminated by some other player! // suppose b[i] < b[max_a] < b[j] // a[i] < a[max_b] < a[k] // find minimum a[j] among j s.t. b[j] > b[max_a] // same for k as well // a[i] > a[j], b[i] > b[k] must hold // if j != k // then winning against whoever win is enough // // b[j] < b[k] // if j is winnable, // winning j is enough to win the game // // start from maxIndexA // add all indices i s.t. b[i] > b[maxIndexA] // then we add all indices j s.t. a[j] > a[i] for such i // then we add all indices k s.t. // continue this until there is nothing new added Pair[] pa = new Pair[n]; for(int i=0; i<n; i++) pa[i] = new Pair(a[i], i); Arrays.sort(pa); Pair[] pb = new Pair[n]; for(int i=0; i<n; i++) pb[i] = new Pair(b[i], i); Arrays.sort(pb); int[] indexToRankA = new int[n]; for(int i=0; i<n; i++) indexToRankA[pa[i].second] = i; int[] indexToRankB = new int[n]; for(int i=0; i<n; i++) indexToRankB[pb[i].second] = i; boolean[] winnableA = solve(pa, pb, indexToRankA, indexToRankB); boolean[] winnableB = solve(pb, pa, indexToRankB, indexToRankA); // int maxIndexA = 0; // int maxIndexB = 0; // for(int i=1; i<n; i++) { // if(a[i] > a[maxIndexA]) // maxIndexA = i; // if(b[i] > b[maxIndexB]) // maxIndexB = i; // } // 9 // 1 9 3 2 7 5 6 10 0 // 100 300 500 299 600 277 399 455 355 // a[maxIndexB] = 7 // b[maxIndexA] = 455 // 0 1 1 0 1 0 0 1 0 StringBuilder sb = new StringBuilder(); for(int i=0; i<n; i++) { if(winnableA[i] || winnableB[i]) sb.append('1'); else sb.append('0'); // if(i == maxIndexA || i == maxIndexB) // sb.append('1'); // else if(a[i] > a[maxIndexB] || b[i] > b[maxIndexA]) // sb.append('1'); // else // sb.append('0'); } ans = sb.toString(); } private boolean[] solve(Pair[] pa, Pair[] pb, int[] indexToRankA, int[] indexToRankB) { // start from maxIndexA // add all indices i s.t. b[i] > b[maxIndexA] // then we add all indices j s.t. a[j] > a[i] for such i // then we add all indices k s.t. // continue this until there is nothing new added HashSet<Integer> curr = new HashSet<>(); curr.add(pa[n-1].second); boolean turnA = false; int aFrom = n-1; int bFrom = n; while(!curr.isEmpty()) { HashSet<Integer> next = new HashSet<>(); if(turnA) { int aFromNext = aFrom; for(int index: curr) aFromNext = Math.min(aFromNext, indexToRankA[index]+1); for(int i=aFromNext; i<aFrom; i++) next.add(pa[i].second); aFrom = aFromNext; turnA = false; } else { int bFromNext = bFrom; // add all indices i s.t. b[i] > b[maxIndexA] for(int index: curr) { bFromNext = Math.min(bFromNext, indexToRankB[index]+1); } for(int i=bFromNext; i<bFrom; i++) next.add(pb[i].second); bFrom = bFromNext; turnA = true; } curr = next; } boolean[] ans = new boolean[n]; for(int i=0; i<n; i++) { if(indexToRankA[i] >= aFrom || indexToRankB[i] >= bFrom) ans[i] = true; } return ans; } static class Pair implements Comparable<Pair>{ final static long FIXED_RANDOM = System.currentTimeMillis(); int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int hashCode() { // http://xorshift.di.unimi.it/splitmix64.c long x = first; x <<= 32; x += second; x += FIXED_RANDOM; x += 0x9e3779b97f4a7c15l; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l; x = (x ^ (x >> 27)) * 0x94d049bb133111ebl; return (int)(x ^ (x >> 31)); } @Override public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; Pair other = (Pair) obj; return first == other.first && second == other.second; } @Override public String toString() { return "[" + first + "," + second + "]"; } @Override public int compareTo(Pair o) { int cmp = Integer.compare(first, o.first); return cmp != 0? cmp: Integer.compare(second, o.second); } } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[][] nextMatrix(int n, int m) { return nextMatrix(n, m, 0); } int[][] nextMatrix(int n, int m, int offset) { int[][] mat = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[i][j] = nextInt()+offset; } } return mat; } int[][] nextTransposedMatrix(int n, int m){ return nextTransposedMatrix(n, m, 0); } int[][] nextTransposedMatrix(int n, int m, int offset){ int[][] mat = new int[m][n]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[j][i] = nextInt()+offset; } } return mat; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } String[] nextStringArray(int len) { String[] s = new String[len]; for(int i=0; i<len; i++) s[i] = next(); return s; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean ans) { if(ans) println(YES); else println(NO); } public void printAns(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(long[] arr){ printAns(arr); println(); } public void printAns(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(int[] arr){ printAns(arr); println(); } public <T> void printAns(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void printlnAns(ArrayList<T> arr){ printAns(arr); println(); } public void printAns(int[] arr, int add){ if(arr != null && arr.length > 0){ print(arr[0]+add); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]+add); } } } public void printlnAns(int[] arr, int add){ printAns(arr, add); println(); } public void printAns(ArrayList<Integer> arr, int add) { if(arr != null && arr.size() > 0){ print(arr.get(0)+add); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)+add); } } } public void printlnAns(ArrayList<Integer> arr, int add){ printAns(arr, add); println(); } public void printlnAnsSplit(long[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public void printlnAnsSplit(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void printlnAnsSplit(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private void permutateAndSort(long[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); long temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private void permutateAndSort(int[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); int temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][][] constructDirectedNeighborhood(int n, int[][] e){ int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegree[u]++; inDegree[v]++; } int[][] inNeighbors = new int[n][]; int[][] outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][--outDegree[u]] = v; inNeighbors[v][--inDegree[v]] = u; } return new int[][][] {inNeighbors, outNeighbors}; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][--degree[u]] = v; neighbors[v][--degree[v]] = u; } return neighbors; } static private void drawGraph(int[][] e) { makeDotUndirected(e); try { final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot") .redirectOutput(new File("graph.png")) .start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
1 second
["0001\n1111\n1"]
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Java 17
standard input
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
f9cf1a6971a7003078b63195198e5a51
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
standard output
PASSED
3e583b37101c7c0cfb54d530a0709fc1
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.util.*; import java.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class Round758D { MyPrintWriter out; MyScanner in; // final static long FIXED_RANDOM; // static { // FIXED_RANDOM = System.currentTimeMillis(); // } final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void initIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); Round758D sol = new Round758D(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; boolean hasMultipleTests = false; initIO(isFileIO); int t = hasMultipleTests? in.nextInt() : 1; for (int i = 1; i <= t; ++i) { if(isDebug){ out.printf("Test %d\n", i); } getInput(); solve(); printOutput(); } in.close(); out.close(); } // use suitable one between matrix(2, n) or matrix(n, 2) for graph edges, pairs, ... int n; String[] domino; void getInput() { n = in.nextInt(); domino = in.nextStringArray(n); } void printOutput() { out.printlnAns(ans); } final long MOD = 998244353; long ans; void solve(){ // BB // ?? // W? // ?? // 1) # of B in right cell and # of W in left cell must be same // 2) and symmetrically for W and B, resp. // to put it differently, // if the left cell has x B's and y W's, // then the right cell should have y B's and x W's // for each of x and y, check if this is possible // need lPx and rPy where l and r are # of ? in left cell and right cell, resp // is this enough? // XB - WX // i) XB - WB - WX // ii) XB - WW - BX // case 1) # of B in the left cell is 1 // BB // W? // W? // W? // 3 ways to choose BBW // case 2) # of B in the left cell is 2 // BB // B? // W? // W? // 3 ways to choose BWW // BB // W? // W? // B? // 3 ways to choose BWW // case 3) # of B in the left cell is 3 // BB // B? // W? // B? // 1 way to choose WWW // counter example: // ?? // W? // x=0 // W? // W? // x=1 // B? // W? // BB // WW // However, the following is impossible: // BW // WB // the problem is a domino cannot make the match with itself // BW // WB // WB // WB // WB // BB // WW // WB WB WB WB WW BW BB // WB WB WW BW BW BW BB // if WB and BW both exist, then BB and WW must exist // WB WB ... WB WW BW BW .... BW BB WW BB WW BB .... WB // if BB exists, then automatically (the same number of) WW exists // if the left cell has x B's and y W's, // then the right cell should have y B's and x W's // for each of x and y, check if this is possible // need lPx and rPy where l and r are # of ? in left cell and right cell, resp int leftB = 0; int leftW = 0; int leftQ = 0; int rightB = 0; int rightW = 0; int rightQ = 0; int numQQ = 0, numQB = 0, numBQ = 0, numWQ = 0, numQW = 0; boolean BBexists = false, WWexists = false; for(int i=0; i<n; i++) { switch(domino[i].charAt(0)){ case 'B': leftB++; break; case 'W': leftW++; break; case '?': leftQ++; break; } switch(domino[i].charAt(1)){ case 'B': rightB++; break; case 'W': rightW++; break; case '?': rightQ++; break; } if(domino[i].equals("B?")) numBQ++; else if(domino[i].equals("??")) numQQ++; else if(domino[i].equals("?B")) numQB++; else if(domino[i].equals("W?")) numWQ++; else if(domino[i].equals("?W")) numQW++; else if(domino[i].equals("BB")) BBexists = true; else if(domino[i].equals("WW")) WWexists = true; } // nCr = n!/r!/(n-r)! = n!/(r-1)!/(n-r+1)! / r * (n-r+1) long[] leftC = new long[leftQ+1]; leftC[0] = 1; for(int i=1; i<=leftQ; i++) leftC[i] = (leftC[i-1]*(leftQ+1-i)%MOD)*inverse(i, MOD)%MOD; long[] rightC = new long[rightQ+1]; rightC[0] = 1; for(int i=1; i<=rightQ; i++) rightC[i] = (rightC[i-1]*(rightQ+1-i)%MOD)*inverse(i, MOD)%MOD; long[] qqC = new long[numQQ+1]; qqC[0] = 1; for(int i=1; i<=numQQ; i++) qqC[i] = (qqC[i-1]*(numQQ+1-i)%MOD)*inverse(i, MOD)%MOD; ans = 0; // if the left cell has x B's and y W's, // then the right cell should have y B's and x W's for(int x=0; x<=n; x++) { int y=n-x; if(leftB <= x && leftW <= y && rightB <= y && rightW <= x) { // for each of x and y, check if this is possible // need lCx and rCy where l and r are # of ? in left cell and right cell, resp ans += leftC[x-leftB]*rightC[y-rightB]%MOD; // subtract # of ways: both of WB, BW exist but BB (and thus WW) do not exist // if BB or WW exist in original, pass // otherwise, count # of B?, W?, ?B, ?W, since they are fixed // and then, ?? can be either BW or WB // so we simply pick k of ?? to be BW // this actually means if(BBexists || WWexists) continue; // but then, if WB exists but BW doesn't exist, then it's fine // so x > 0 and y > 0 if(x > 0 && y > 0 && numQW <= x && numQB <= y && numWQ <= y && numBQ <= x) ans -= qqC[x - numQW - leftB]; } } ans %= MOD; if(ans < 0) ans += MOD; } static long pow(long a, int k, long p) { long m = k; long ans = 1; // curr = k^(2^i) long curr = a; // k^(2x+1) = (k^x)^2 * k while(m > 0) { if( (m&1) == 1 ) { ans *= curr; ans %= p; } m >>= 1; curr *= curr; curr %= p; } return ans; } // computes a^(p-2) static long inverse(int a, long p) { return pow(a, (int)(p-2), p); } static class Pair implements Comparable<Pair>{ final static long FIXED_RANDOM = System.currentTimeMillis(); int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int hashCode() { // http://xorshift.di.unimi.it/splitmix64.c long x = first; x <<= 32; x += second; x += FIXED_RANDOM; x += 0x9e3779b97f4a7c15l; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l; x = (x ^ (x >> 27)) * 0x94d049bb133111ebl; return (int)(x ^ (x >> 31)); } @Override public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; Pair other = (Pair) obj; return first == other.first && second == other.second; } @Override public String toString() { return "[" + first + "," + second + "]"; } @Override public int compareTo(Pair o) { int cmp = Integer.compare(first, o.first); return cmp != 0? cmp: Integer.compare(second, o.second); } } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[][] nextMatrix(int n, int m) { return nextMatrix(n, m, 0); } int[][] nextMatrix(int n, int m, int offset) { int[][] mat = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[i][j] = nextInt()+offset; } } return mat; } int[][] nextTransposedMatrix(int n, int m){ return nextTransposedMatrix(n, m, 0); } int[][] nextTransposedMatrix(int n, int m, int offset){ int[][] mat = new int[m][n]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[j][i] = nextInt()+offset; } } return mat; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } String[] nextStringArray(int len) { String[] s = new String[len]; for(int i=0; i<len; i++) s[i] = next(); return s; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean ans) { if(ans) println(YES); else println(NO); } public void printAns(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(long[] arr){ printAns(arr); println(); } public void printAns(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(int[] arr){ printAns(arr); println(); } public <T> void printAns(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void printlnAns(ArrayList<T> arr){ printAns(arr); println(); } public void printAns(int[] arr, int add){ if(arr != null && arr.length > 0){ print(arr[0]+add); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]+add); } } } public void printlnAns(int[] arr, int add){ printAns(arr, add); println(); } public void printAns(ArrayList<Integer> arr, int add) { if(arr != null && arr.size() > 0){ print(arr.get(0)+add); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)+add); } } } public void printlnAns(ArrayList<Integer> arr, int add){ printAns(arr, add); println(); } public void printlnAnsSplit(long[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public void printlnAnsSplit(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void printlnAnsSplit(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private void permutateAndSort(long[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); long temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private void permutateAndSort(int[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); int temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][][] constructDirectedNeighborhood(int n, int[][] e){ int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegree[u]++; inDegree[v]++; } int[][] inNeighbors = new int[n][]; int[][] outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][--outDegree[u]] = v; inNeighbors[v][--inDegree[v]] = u; } return new int[][][] {inNeighbors, outNeighbors}; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][--degree[u]] = v; neighbors[v][--degree[v]] = u; } return neighbors; } static private void drawGraph(int[][] e) { makeDotUndirected(e); try { final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot") .redirectOutput(new File("graph.png")) .start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 17
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
ffedebc47aad07953e63be455cf2be51
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
/* I am dead inside Do you like NCT, sKz, BTS? 5 4 3 2 1 Moonwalk Imma knock it down like domino Is this what you want? Is this what you want? Let's ttalkbocky about that :() */ import static java.lang.Math.*; import java.util.*; import java.io.*; public class x1608D { static final long MOD = 998244353L; public static void main(String omkar[]) throws Exception { fac = new long[300005]; invfac = new long[300005]; fac[0] = invfac[0] = 1L; for(int i=1; i <= 300000; i++) fac[i] = (fac[i-1]*i)%MOD; invfac[300000] = power(fac[300000], MOD-2, MOD); for(int i=299999; i >= 1; i--) invfac[i] = (invfac[i+1]*(i+1))%MOD; BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int bc = 0, wc = 0; int qc = 0; long[] boof = new long[2]; boof[0] = boof[1] = 1L; long subtract = 1L; for(int i=0; i < N; i++) { String lol = infile.readLine(); char a = lol.charAt(0); char b = lol.charAt(1); if(a == 'W') wc++; else if(a == 'B') bc++; else qc++; //other character if(b == 'W') wc++; else if(b == 'B') bc++; else qc++; int cnt = 0; if(a != 'W' && b != 'B') cnt++; else boof[0] = 0L; //other rotation if(a != 'B' && b != 'W') cnt++; else boof[1] = 0L; subtract *= cnt; if(subtract >= MOD) subtract -= MOD; } if(max(wc, bc) > N) { System.out.println(0); return; } int temp = (qc+wc-bc)/2; long res = nCr(qc, temp); res += MOD-subtract; res %= MOD; res += boof[0]+boof[1]; res %= MOD; System.out.println(res); } static long[] fac; static long[] invfac; public static long nCr(int a, int b) { if(a < b || min(a, b) < 0) return 0L; long res = (fac[a]*invfac[b])%MOD; return (res*invfac[a-b])%MOD; } public static long power(long x, long y, long p) { //0^0 = 1 long res = 1L; x = x%p; while(y > 0) { if((y&1)==1) res = (res*x)%p; y >>= 1; x = (x*x)%p; } return res; } }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 8
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
69b8300b96baaf40e1b928de6299b408
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.math.*; import java.io.*; public class Main { public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); // Scanner in = new Scanner(System.in); // Scanner in = new Scanner(new BufferedReader(new // InputStreamReader(System.in))); PrintWriter out = new PrintWriter(System.out); // InputReader in = new InputReader(new // File("ethan_traverses_a_tree.txt")); // PrintWriter out = new PrintWriter(new // File("ethan_traverses_a_tree-output.txt")); final long mod = 998244353; int n = in.nextInt(); char[][] a = new char[n][2]; String[] b = new String[n]; for (int i = 0; i < n; i++) { b[i] = in.next(); a[i] = b[i].toCharArray(); } boolean hassame = false; int countw = 0; int countb = 0; int countremain = 0; int countkpair = 0; for (int i = 0; i < n; i++) { if (b[i].equals("WW") || b[i].equals("BB")) { hassame = true; } if (b[i].equals("??")) { countkpair++; } for (int j = 0; j < 2; j++) { if (a[i][j] == 'W') { countw++; } else if (a[i][j] == 'B') { countb++; } else { countremain++; } } } if (countw > n || countb > n) { out.printf("0\n"); } else if (countw == n || countb == n) { if (hassame == true) { out.printf("1\n"); } else { if (canAllBw(a) || canAllWb(a)) { out.printf("1\n"); } else { out.printf("0\n"); } } } else { long[] c = new long[countremain + 1]; c[0] = 1; for (int i = 1; i < c.length; i++) { long tmp = (countremain - i + 1) * inverse(i, mod) % mod; c[i] = (c[i - 1] * tmp) % mod; } int remainw = n - countw; int remainb = n - countb; long ans = c[remainw]; if(hassame == false && countkpair > 0) { ans = (ans - powmod(2, countkpair, mod) + mod) % mod; } if (canAllBw(a)) { ans = (ans + 1) % mod; } if (canAllWb(a)) { ans = (ans + 1) % mod; } out.printf("%d\n", ans); } out.close(); } static public boolean canAllWb(char[][] a) { for (int i = 0; i < a.length; i++) { if (a[i][0] == 'B' || a[i][1] == 'W') { return false; } } return true; } static public boolean canAllBw(char[][] a) { for (int i = 0; i < a.length; i++) { if (a[i][0] == 'W' || a[i][1] == 'B') { return false; } } return true; } static public long inverse(long a, long p) { return powmod(a, p - 2, p); } static public long powmod(long a, long n, long mod) { long result = 1; long p = a; while (n != 0) { if (n % 2 == 1) { result = (result * p) % mod; } p = (p * p) % mod; n = n / 2; } return result; } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public boolean hasNext() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 8
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
9a1b4cf4ef68923f7b8df580773b9ae0
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.util.*; import java.io.*; public class D { static int mod = 998244353; static long[] fac, facInv; public static long modPow(long a, long e) { return e == 0 ? 1 : ((e % 2 == 1) ? (modPow(a, e - 1) * a % mod) : modPow(a * a % mod, e / 2)); } public static void init(int n) { fac = new long[n + 1]; facInv = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) { fac[i] = i * fac[i - 1] % mod; } facInv[n] = modPow(fac[n], mod - 2); for (int i = n - 1; i >= 0; i--) { facInv[i] = facInv[i + 1] * (i + 1) % mod; } } public static long nck(int n, int k) { if (n < 0 || k < 0 || k > n) { return 0; } return fac[n] * facInv[k] % mod * facInv[n - k] % mod; } public static long solve(int zero, int one, int pzero, int pone) { long ans = 0; int all = one + zero + pone + pzero; for (int cur = 0; cur <= all; cur++) { int remOne = cur - one; int remZero = cur - zero; if (remOne < 0 || remZero < 0) continue; long inc = nck(pzero, remZero) * nck(pone, remOne) % mod; // System.out.println(nck(pzero, remZero) + " " + nck(pone, remOne)); // System.out.println(cur + " " + pzero + " " + remZero + " " + pone + " " + remOne + " " + inc); ans = (ans + inc) % mod; } return ans; } public static boolean match(String x, String y) { for (int i = 0; i < x.length(); i++) { if (x.charAt(i) == '?' || y.charAt(i) == '?') continue; if (x.charAt(i) != y.charAt(i)) return false; } return true; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); init((int) 3e5); // System.out.println(Arrays.toString(Arrays.copyOfRange(fac, 0, 10))); // System.out.println(Arrays.toString(Arrays.copyOfRange(facInv, 0, 10))); // pw.println(nck(1, 1)); // System.out.println(modPow(2,4)); int n = sc.nextInt(); int zero = 0; int one = 0; int pzero = 0; int pone = 0; boolean allBW = true; boolean allWB = true; long sub = 1; for (int i = 0; i < n; i++) { String cur = sc.next(); allBW &= match(cur, "BW"); allWB &= match(cur, "WB"); int cnt = (match(cur, "BW") ? 1 : 0) + (match(cur, "WB") ? 1 : 0); sub = sub * cnt % mod; if (cur.equals("??")) { pzero++; pone++; } else if (cur.equals("WW")) { zero++; } else if (cur.equals("W?") || cur.equals("?W")) { pzero++; } else if (cur.equals("BB")) { one++; } else if (cur.equals("B?") || cur.equals("?B")) { pone++; } } long ans = solve(zero, one, pzero, pone); ans = (ans - sub) % mod; ans = (ans + mod) % mod; if (allBW) ans++; if (allWB) ans++; ans %= mod; pw.println(ans); pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } } }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 8
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
8c4aac45ae49a6f0c8bb63dcf2afb621
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static final int MOD = 998244353; public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out = new PrintWriter(System.out); /****** CODE STARTS HERE *****/ //-------------------------------------------------------------------------------------------------------- int n=fs.nextInt(); int f1=0, f2=0; char[][] s = new char[n][2]; for(int i=0; i<n; i++)s[i]=fs.next().toCharArray(); int cw=0, cb=0, emp=2, wl=0, bl=0, wr=0, br=0; long cc = 1; for(int i=0; i<n; i++) { if(s[i][0]=='?' && s[i][1]=='?') { cc = (cc*2)%MOD; continue; } emp = 1; if(s[i][0] == s[i][1] && s[i][0]!='?')f1=1; if(s[i][0]=='W') { cw++; wl=1; } else if(s[i][0]=='B') { bl=1; cb++; } if(s[i][1]=='W') { cw++; wr=1; } else if(s[i][1]=='B') { cb++; br=1; } } if(n+n-cw-cb < 0 || cb>n || cw>n) { System.out.println(0); return; } if((wl==1&&wr==1) || (bl==1&&br==1))emp=0; long ans = nCrModPFermat(n+n-cw-cb, n-cw, MOD); if(f1==1) { System.out.println(ans); }else { System.out.println(((ans-cc)%MOD+emp)%MOD); } out.close(); } /* Iterative Function to calculate (x^y)%p in O(log y) */ static long power(long x, int y, int 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, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static long 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 long[] fac = new long[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; } // A Lucas Theorem based solution to compute nCr % p static class Lucas_Theorem_nCr_mod_P{ // Returns nCr % p. In this Lucas Theorem based program, // this function is only called for n < p and r < p. static int nCrModpDP(int n, int r, int p) { // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr int[] C=new int[r+1]; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j-1])%p; } return C[r]; } // Lucas Theorem based function that returns nCr % p // This function works like decimal to binary conversion // recursive function. First we compute last digits of // n and r in base p, then recur for remaining digits static int nCrModpLucas(int n, int r, int p) { // Base case if (r==0) return 1; // Compute last digits of n and r in base p int ni = n%p; int ri = r%p; // Compute result for last digits computed above, and // for remaining digits. Multiply the two results and // compute the result of multiplication in modulo p. return (nCrModpLucas(n/p, r/p, p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits } // Driver program public static void main(String[] args) { int n = 33, r = 8, p = (int)1e9+7; System.out.println("Value of nCr % p is "+nCrModpLucas(n, r, p)); } } // This code is contributed by Rahul_Trivedi //****** CODE ENDS HERE ***** //---------------------------------------------------------------------------------------------------------------- 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); } //----------- FastScanner class for faster input--------------------------- 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
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
15163ab01b47b92c8f9a7bb04e3b00ce
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { /** * @param args */ public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out = new PrintWriter(System.out); /****** CODE STARTS HERE *****/ //-------------------------------------------------------------------------------------------------------- int n=fs.nextInt(); int f1=0, f2=0; char[][] s = new char[n][2]; for(int i=0; i<n; i++)s[i]=fs.next().toCharArray(); int cw=0, cb=0, emp=2, wl=0, bl=0, wr=0, br=0; long cc = 1; for(int i=0; i<n; i++) { if(s[i][0]=='?' && s[i][1]=='?') { cc = (cc*2)%998244353; continue; } emp = 1; if(s[i][0] == s[i][1] && s[i][0]!='?')f1=1; if(s[i][0]=='W') { cw++; wl=1; } else if(s[i][0]=='B') { bl=1; cb++; } if(s[i][1]=='W') { cw++; wr=1; } else if(s[i][1]=='B') { cb++; br=1; } } if(n+n-cw-cb < 0 || cb>n || cw>n) { System.out.println(0); return; } if((wl==1&&wr==1) || (bl==1&&br==1))f2=1; if(n+n-cw-cb == 0) { if(f1==1 || f2==0) System.out.println(1); else System.out.println(0); return; } long ans = nCrModPFermat(n+n-cw-cb, n-cw, 998244353); // System.out.println(ans); if(f1==1) { System.out.println(ans); }else if(f2==1) { System.out.println((ans-cc)%998244353); }else { System.out.println(((ans-cc)%998244353+emp)%998244353); } out.close(); } /* Iterative Function to calculate (x^y)%p in O(log y) */ static long power(long x, int y, int 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, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static long 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 long[] fac = new long[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; } // A Lucas Theorem based solution to compute nCr % p static class Lucas_Theorem_nCr_mod_P{ // Returns nCr % p. In this Lucas Theorem based program, // this function is only called for n < p and r < p. static int nCrModpDP(int n, int r, int p) { // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr int[] C=new int[r+1]; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j-1])%p; } return C[r]; } // Lucas Theorem based function that returns nCr % p // This function works like decimal to binary conversion // recursive function. First we compute last digits of // n and r in base p, then recur for remaining digits static int nCrModpLucas(int n, int r, int p) { // Base case if (r==0) return 1; // Compute last digits of n and r in base p int ni = n%p; int ri = r%p; // Compute result for last digits computed above, and // for remaining digits. Multiply the two results and // compute the result of multiplication in modulo p. return (nCrModpLucas(n/p, r/p, p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits } // Driver program public static void main(String[] args) { int n = 33, r = 8, p = (int)1e9+7; System.out.println("Value of nCr % p is "+nCrModpLucas(n, r, p)); } } // This code is contributed by Rahul_Trivedi //****** CODE ENDS HERE ***** //---------------------------------------------------------------------------------------------------------------- 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); } //----------- FastScanner class for faster input--------------------------- 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
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
fb5232620e85c955ac74d906fefa76fd
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.math.*; /** __ __ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ `-` / _____ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class C{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 200015; static final int MOD= 998244353; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; static boolean[] prime; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) // marking smallest prime factor for every // number to be itself. spf[i] = i; // separately marking spf for every even // number as 2 for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j<MAXN; j+=i) // marking spf[j] if it is not // previously marked if (spf[j]==j) spf[j] = i; } } } void sieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. 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; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } public int lowerIndex(int[] arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } public int upperIndex(int[] arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } public int add(int a, int b){ a+=b; while(a>=MOD) a-=MOD; while(a<0) a+=MOD; return a; } public int mul(int a, int b){ long res= (long)a*(long)b; return (int)(res%MOD); } public int power(int a, int b) { int ans=1; while(b>0){ if((b&1)!=0) ans= mul(ans,a); b>>=1; a= mul(a,a); } return ans; } int[] fact= new int[MAXN]; int[] inv= new int[MAXN]; public int Ckn(int n, int k){ if(k<0 || n<0) return 0; if(n<k) return 0; return mul(mul(fact[n],inv[k]),inv[n-k]); } public int inverse(int a){ return power(a,MOD-2); } public void preprocess() { fact[0]=1; for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i); inv[MAXN-1]= inverse(fact[MAXN-1]); for(int i=MAXN-2;i>=0;i--){ inv[i]= mul(inv[i+1],i+1); } } /** * return VALUE of lower bound for unsorted array */ public int lowerBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.lower(x); } /** * return VALUE of upper bound for unsorted array */ public int upperBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.higher(x); } public void debugArr(int[] arr){ for(int i: arr) out.print(i+" "); out.println(); } public int rand(){ int min=0, max= MAXN; int random_int = (int)Math.floor(Math.random()*(max-min+1)+min); return random_int; } public void suffleSort(int[] arr){ shuffleArray(arr); Arrays.sort(arr); } public void shuffleArray(int[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } InputReader in; PrintWriter out; CustomFileReader cin; int[] xor= new int[3*100000+5]; int[] pow2= new int[1000000+1]; public void solve(InputReader in, PrintWriter out) { this.in=in; this.out=out; // sieve(); // pow2[0]=1; // for(int i=1;i<pow2.length;i++){ // pow2[i]= mul(pow2[i-1],2); // } int t= 1; preprocess(); // int t=in.nextInt(); // int t= cin.nextIntArrLine()[0]; for(int i=1;i<=t;i++) solveB(i); } final double pi= Math.acos(-1); static Point base; int[] par; int[] size; PriorityQueue<Pair> q= new PriorityQueue<>((a,b)->b.x-a.x); private int find(int u){ if(par[u]==u) return u; par[u]= find(par[u]); return par[u]; } private boolean union(int u, int v){ u= find(u); v= find(v); if(u==v) return false; if(size[u]>size[v]){ int temp= u; u=v; v= temp; } par[u]=v; size[v]+= size[u]; return true; } private boolean already(int u, int v){ return find(u)==find(v); } public void solveB(int t){ int n= in.nextInt(); int wb=0, bw=0, _b=0, b_=0, _w=0, w_=0, __=0, bb=0, ww=0; for(int i=0;i<n;i++){ String temp= in.nextToken(); if(temp.equals("BB")) bb++; if(temp.equals("BW")) bw++; if(temp.equals("WB")) wb++; if(temp.equals("WW")) ww++; if(temp.equals("B?")) b_++; if(temp.equals("?B")) _b++; if(temp.equals("W?")) w_++; if(temp.equals("?W")) _w++; if(temp.equals("??")) __++; } int b= 2*bb+bw+wb+b_+_b, w= 2*ww+bw+wb+w_+_w, x= 2*__+b_+_b+_w+w_; if(b>n) { out.println(0); return; } int res= Ckn(x,Math.max(n-b,0)), ans=0; int WB= wb+w_+_b, BW= bw+b_+_w; if(WB!=0 && BW!=0) { if(__!=0)ans= power(2,__); } else if((WB==0 && BW!=0) || (WB!=0 && BW==0)) { if(__!=0) ans= add(power(2,__),-1); } else { if(__!=0) ans= add(power(2,__),-2); } if(bb==0 && ww==0)res= add(res,-ans); out.println(res); } public void solveA(int t){ int n= in.nextInt(); char[][] a= new char[n][2]; for(int i=0;i<n;i++){ String temp= in.nextToken(); a[i][0]= temp.charAt(0); a[i][1]= temp.charAt(1); } int res=0; String temp= ""+a[0][0]+a[0][1]; if(temp.equals("WW") || temp.equals("?W") || temp.equals("W?") || temp.equals("??")) res= add(res, calc("WW",a)); if(temp.equals("WB") || temp.equals("W?") || temp.equals("?B") || temp.equals("??")) res= add(res, calc("WB", a)); if(temp.equals("BB") || temp.equals("?B") || temp.equals("B?") || temp.equals("??")) res= add(res, calc("BB", a)); if(temp.equals("BW") || temp.equals("?W") || temp.equals("B?") || temp.equals("??")) res= add(res, calc("BW", a)); out.println(res); } private int calc(String s, char[][] a){ int n= a.length; int[][] dp= new int[n][4]; //0: ww , 1: wb ,2: bb, 3: bw if(s.equals("WW")) dp[0][0]=1; else if(s.equals("WB")) dp[0][1]=1; else if(s.equals("BB")) dp[0][2]=1; else if(s.equals("Bw")) dp[0][3]=1; for(int i=1;i<n-1;i++){ String temp= ""+a[i][0]+a[i][1]; out.println(temp); if(temp.equals("WW") || temp.equals("?W") || temp.equals("W?") || temp.equals("??"))dp[i][0] = add(dp[i-1][1],dp[i-1][2]); if(temp.equals("WB") || temp.equals("W?") || temp.equals("?B") || temp.equals("??"))dp[i][1] = add(dp[i-1][1],dp[i-1][2]); if(temp.equals("BB") || temp.equals("?B") || temp.equals("B?") || temp.equals("??"))dp[i][2] = add(dp[i-1][0],dp[i-1][3]); if(temp.equals("BW") || temp.equals("?W") || temp.equals("B?") || temp.equals("??"))dp[i][3] = add(dp[i-1][0],dp[i-1][3]); } if(n==1) return add(dp[0][0],add(dp[0][1],add(dp[0][2],dp[0][3]))); String temp= ""+a[n-1][0]+a[n-1][1]; if(s.charAt(0)=='B'){ if(temp.equals("WW") || temp.equals("?W") || temp.equals("W?") || temp.equals("??"))dp[n-1][0] = add(dp[n-2][1],dp[n-2][2]); if(temp.equals("BW") || temp.equals("?W") || temp.equals("B?") || temp.equals("??"))dp[n-1][3] = add(dp[n-2][0],dp[n-2][3]); } else { if(temp.equals("WB") || temp.equals("W?") || temp.equals("?B") || temp.equals("??"))dp[n-1][1] = add(dp[n-2][1],dp[n-2][2]); if(temp.equals("BB") || temp.equals("?B") || temp.equals("B?") || temp.equals("??"))dp[n-1][2] = add(dp[n-2][0],dp[n-2][3]); } for(int i=0;i<n;i++){ for(int j=0;j<4;j++) out.print(dp[i][j]+" "); out.println(); } return add(dp[n-1][0],add(dp[n-1][1],add(dp[n-1][2],dp[n-1][3]))); } static class Node implements Comparable<Node>{ char op; int s; public Node (char op, int s) { this.op= op; this.s= s; } @Override public int compareTo(Node o) { if (this.s==o.s) return (int)(this.op-o.op); return this.s-o.s; } } private long distance(Point p1, Point p2) { long x= p1.x-p2.x, y= p1.y-p2.y; return x*x+y*y; } private boolean eqPoint(Point p1, Point p2){ return p1.x==p2.x && p1.y==p2.y; } private double polarAngle(Point p1, Point p2) { // p1 -> p2 if (p1.x==p2.x) return pi/2; else if (p1.y==p2.y){ if(p1.x<p2.x) return 0; else return pi; } else { double y= (double)p2.y-(double)p1.y; double x= (double)p2.x-(double)p1.x; BigDecimal alpha1= new BigDecimal(y); BigDecimal alpha2= new BigDecimal(x); BigDecimal val= alpha1.divide(alpha2); double angle= Math.atan(val.doubleValue()); if (angle<0) angle+= pi; out.println("angle: "+angle); return angle; } } private boolean isRightTurn(Point p1, Point p2, Point p3){ Vector v1= new Vector(p1,p2), v2= new Vector(p1,p3); if(crossProd(v1,v2)<0) return true; else return false; } private long crossProd(Vector v1, Vector v2){ //x1*y2-x2*y1 return v1.x*v2.y - v2.x*v1.y; } static class PointAngle implements Comparable<PointAngle>{ Point p; double angle; long dis; public PointAngle(Point p, double angle, long dis) { this.p= p; this.angle= angle; this.dis= dis; } @Override public int compareTo(PointAngle o) { double dif= this.angle-o.angle; if (dif <0) return -1; else if(dif >0) return 1; else { long dif2r= this.dis-o.dis; long dif2l= o.dis-this.dis; if (base.x < this.p.x) return intDif(dif2r); else return intDif(dif2l); } } private int intDif(long a){ if (a>0) return 1; else if(a<0) return -1; else return 0; } } public long _gcd(long a, long b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } public long _lcm(long a, long b){ return (a*b)/_gcd(a,b); } } // static class SEG { // Pair[] segtree; // public SEG(int n){ // segtree= new Pair[4*n]; // Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE)); // } // // void buildTree(int l, int r, int index) { // // if (l == r) { // // segtree[index].y = a[l]; // // return; // // } // // int mid = (l + r) / 2; // // buildTree(l, mid, 2 * index + 1); // // buildTree(mid + 1, r, 2 * index + 2); // // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y); // // } // void update(int l, int r, int index, int pos, Pair val) { // if (l == r) { // segtree[index] = val; // return; // } // int mid = (l + r) / 2; // if (pos <= mid) update(l, mid, 2 * index + 1, pos, val); // else update(mid + 1, r, 2 * index + 2, pos, val); // if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){ // segtree[index]= segtree[2 * index + 1]; // } // else { // segtree[index]= segtree[2 * index + 2]; // } // } // // Pair query(int l, int r, int from, int to, int index) { // // if (from <= l && r <= to) // // return segtree[index]; // // if (r < from | to < l) // // return 0; // // int mid = (l + r) / 2; // // Pair left= query(l, mid, from, to, 2 * index + 1); // // Pair right= query(mid + 1, r, from, to, 2 * index + 2); // // if(left.y < right.y) return left; // // else return right; // // } // } static class Venice{ public Map<Long,Long> m= new HashMap<>(); public long base=0; public long totalValue=0; private int M= 1000000007; private long addMod(long a, long b){ a+=b; if(a>=M) a-=M; return a; } public void reset(){ m= new HashMap<>(); base=0; totalValue=0; } public void update(long add){ base= base+ add; } public void add(long key, long val){ long newKey= key-base; m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val)); } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ return this.z-o.z; } } static class Point implements Comparable<Point>{ public long x; public long y; public Point(long x, long y){ this.x= x; this.y= y; } @Override public int compareTo(Point o) { if(this.y!=o.y) return (int)(this.y-o.y); return (int)(this.x-o.x); } } static class Vector { public long x; public long y; // p1 -> p2 public Vector(Point p1, Point p2){ this.x= p2.x-p1.x; this.y= p2.y-p1.y; } } static class Pair implements Comparable<Pair>{ public int x; public int y; public Pair(int x, int y){ this.x= x; this.y= y; } @Override public int compareTo(Pair o) { if(this.x!=o.x) return this.x-o.x; return (int)(this.y-o.y); } } // public static class compareL implements Comparator<Tuple>{ // @Override // public int compare(Tuple t1, Tuple t2) { // return t2.l - t1.l; // } // } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } public int[] nextIntArr(int n){ int[] arr= new int[n]; for(int i=0;i<n;i++) arr[i]= nextInt(); return arr; } public long[] nextLongArr(int n){ long[] arr= new long[n]; for(int i=0;i<n;i++) arr[i]= nextLong(); return arr; } public List<Integer> nextIntList(int n){ List<Integer> arr= new ArrayList<>(); for(int i=0;i<n;i++) arr.add(nextInt()); return arr; } public int[][] nextIntMatArr(int n, int m){ int[][] mat= new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt(); return mat; } public List<List<Integer>> nextIntMatList(int n, int m){ List<List<Integer>> mat= new ArrayList<>(); for(int i=0;i<n;i++){ List<Integer> temp= new ArrayList<>(); for(int j=0;j<m;j++) temp.add(nextInt()); mat.add(temp); } return mat; } public char[] nextStringCharArr(){ return nextToken().toCharArray(); } } static class CustomFileReader{ String path=""; Scanner sc; public CustomFileReader(String path){ this.path=path; try{ sc= new Scanner(new File(path)); } catch(Exception e){} } public String nextLine(){ return sc.nextLine(); } public int[] nextIntArrLine(){ String line= sc.nextLine(); String[] part= line.split("[\\s+]"); int[] res= new int[part.length]; for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]); return res; } } }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
5d3a0eaff8704aa422c925ab66670ffc
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1608d_2 { public static void main(String[] args) throws IOException { int n = ri(), cntw = 0, cntb = 0, invalid = 1, cntqq = 0, allbw = 1, allwb = 1; int fact[] = new int[2 * n + 1]; fact[0] = fact[1] = 1; for (int i = 2; i <= 2 * n; ++i) { fact[i] = mmul(i, fact[i - 1]); } for (int i = 0; i < n; ++i) { char d[] = rcha(); if (d[0] == 'B') { ++cntb; allwb = 0; } if (d[0] == 'W') { ++cntw; allbw = 0; } if (d[1] == 'B') { ++cntb; allbw = 0; } if (d[1] == 'W') { ++cntw; allwb = 0; } if (d[0] == '?' && d[1] == '?') { ++cntqq; } else if (d[0] == d[1]) { invalid = 0; } } if (cntw > n || cntb > n) { prln(0); } else { prln(msub(mmul(fact[2 * n - cntw - cntb], minv(fact[n - cntw]), minv(fact[n - cntb])), invalid * msub(mpow(2, cntqq), madd(allbw, allwb)))); } close(); } static int mmod = 998244353; static int madd(int a, int b) { return (a + b) % mmod; } static int madd(int... a) { int ans = a[0]; for (int i = 1; i < a.length; ++i) { ans = madd(ans, a[i]); } return ans; } static int msub(int a, int b) { return (a - b + mmod) % mmod; } static int mmul(int a, int b) { return (int) ((long) a * b % mmod); } static int mmul(int... a) { int ans = a[0]; for (int i = 1; i < a.length; ++i) { ans = mmul(ans, a[i]); } return ans; } static int minv(int x) { // return mpow(x, mmod - 2); return (exgcd(x, mmod)[0] % mmod + mmod) % mmod; } static int mpow(int a, long b) { if (a == 0) { return 0; } int ans = 1; while (b > 0) { if ((b & 1) > 0) { ans = mmul(ans, a); } a = mmul(a, a); b >>= 1; } return ans; } static BufferedReader __i = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __o = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __r = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 9223372036854775807L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcd(int a, int b) {return b == 0 ? a : gcd(b, a % b);} static long gcd(long a, long b) {return b == 0 ? a : gcd(b, a % b);} static int[] exgcd(int a, int b) {if (b == 0) return new int[] {1, 0}; int[] y = exgcd(b, a % b); return new int[] {y[1], y[0] - y[1] * (a / b)};} static long[] exgcd(long a, long b) {if (b == 0) return new long[] {1, 0}; long[] y = exgcd(b, a % b); return new long[] {y[1], y[0] - y[1] * (a / b)};} static int randInt(int min, int max) {return __r.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static void ria(int[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = ni();} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static void riam1(int[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static void rla(long[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = nl();} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static void rda(double[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = nd();} static char[] rcha() throws IOException {return rline().toCharArray();} static void rcha(char[] a) throws IOException {int n = a.length, i = 0; for (char c : rline().toCharArray()) a[i++] = c;} static String rline() throws IOException {return __i.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__o.print(i);} static void prln(int i) {__o.println(i);} static void pr(long l) {__o.print(l);} static void prln(long l) {__o.println(l);} static void pr(double d) {__o.print(d);} static void prln(double d) {__o.println(d);} static void pr(char c) {__o.print(c);} static void prln(char c) {__o.println(c);} static void pr(char[] s) {__o.print(new String(s));} static void prln(char[] s) {__o.println(new String(s));} static void pr(String s) {__o.print(s);} static void prln(String s) {__o.println(s);} static void pr(Object o) {__o.print(o);} static void prln(Object o) {__o.println(o);} static void prln() {__o.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__o.flush();} static void close() {__o.close();} }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
953cf5b449fd5b3977790422598d2821
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.io.*; import java.util.*; public class D implements constant { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter pw = new PrintWriter(System.out, true); static long [] fact; static long [] invFact; // Fermats Little Theorem: // (a^p - a) % p = 0 // => a^p % p - a % p = 0 // => a^p % p = a % p // => a^(p - 1) % p = (a * a^-1) % p // => a^(p - 1) % p = 1 % p // => a^(p - 2) % p = a^-1 % p static long binPow(long a, long b){ long res = 1; while(b > 0){ a = a % mod; if((b&1) == 1){ res = (res * a) % mod; } b >>= 1; a = (a * a) % mod; } return res; } static long modInverse(long a){ return binPow(a, mod - 2); } static long mul(long a, long b){ return (a * b) % mod; } static long nCr(int n, int r){ long res = mul(fact[n], invFact[r]); res = mul(res, invFact[n - r]); return res; } public static void main(String args[]) throws IOException{ int n; n = Integer.parseInt(br.readLine()); String [] ls = new String[n]; boolean full = false; int black = 0, white = 0; for(int i = 0; i < n; ++i){ ls[i] = br.readLine(); if(ls[i].charAt(0) == 'W') white++; if(ls[i].charAt(0) == 'B') black++; if(ls[i].charAt(1) == 'W') white++; if(ls[i].charAt(1) == 'B') black++; if(ls[i].charAt(0) != '?' && ls[i].charAt(0) == ls[i].charAt(1)){ full = true; } } if(black > n || white > n){ pw.println(0); return; } fact = new long[2 * n + 1]; invFact = new long[2 * n + 1]; fact[0] = 1; invFact[0] = 1; for(int i = 1; i <= 2 * n; ++i){ fact[i] = mul(fact[i - 1], i); invFact[i] = modInverse(fact[i]); } int empty = 2 * n - black - white; long ans = nCr(empty, n - black); if(full){ pw.println(ans); return; } long invalid = 1; boolean WB = true, BW = true; for(int i = 0; i < n; ++i){ if(ls[i].charAt(0) == '?' && ls[i].charAt(1) == '?'){ invalid = mul(invalid, 2); } if(ls[i].charAt(0) == 'B' || ls[i].charAt(1) == 'W'){ WB = false; } if(ls[i].charAt(0) == 'W' || ls[i].charAt(1) == 'B'){ BW = false; } } if(WB) invalid--; if(BW) invalid--; ans = ans - invalid; pw.println(ans); } } interface constant { long mod = 998244353; }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
e410c3affac2b2fcd80a5020dfe0c9b8
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1608d_2 { public static void main(String[] args) throws IOException { int n = ri(), cntw = 0, cntb = 0, invalid = 1, cntqq = 0, allbw = 1, allwb = 1; int fact[] = new int[2 * n + 1]; fact[0] = fact[1] = 1; for (int i = 2; i <= 2 * n; ++i) { fact[i] = mmul(i, fact[i - 1]); } for (int i = 0; i < n; ++i) { char d[] = rcha(); if (d[0] == 'B') { ++cntb; allwb = 0; } if (d[0] == 'W') { ++cntw; allbw = 0; } if (d[1] == 'B') { ++cntb; allbw = 0; } if (d[1] == 'W') { ++cntw; allwb = 0; } if (d[0] == '?' && d[1] == '?') { ++cntqq; } else if (d[0] == d[1]) { invalid = 0; } } if (cntw > n || cntb > n) { prln(0); } else { prln(msub(mmul(fact[2 * n - cntw - cntb], minv(fact[n - cntw]), minv(fact[n - cntb])), invalid * msub(mpow(2, cntqq), madd(allbw, allwb)))); } close(); } static int mmod = 998244353; static int madd(int a, int b) { return (a + b) % mmod; } static int madd(int... a) { int ans = a[0]; for (int i = 1; i < a.length; ++i) { ans = madd(ans, a[i]); } return ans; } static int msub(int a, int b) { return (a - b + mmod) % mmod; } static int mmul(int a, int b) { return (int) ((long) a * b % mmod); } static int mmul(int... a) { int ans = a[0]; for (int i = 1; i < a.length; ++i) { ans = mmul(ans, a[i]); } return ans; } static int minv(int x) { // return mpow(x, mmod - 2); return (exgcd(x, mmod)[0] % mmod + mmod) % mmod; } static int mpow(int a, long b) { if (a == 0) { return 0; } int ans = 1; while (b > 0) { if ((b & 1) > 0) { ans = mmul(ans, a); } a = mmul(a, a); b >>= 1; } return ans; } static BufferedReader __i = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __o = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __r = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 9223372036854775807L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcd(int a, int b) {return b == 0 ? a : gcd(b, a % b);} static long gcd(long a, long b) {return b == 0 ? a : gcd(b, a % b);} static int[] exgcd(int a, int b) {if (b == 0) return new int[] {1, 0}; int[] y = exgcd(b, a % b); return new int[] {y[1], y[0] - y[1] * (a / b)};} static long[] exgcd(long a, long b) {if (b == 0) return new long[] {1, 0}; long[] y = exgcd(b, a % b); return new long[] {y[1], y[0] - y[1] * (a / b)};} static int randInt(int min, int max) {return __r.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static void ria(int[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = ni();} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static void riam1(int[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static void rla(long[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = nl();} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static void rda(double[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = nd();} static char[] rcha() throws IOException {return rline().toCharArray();} static void rcha(char[] a) throws IOException {int n = a.length, i = 0; for (char c : rline().toCharArray()) a[i++] = c;} static String rline() throws IOException {return __i.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__o.print(i);} static void prln(int i) {__o.println(i);} static void pr(long l) {__o.print(l);} static void prln(long l) {__o.println(l);} static void pr(double d) {__o.print(d);} static void prln(double d) {__o.println(d);} static void pr(char c) {__o.print(c);} static void prln(char c) {__o.println(c);} static void pr(char[] s) {__o.print(new String(s));} static void prln(char[] s) {__o.println(new String(s));} static void pr(String s) {__o.print(s);} static void prln(String s) {__o.println(s);} static void pr(Object o) {__o.print(o);} static void prln(Object o) {__o.println(o);} static void prln() {__o.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__o.flush();} static void close() {__o.close();} }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
8335c932582b92ae13410ee30ba8be41
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.io.*; import java.util.*; public class Solution extends PrintWriter { void solve() { pre(); int n = sc.nextInt(); int BB = 0; int WW = 0; int BW = 0; int WB = 0; int QB = 0; int QW = 0; int BQ = 0; int WQ = 0; int QQ = 0; for(int i = 0; i < n; i++) { char[] chs = sc.nextString().toCharArray(); if(chs[0] == 'B' && chs[1] == 'B') BB++; else if(chs[0] == 'W' && chs[1] == 'W') WW++; else if(chs[0] == 'B' && chs[1] == 'W') BW++; else if(chs[0] == 'W' && chs[1] == 'B') WB++; else if(chs[0] == '?' && chs[1] == 'B') QB++; else if(chs[0] == '?' && chs[1] == 'W') QW++; else if(chs[0] == 'B' && chs[1] == '?') BQ++; else if(chs[0] == 'W' && chs[1] == '?') WQ++; else if(chs[0] == '?' && chs[1] == '?') QQ++; } long ans = 0L; //WB if(QB + WQ + QQ + WB == n) { ans++; } //BW if(BQ + QW + QQ + BW == n) { ans++; } int q = QQ; int b = QB + BQ; int w = QW + WQ; ans += C(2*q+b+w, q+b-WW+BB); if(ans <= MOD) ans -= MOD; if(WW == 0 && BB == 0) ans -= pow[q]; if(ans < 0) ans += MOD; println(ans); } int MX = 2 * 100000; long[] fac = new long[MX+1]; long[] fac_inv = new long[MX+1]; long[] inv = new long[MX+1]; long[] pow = new long[MX+1]; long MOD = 998_244_353L; long C(int n, int k) { if(n < k || n < 0 || k < 0) return 0L; long c = (fac_inv[k] * fac_inv[n - k]) % MOD; c = (c * fac[n]) % MOD; return c; } void pre() { pow[0] = 1L; for(int i = 1; i <= MX; i++) pow[i] = (pow[i-1] * 2L) % MOD; inv[1] = 1L; for(int i = 2; i <= MX; i++) inv[i] = MOD - (MOD/i) * inv[(int)(MOD%i)] % MOD; fac[0] = 1L; fac_inv[0] = 1L; for(int i = 1; i <= MX; i++) { fac[i] = (fac[i-1]*i)%MOD; fac_inv[i] = (fac_inv[i-1]*inv[i])%MOD; } } // Main() throws FileNotFoundException { super(new File("output.txt")); } // InputReader sc = new InputReader(new FileInputStream("test_input.txt")); Solution() { super(System.out); } InputReader sc = new InputReader(System.in); static class InputReader { InputReader(InputStream in) { this.in = in; } InputStream in; private byte[] buf = new byte[16384]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } /* private String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); }*/ public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } public static void main(String[] $) { new Thread(null, new Runnable() { public void run() { long start = System.nanoTime(); try {Solution solution = new Solution(); solution.solve(); solution.flush();} catch (Exception e) {e.printStackTrace(); System.exit(1);} System.err.println((System.nanoTime()-start)/1E9); } }, "1", 1 << 27).start(); } }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
8c1e992383b042fee404b786a2912a47
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class Main { private static void run() throws IOException { int n; n = in.nextInt(); int count_w = 0; int count_b = 0; int count_xx = 0; boolean will_be_wb = false; boolean will_be_bw = false; boolean bb_or_ww = false; for (int i = 0; i < n; i++) { String s = in.next(); for (int j = 0; j < 2; j++) { if (s.charAt(j) == 'W') count_w++; if (s.charAt(j) == 'B') count_b++; } switch (s) { case "WW": case "BB": bb_or_ww = true; break; case "??": count_xx++; break; case "W?": case "?B": case "WB": will_be_wb = true; break; case "B?": case "?W": case "BW": will_be_bw = true; break; } } long ans = C(2 * n - count_b - count_w, n - count_b); if (!bb_or_ww) { long invalid = pow_mod(2, count_xx); if (!will_be_wb) invalid = add_mod(invalid, -1); if (!will_be_bw) invalid = add_mod(invalid, -1); ans = add_mod(ans, -invalid); } out.println(ans); } private static long C(int n, int m) { if (m > n || m < 0) return 0; return multiplied_mod(fac[n], inv[n - m], inv[m]); } private static long[] fac, inv; private static void init() { int max_n = 200010; fac = new long[max_n]; inv = new long[max_n]; fac[0] = 1; inv[0] = 1; for (int i = 1; i < max_n; i++) { fac[i] = multiplied_mod(fac[i - 1], i); inv[i] = pow_mod(fac[i], mod - 2); } } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(new OutputStreamWriter(System.out)); init(); // int t = in.nextInt(); // for (int i = 0; i < t; i++) { // } run(); out.flush(); in.close(); out.close(); } private static int gcd(int a, int b) { if (a == 0 || b == 0) return 0; while (b != 0) { int tmp; tmp = a % b; a = b; b = tmp; } return a; } static final long mod = 998244353; static long pow_mod(long a, long b) { long result = 1; while (b != 0) { if ((b & 1) != 0) result = (result * a) % mod; a = (a * a) % mod; b >>= 1; } return result; } private static long add_mod(long... longs) { long ans = 0; for (long now : longs) { ans = (ans + now) % mod; } return ans; } private static long multiplied_mod(long... longs) { long ans = 1; for (long now : longs) { ans = (ans * now) % mod; } return ans; } @SuppressWarnings("FieldCanBeLocal") private static Reader in; private static PrintWriter out; private static int[] read_int_array(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = in.nextInt(); } return a; } private static long[] read_long_array(int len) throws IOException { long[] a = new long[len]; for (int i = 0; i < len; i++) { a[i] = in.nextLong(); } return a; } private static void print_array(int[] array) { for (int now : array) { out.print(now); out.print(' '); } out.println(); } private static void print_array(long[] array) { for (long now : array) { out.print(now); out.print(' '); } out.println(); } static class Reader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { final byte[] buf = new byte[1024]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextSign() throws IOException { byte c = read(); while ('+' != c && '-' != c) { c = read(); } return '+' == c ? 0 : 1; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() throws IOException { int b; // noinspection ALL while ((b = read()) != -1 && isSpaceChar(b)) { ; } return b; } public char nc() throws IOException { return (char) skip(); } 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(); } } }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
5bd29c95eccd84859dca04f3b92a4539
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
public class Main { public static void main(String[] args) { new Main(); } public Main() { FastScanner fs = new FastScanner(); java.io.PrintWriter out = new java.io.PrintWriter(System.out); solve(fs, out); out.flush(); } public void solve(FastScanner fs, java.io.PrintWriter out) { int n = fs.nextInt(); calc(2 * n); int lb = 0, lw = 0, rb = 0, rw = 0; int wb = 0, bw = 0, any = 0; for (int i = 0;i < n;++ i) { char[] c = fs.next().toCharArray(); if (c[0] == 'B') ++ lb; if (c[0] == 'W') ++ lw; if (c[1] == 'B') ++ rb; if (c[1] == 'W') ++ rw; if (c[0] == 'B' && c[1] == '?' || c[0] == '?' && c[1] == 'W' || c[0] == 'B' && c[1] == 'W') ++ bw; if (c[0] == 'W' && c[1] == '?' || c[0] == '?' && c[1] == 'B' || c[0] == 'W' && c[1] == 'B') ++ wb; if (c[0] == '?' && c[1] == '?') ++ any; } int ans = 0; for (int i = 0;i <= n;++ i) { int lb2 = i - lb, lw2 = n - i - lw, rb2 = n - i - rb, rw2 = i - rw; if (lb2 < 0 || lw2 < 0 || rb2 < 0 || rw2 < 0) continue; ans = plus(ans, times(comb(lb2 + lw2, lb2), comb(rb2 + rw2, rb2))); } if (wb + bw + any == n) { for (int i = Math.max(1, wb);i <= Math.min(n - 1, n - bw);++ i) { ans = minus(ans, comb(any, i - wb)); } } out.println(ans); } final int MOD = 998_244_353; int plus(int n, int m) { int sum = n + m; if (sum >= MOD) sum -= MOD; return sum; } int minus(int n, int m) { int sum = n - m; if (sum < 0) sum += MOD; return sum; } int times(int n, int m) { return (int)((long)n * m % MOD); } int divide(int n, int m) { return times(n, IntMath.pow(m, MOD - 2, MOD)); } int[] fact, invf; void calc(int len) { len += 2; fact = new int[len]; invf = new int[len]; fact[0] = fact[1] = invf[0] = invf[1] = 1; for (int i = 2;i < fact.length;++ i) fact[i] = times(fact[i - 1], i); invf[len - 1] = divide(1, fact[len - 1]); for (int i = len - 1;i > 1;-- i) invf[i - 1] = times(i, invf[i]); } int comb(int n, int m) { if (n < m) return 0; return times(fact[n], times(invf[n - m], invf[m])); } } class FastScanner { private final java.io.InputStream in = System.in; private final byte[] buffer = new byte[8192]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) return true; ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } return buflen > 0; } private byte readByte() { return hasNextByte() ? buffer[ptr++ ] : -1; } private static boolean isPrintableChar(byte c) { return 32 < c || c < 0; } private static boolean isNumber(int c) { return '0' <= c && c <= '9'; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++ ; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); byte b; while (isPrintableChar(b = readByte())) sb.appendCodePoint(b); return sb.toString(); } public final char nextChar() { if (!hasNext()) throw new java.util.NoSuchElementException(); return (char)readByte(); } public final long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; try { byte b = readByte(); if (b == '-') { while (isNumber(b = readByte())) n = n * 10 + '0' - b; return n; } else if (!isNumber(b)) throw new NumberFormatException(); do n = n * 10 + b - '0'; while (isNumber(b = readByte())); } catch (java.util.NoSuchElementException e) {} return n; } public final int nextInt() { if (!hasNext()) throw new java.util.NoSuchElementException(); int n = 0; try { byte b = readByte(); if (b == '-') { while (isNumber(b = readByte())) n = n * 10 + '0' - b; return n; } else if (!isNumber(b)) throw new NumberFormatException(); do n = n * 10 + b - '0'; while (isNumber(b = readByte())); } catch (java.util.NoSuchElementException e) {} return n; } public double nextDouble() { return Double.parseDouble(next()); } } class Arrays { public static void sort(final int[] array) { sort(array, 0, array.length); } public static void sort(final int[] array, int fromIndex, int toIndex) { if (toIndex - fromIndex <= 512) { java.util.Arrays.sort(array, fromIndex, toIndex); return; } sort(array, fromIndex, toIndex, 0, new int[array.length]); } private static final void sort(int[] a, final int from, final int to, final int l, final int[] bucket) { if (to - from <= 512) { java.util.Arrays.sort(a, from, to); return; } final int BUCKET_SIZE = 256; final int INT_RECURSION = 4; final int MASK = 0xff; final int shift = l << 3; final int[] cnt = new int[BUCKET_SIZE + 1]; final int[] put = new int[BUCKET_SIZE]; for (int i = from; i < to; i++) ++ cnt[(a[i] >>> shift & MASK) + 1]; for (int i = 0; i < BUCKET_SIZE; i++) cnt[i + 1] += cnt[i]; for (int i = from; i < to; i++) { int bi = a[i] >>> shift & MASK; bucket[cnt[bi] + put[bi]++] = a[i]; } for (int i = BUCKET_SIZE - 1, idx = from; i >= 0; i--) { int begin = cnt[i]; int len = cnt[i + 1] - begin; System.arraycopy(bucket, begin, a, idx, len); idx += len; } final int nxtL = l + 1; if (nxtL < INT_RECURSION) { sort(a, from, to, nxtL, bucket); if (l == 0) { int lft, rgt; lft = from - 1; rgt = to; while (rgt - lft > 1) { int mid = lft + rgt >> 1; if (a[mid] < 0) lft = mid; else rgt = mid; } reverse(a, from, rgt); reverse(a, rgt, to); } } } public static void sort(final long[] array) { sort(array, 0, array.length); } public static void sort(final long[] array, int fromIndex, int toIndex) { if (toIndex - fromIndex <= 512) { java.util.Arrays.sort(array, fromIndex, toIndex); return; } sort(array, fromIndex, toIndex, 0, new long[array.length]); } private static final void sort(long[] a, final int from, final int to, final int l, final long[] bucket) { final int BUCKET_SIZE = 256; final int LONG_RECURSION = 8; final int MASK = 0xff; final int shift = l << 3; final int[] cnt = new int[BUCKET_SIZE + 1]; final int[] put = new int[BUCKET_SIZE]; for (int i = from; i < to; i++) ++ cnt[(int) ((a[i] >>> shift & MASK) + 1)]; for (int i = 0; i < BUCKET_SIZE; i++) cnt[i + 1] += cnt[i]; for (int i = from; i < to; i++) { int bi = (int) (a[i] >>> shift & MASK); bucket[cnt[bi] + put[bi]++] = a[i]; } for (int i = BUCKET_SIZE - 1, idx = from; i >= 0; i--) { int begin = cnt[i]; int len = cnt[i + 1] - begin; System.arraycopy(bucket, begin, a, idx, len); idx += len; } final int nxtL = l + 1; if (nxtL < LONG_RECURSION) { sort(a, from, to, nxtL, bucket); if (l == 0) { int lft, rgt; lft = from - 1; rgt = to; while (rgt - lft > 1) { int mid = lft + rgt >> 1; if (a[mid] < 0) lft = mid; else rgt = mid; } reverse(a, from, rgt); reverse(a, rgt, to); } } } public static void reverse(int[] array) { reverse(array, 0, array.length); } public static void reverse(int[] array, int fromIndex, int toIndex) { for (-- toIndex;fromIndex < toIndex;++ fromIndex, -- toIndex) { int swap = array[fromIndex]; array[fromIndex] = array[toIndex]; array[toIndex] = swap; } } public static void reverse(long[] array) { reverse(array, 0, array.length); } public static void reverse(long[] array, int fromIndex, int toIndex) { for (-- toIndex;fromIndex < toIndex;++ fromIndex, -- toIndex) { long swap = array[fromIndex]; array[fromIndex] = array[toIndex]; array[toIndex] = swap; } } public static void shuffle(int[] array) { java.util.Random rnd = new java.util.Random(); for (int i = 0;i < array.length;++ i) { int j = rnd.nextInt(array.length - i) + i; int swap = array[i]; array[i] = array[j]; array[j] = swap; } } public static void shuffle(long[] array) { java.util.Random rnd = new java.util.Random(); for (int i = 0;i < array.length;++ i) { int j = rnd.nextInt(array.length - i) + i; long swap = array[i]; array[i] = array[j]; array[j] = swap; } } } class IntMath { public static int gcd(int a, int b) { while (a != 0) if ((b %= a) != 0) a %= b; else return a; return b; } public static int gcd(int... array) { int ret = array[0]; for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]); return ret; } public static long gcd(long a, long b) { while (a != 0) if ((b %= a) != 0) a %= b; else return a; return b; } public static long gcd(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]); return ret; } public static long lcm(long a, long b) { return a / gcd(a, b) * b; } public static int pow(int a, int b) { int ans = 1; for (int mul = a; b > 0; b >>= 1, mul *= mul) if ((b & 1) != 0) ans *= mul; return ans; } public static long pow(long a, long b) { long ans = 1; for (long mul = a; b > 0; b >>= 1, mul *= mul) if ((b & 1) != 0) ans *= mul; return ans; } public static int pow(int a, long b, int mod) { if (b < 0) b = b % (mod - 1) + mod - 1; long ans = 1; for (long mul = a; b > 0; b >>= 1, mul = mul * mul % mod) if ((b & 1) != 0) ans = ans * mul % mod; return (int)ans; } public static int pow(long a, long b, int mod) { return pow((int)(a % mod), b, mod); } public static int floorsqrt(long n) { return (int)Math.sqrt(n + 0.1); } public static int ceilsqrt(long n) { return n <= 1 ? (int)n : (int)Math.sqrt(n - 0.1) + 1; } }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
4a6da2adc6e13d1aba96c5960d3548d9
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class Main { private static void run() throws IOException { int n; n = in.nextInt(); int count_w = 0; int count_b = 0; int count_xx = 0; boolean will_be_wb = false; boolean will_be_bw = false; boolean bb_or_ww = false; for (int i = 0; i < n; i++) { String s = in.next(); for (int j = 0; j < 2; j++) { if (s.charAt(j) == 'W') count_w++; if (s.charAt(j) == 'B') count_b++; } switch (s) { case "WW": case "BB": bb_or_ww = true; break; case "??": count_xx++; break; case "W?": case "?B": case "WB": will_be_wb = true; break; case "B?": case "?W": case "BW": will_be_bw = true; break; } } long ans = C(2 * n - count_b - count_w, n - count_b); if (!bb_or_ww) { long invalid = pow_mod(2, count_xx); if (!will_be_wb) invalid = add_mod(invalid, -1); if (!will_be_bw) invalid = add_mod(invalid, -1); ans = add_mod(ans, -invalid); } out.println(ans); } private static long C(int n, int m) { if (m > n || m < 0) return 0; return multiplied_mod(fac[n], inv[n - m], inv[m]); } private static long[] fac, inv; private static void init() { int max_n = 200010; fac = new long[max_n]; inv = new long[max_n]; fac[0] = 1; inv[0] = 1; for (int i = 1; i < max_n; i++) { fac[i] = multiplied_mod(fac[i - 1], i); inv[i] = pow_mod(fac[i], mod - 2); } } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(new OutputStreamWriter(System.out)); init(); // int t = in.nextInt(); // for (int i = 0; i < t; i++) { // } run(); out.flush(); in.close(); out.close(); } private static int gcd(int a, int b) { if (a == 0 || b == 0) return 0; while (b != 0) { int tmp; tmp = a % b; a = b; b = tmp; } return a; } static final long mod = 998244353; static long pow_mod(long a, long b) { long result = 1; while (b != 0) { if ((b & 1) != 0) result = (result * a) % mod; a = (a * a) % mod; b >>= 1; } return result; } private static long add_mod(long... longs) { long ans = 0; for (long now : longs) { ans = (ans + now) % mod; } return ans; } private static long multiplied_mod(long... longs) { long ans = 1; for (long now : longs) { ans = (ans * now) % mod; } return ans; } @SuppressWarnings("FieldCanBeLocal") private static Reader in; private static PrintWriter out; private static int[] read_int_array(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = in.nextInt(); } return a; } private static long[] read_long_array(int len) throws IOException { long[] a = new long[len]; for (int i = 0; i < len; i++) { a[i] = in.nextLong(); } return a; } private static void print_array(int[] array) { for (int now : array) { out.print(now); out.print(' '); } out.println(); } private static void print_array(long[] array) { for (long now : array) { out.print(now); out.print(' '); } out.println(); } static class Reader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { final byte[] buf = new byte[1024]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextSign() throws IOException { byte c = read(); while ('+' != c && '-' != c) { c = read(); } return '+' == c ? 0 : 1; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() throws IOException { int b; // noinspection ALL while ((b = read()) != -1 && isSpaceChar(b)) { ; } return b; } public char nc() throws IOException { return (char) skip(); } 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(); } } }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
72b171535e3e08223d5a321cdf34093b
train_109.jsonl
1639217100
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.math.*; /** __ __ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ `-` / _____ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class C{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 200015; static final int MOD= 998244353; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; static boolean[] prime; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) // marking smallest prime factor for every // number to be itself. spf[i] = i; // separately marking spf for every even // number as 2 for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j<MAXN; j+=i) // marking spf[j] if it is not // previously marked if (spf[j]==j) spf[j] = i; } } } void sieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. 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; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } public int lowerIndex(int[] arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } public int upperIndex(int[] arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } public int add(int a, int b){ a+=b; while(a>=MOD) a-=MOD; while(a<0) a+=MOD; return a; } public int mul(int a, int b){ long res= (long)a*(long)b; return (int)(res%MOD); } public int power(int a, int b) { int ans=1; while(b>0){ if((b&1)!=0) ans= mul(ans,a); b>>=1; a= mul(a,a); } return ans; } int[] fact= new int[MAXN]; int[] inv= new int[MAXN]; public int Ckn(int n, int k){ if(k<0 || n<0) return 0; if(n<k) return 0; return mul(mul(fact[n],inv[k]),inv[n-k]); } public int inverse(int a){ return power(a,MOD-2); } public void preprocess() { fact[0]=1; for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i); inv[MAXN-1]= inverse(fact[MAXN-1]); for(int i=MAXN-2;i>=0;i--){ inv[i]= mul(inv[i+1],i+1); } } /** * return VALUE of lower bound for unsorted array */ public int lowerBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.lower(x); } /** * return VALUE of upper bound for unsorted array */ public int upperBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.higher(x); } public void debugArr(int[] arr){ for(int i: arr) out.print(i+" "); out.println(); } public int rand(){ int min=0, max= MAXN; int random_int = (int)Math.floor(Math.random()*(max-min+1)+min); return random_int; } public void suffleSort(int[] arr){ shuffleArray(arr); Arrays.sort(arr); } public void shuffleArray(int[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } InputReader in; PrintWriter out; CustomFileReader cin; int[] xor= new int[3*100000+5]; int[] pow2= new int[1000000+1]; public void solve(InputReader in, PrintWriter out) { this.in=in; this.out=out; // sieve(); // pow2[0]=1; // for(int i=1;i<pow2.length;i++){ // pow2[i]= mul(pow2[i-1],2); // } int t= 1; preprocess(); // int t=in.nextInt(); // int t= cin.nextIntArrLine()[0]; for(int i=1;i<=t;i++) solveB(i); } final double pi= Math.acos(-1); static Point base; public void solveB(int t){ int n= in.nextInt(); int wb=0, bw=0, _b=0, b_=0, _w=0, w_=0, __=0, bb=0, ww=0; for(int i=0;i<n;i++){ String temp= in.nextToken(); if(temp.equals("BB")) bb++; if(temp.equals("BW")) bw++; if(temp.equals("WB")) wb++; if(temp.equals("WW")) ww++; if(temp.equals("B?")) b_++; if(temp.equals("?B")) _b++; if(temp.equals("W?")) w_++; if(temp.equals("?W")) _w++; if(temp.equals("??")) __++; } int b= 2*bb+bw+wb+b_+_b, w= 2*ww+bw+wb+w_+_w, x= 2*__+b_+_b+_w+w_; if(b>n) { out.println(0); return; } int res= Ckn(x,Math.max(n-b,0)), ans=0; int WB= wb+w_+_b, BW= bw+b_+_w; if(WB!=0 && BW!=0) { if(__!=0)ans= power(2,__); } else if((WB==0 && BW!=0) || (WB!=0 && BW==0)) { if(__!=0) ans= add(power(2,__),-1); } else { if(__!=0) ans= add(power(2,__),-2); } if(bb==0 && ww==0)res= add(res,-ans); out.println(res); } static class Node implements Comparable<Node>{ char op; int s; public Node (char op, int s) { this.op= op; this.s= s; } @Override public int compareTo(Node o) { if (this.s==o.s) return (int)(this.op-o.op); return this.s-o.s; } } private long distance(Point p1, Point p2) { long x= p1.x-p2.x, y= p1.y-p2.y; return x*x+y*y; } private boolean eqPoint(Point p1, Point p2){ return p1.x==p2.x && p1.y==p2.y; } private double polarAngle(Point p1, Point p2) { // p1 -> p2 if (p1.x==p2.x) return pi/2; else if (p1.y==p2.y){ if(p1.x<p2.x) return 0; else return pi; } else { double y= (double)p2.y-(double)p1.y; double x= (double)p2.x-(double)p1.x; BigDecimal alpha1= new BigDecimal(y); BigDecimal alpha2= new BigDecimal(x); BigDecimal val= alpha1.divide(alpha2); double angle= Math.atan(val.doubleValue()); if (angle<0) angle+= pi; out.println("angle: "+angle); return angle; } } private boolean isRightTurn(Point p1, Point p2, Point p3){ Vector v1= new Vector(p1,p2), v2= new Vector(p1,p3); if(crossProd(v1,v2)<0) return true; else return false; } private long crossProd(Vector v1, Vector v2){ //x1*y2-x2*y1 return v1.x*v2.y - v2.x*v1.y; } static class PointAngle implements Comparable<PointAngle>{ Point p; double angle; long dis; public PointAngle(Point p, double angle, long dis) { this.p= p; this.angle= angle; this.dis= dis; } @Override public int compareTo(PointAngle o) { double dif= this.angle-o.angle; if (dif <0) return -1; else if(dif >0) return 1; else { long dif2r= this.dis-o.dis; long dif2l= o.dis-this.dis; if (base.x < this.p.x) return intDif(dif2r); else return intDif(dif2l); } } private int intDif(long a){ if (a>0) return 1; else if(a<0) return -1; else return 0; } } public long _gcd(long a, long b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } public long _lcm(long a, long b){ return (a*b)/_gcd(a,b); } } // static class SEG { // Pair[] segtree; // public SEG(int n){ // segtree= new Pair[4*n]; // Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE)); // } // // void buildTree(int l, int r, int index) { // // if (l == r) { // // segtree[index].y = a[l]; // // return; // // } // // int mid = (l + r) / 2; // // buildTree(l, mid, 2 * index + 1); // // buildTree(mid + 1, r, 2 * index + 2); // // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y); // // } // void update(int l, int r, int index, int pos, Pair val) { // if (l == r) { // segtree[index] = val; // return; // } // int mid = (l + r) / 2; // if (pos <= mid) update(l, mid, 2 * index + 1, pos, val); // else update(mid + 1, r, 2 * index + 2, pos, val); // if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){ // segtree[index]= segtree[2 * index + 1]; // } // else { // segtree[index]= segtree[2 * index + 2]; // } // } // // Pair query(int l, int r, int from, int to, int index) { // // if (from <= l && r <= to) // // return segtree[index]; // // if (r < from | to < l) // // return 0; // // int mid = (l + r) / 2; // // Pair left= query(l, mid, from, to, 2 * index + 1); // // Pair right= query(mid + 1, r, from, to, 2 * index + 2); // // if(left.y < right.y) return left; // // else return right; // // } // } static class Venice{ public Map<Long,Long> m= new HashMap<>(); public long base=0; public long totalValue=0; private int M= 1000000007; private long addMod(long a, long b){ a+=b; if(a>=M) a-=M; return a; } public void reset(){ m= new HashMap<>(); base=0; totalValue=0; } public void update(long add){ base= base+ add; } public void add(long key, long val){ long newKey= key-base; m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val)); } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ return this.z-o.z; } } static class Point implements Comparable<Point>{ public long x; public long y; public Point(long x, long y){ this.x= x; this.y= y; } @Override public int compareTo(Point o) { if(this.y!=o.y) return (int)(this.y-o.y); return (int)(this.x-o.x); } } static class Vector { public long x; public long y; // p1 -> p2 public Vector(Point p1, Point p2){ this.x= p2.x-p1.x; this.y= p2.y-p1.y; } } static class Pair implements Comparable<Pair>{ public int x; public int y; public Pair(int x, int y){ this.x= x; this.y= y; } @Override public int compareTo(Pair o) { if(this.x!=o.x) return this.x-o.x; return (int)(this.y-o.y); } } // public static class compareL implements Comparator<Tuple>{ // @Override // public int compare(Tuple t1, Tuple t2) { // return t2.l - t1.l; // } // } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } public int[] nextIntArr(int n){ int[] arr= new int[n]; for(int i=0;i<n;i++) arr[i]= nextInt(); return arr; } public long[] nextLongArr(int n){ long[] arr= new long[n]; for(int i=0;i<n;i++) arr[i]= nextLong(); return arr; } public List<Integer> nextIntList(int n){ List<Integer> arr= new ArrayList<>(); for(int i=0;i<n;i++) arr.add(nextInt()); return arr; } public int[][] nextIntMatArr(int n, int m){ int[][] mat= new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt(); return mat; } public List<List<Integer>> nextIntMatList(int n, int m){ List<List<Integer>> mat= new ArrayList<>(); for(int i=0;i<n;i++){ List<Integer> temp= new ArrayList<>(); for(int j=0;j<m;j++) temp.add(nextInt()); mat.add(temp); } return mat; } public char[] nextStringCharArr(){ return nextToken().toCharArray(); } } static class CustomFileReader{ String path=""; Scanner sc; public CustomFileReader(String path){ this.path=path; try{ sc= new Scanner(new File(path)); } catch(Exception e){} } public String nextLine(){ return sc.nextLine(); } public int[] nextIntArrLine(){ String line= sc.nextLine(); String[] part= line.split("[\\s+]"); int[] res= new int[part.length]; for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]); return res; } } }
Java
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
1 second
["1", "2", "10"]
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
Java 11
standard input
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
3858151e51f6c97abe8904628b70ad7f
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
2,400
Print a single integer — the answer to the problem.
standard output
PASSED
8d41a2844ab9827cceb7f91df8fea20f
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
// Piyush Nagpal import java.util.*; import java.io.*; public class C{ static int MOD=1000000007; static PrintWriter pw; static FastReader sc; 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());} public char nextChar() throws IOException {return next().charAt(0);} String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int[] intArr(int a,int b,int n) throws IOException {int[]in=new int[n];for(int i=a;i<b;i++)in[i]=nextInt();return in;} public long[] longArr(int a,int b,int n) throws IOException {long[]in=new long[n];for(int i=a;i<b;i++)in[i]=nextLong();return in;} public ArrayList<Integer> intlist(int n)throws IOException {ArrayList<Integer> list= new ArrayList<>();for(int i=0;i<n;i++)list.add(nextInt());return list;} public ArrayList<Long> longlist(int n)throws IOException {ArrayList<Long> list= new ArrayList<>();for(int i=0;i<n;i++)list.add(nextLong());return list;} } public static long gcd(long a,long b){if( b>a ){return gcd(b,a);}if( b==0 ){return a;} return gcd(b,a%b);} public static long expo( long a,long b,long M ){long result=1;while(b>0){if( b%2==1 ){result=(result*a)%M;}a=(a*a)%M;b=b/2;}return result%M;} public static ArrayList<Long> Sieve(int n){boolean [] arr= new boolean[n+1];Arrays.fill(arr, true);ArrayList<Long> list= new ArrayList<>();for(int i=2;i<=n;i++){if( arr[i]==true ){list.add((long)i);}for(int j=2*i;j<=n;j+=i){arr[j]=false;}}return list;} public static void parr(int [] arr){for(int i=0;i<arr.length;i++){pw.print(arr[i]+" ");}} public static void parr(long [] arr){for(int i=0;i<arr.length;i++){pw.print(arr[i]+" ");}} public static void plist(ArrayList<Integer> list){for(int i=0;i<list.size();i++){pw.print(list.get(i)+" ");}} public static void pllist(ArrayList<Long> list){for(int i=0;i<list.size();i++){pw.print(list.get(i)+" ");}} // int [] arr=sc.intArr(a,b,n); <b static void solve() throws Exception{ int n=sc.nextInt(),a=sc.nextInt(),b=sc.nextInt(); int max=0,min=0; if(n%2==0){ max=min=n/2; }else{ max=n/2; min=(n/2)-1; } // -1 if( (a+b)>(n-2) || Math.abs(a-b)>1 ){ pw.println("-1"); return; } ArrayList<Integer> list= new ArrayList<>(); for(int i=1;i<=n;i++){ list.add(i); } if(a==b){ if(a>0){ for(int i=1;i<list.size()-1;i+=2){ swap(list,i,i+1); a--; if(a==0){ break; } } } }else if(a>b){ // last swap swap(list,list.size()-1,list.size()-2); a--; if(a>0){ for(int i=1;i<list.size()-2;i+=2){ swap(list,i,i+1); a--; if(a==0){ break; } } } }else if(b>a){ int temp=list.get(0); list.set(0,list.get(1)); list.set(1,temp); b--; if(b>0){ for(int i=2;i<list.size()-1;i+=2){ swap(list,i,i+1); b--; if(b==0){ break; } } } } plist(list); pw.println(); } public static void swap(ArrayList<Integer> list,int i,int j){ int temp=list.get(j); list.set(j,list.get(i)); list.set(i,temp); } public static void main(String[] args) throws Exception{ try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { System.err.println("Error"); } sc= new FastReader(); pw = new PrintWriter(System.out); int tc=1; tc=sc.nextInt(); for(int i=1;i<=tc;i++) { // pw.printf("Case #%d: ", i); solve(); } pw.flush(); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
7083cedc46aa36cae91b65f0d0acb31c
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
// Piyush Nagpal import java.util.*; import java.io.*; public class C{ static int MOD=1000000007; static PrintWriter pw; static FastReader sc; 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());} public char nextChar() throws IOException {return next().charAt(0);} String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int[] intArr(int a,int b,int n) throws IOException {int[]in=new int[n];for(int i=a;i<b;i++)in[i]=nextInt();return in;} public long[] longArr(int a,int b,int n) throws IOException {long[]in=new long[n];for(int i=a;i<b;i++)in[i]=nextLong();return in;} public ArrayList<Integer> intlist(int n)throws IOException {ArrayList<Integer> list= new ArrayList<>();for(int i=0;i<n;i++)list.add(nextInt());return list;} public ArrayList<Long> longlist(int n)throws IOException {ArrayList<Long> list= new ArrayList<>();for(int i=0;i<n;i++)list.add(nextLong());return list;} } public static long gcd(long a,long b){if( b>a ){return gcd(b,a);}if( b==0 ){return a;} return gcd(b,a%b);} public static long expo( long a,long b,long M ){long result=1;while(b>0){if( b%2==1 ){result=(result*a)%M;}a=(a*a)%M;b=b/2;}return result%M;} public static ArrayList<Long> Sieve(int n){boolean [] arr= new boolean[n+1];Arrays.fill(arr, true);ArrayList<Long> list= new ArrayList<>();for(int i=2;i<=n;i++){if( arr[i]==true ){list.add((long)i);}for(int j=2*i;j<=n;j+=i){arr[j]=false;}}return list;} public static void parr(int [] arr){for(int i=0;i<arr.length;i++){pw.print(arr[i]+" ");}} public static void parr(long [] arr){for(int i=0;i<arr.length;i++){pw.print(arr[i]+" ");}} public static void plist(ArrayList<Integer> list){for(int i=0;i<list.size();i++){pw.print(list.get(i)+" ");}} public static void pllist(ArrayList<Long> list){for(int i=0;i<list.size();i++){pw.print(list.get(i)+" ");}} // int [] arr=sc.intArr(a,b,n); <b static void solve() throws Exception{ int n=sc.nextInt(),a=sc.nextInt(),b=sc.nextInt(); // -1 if( (a+b)>(n-2) || Math.abs(a-b)>1 ){ pw.println("-1"); return; } ArrayList<Integer> list= new ArrayList<>(); for(int i=1;i<=n;i++){ list.add(i); } int i=1,j=2; while(a>0 && b>0){ swap(list,i,j); i+=2; j+=2; a--;b--; } if(b>0){ pw.print(list.get(list.size()-1)+" "); for(int k=0;k<list.size()-1;k++){ pw.print(list.get(k)+" "); } pw.println(); return; }else if(a>0){ swap(list,list.size()-2,list.size()-1); } plist(list); pw.println(); } public static void swap(ArrayList<Integer> list,int i,int j){ int temp=list.get(j); list.set(j,list.get(i)); list.set(i,temp); } public static void main(String[] args) throws Exception{ try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { System.err.println("Error"); } sc= new FastReader(); pw = new PrintWriter(System.out); int tc=1; tc=sc.nextInt(); for(int i=1;i<=tc;i++) { // pw.printf("Case #%d: ", i); solve(); } pw.flush(); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
859b29f6853b4a531758f32600ee2614
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
//int /*package whatever //do not write package name here */ import java.util.*; public class Main { public static void main (String[] args) { Scanner sc=new Scanner(System.in); // Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int a=sc.nextInt(); int b=sc.nextInt(); if(a==0&&b==0){ int x=1,y=n; while(y>=x){ System.out.print(y+" "); y--; } } else if(Math.abs(a-b)>1||(a+b>n-2)){ System.out.print("-1"); } else{ ArrayList<Integer> arr=new ArrayList<>(); int x=1,y=n; if(a==b){ arr.add(x); x++; int h=0; while(h<a){ arr.add(y); arr.add(x); y--; x++; h++; } while(x<=y){ arr.add(x); x++; } } else if(a>b){ int h=0; arr.add(x); x++; while(h<a-1){ arr.add(y); arr.add(x); x++; y--; h++; } // for(int i=1;i<=b+1;i++){ // arr.add(x); // arr.add(y); // //System.out.print(x+" "+y+" "); // x++; // y--; // } while(y>=x){ // System.out.print(y+" "); arr.add(y); y--; } } else{ // for(int i=1;i<=a+1;i++){ // // System.out.print(y+" "+x+" "); // arr.add(y); // arr.add(x); // x++; // y--; // } int h=0; arr.add(y); y--; while(h<b-1){ arr.add(x); arr.add(y); x++; y--; h++; } while(x<=y){ // System.out.print(y+" "); arr.add(x); x++; } } for(int h:arr){ System.out.print(h+" "); } } System.out.println(); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
54ef46cad20c4cdb01aa15ebf86c3c30
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; public class Main { public static void main(String []args) { int t; Scanner in=new Scanner(System.in); t=in.nextInt(); while((t--)!=0) { int n; n=in.nextInt(); int a,b; a=in.nextInt(); b=in.nextInt(); if(Math.abs(a-b)>1||(a+b)>n-2) { System.out.println(-1); continue; } if(a>b) { int l=1; int r=n; int i; for(i=1;i<=a;i++) { System.out.print(l++ +" "); System.out.print(r-- +" "); } for(i=r;i>=l;i--)System.out.print(i+" "); System.out.println(); } else if(a<b) { int l=1; int r=n; int i; for(i=1;i<=b;i++) { System.out.print(r-- +" "); System.out.print(l++ +" "); } for(i=l;i<=r;i++)System.out.print(i+" "); System.out.println(); } else { int l=1; int r=n; int i; for(i=1;i<=b;i++) { System.out.print(r-- +" "); System.out.print(l++ +" "); } for(i=r;i>=l;i--)System.out.print(i+" "); System.out.println(); } } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
777a2bdd5be479be01a8d0c71e1ec111
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; import java.io.*; public class B1608{ static FastScanner fs = null; 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 a = fs.nextInt(); int b = fs.nextInt(); int d = a-b; if(d<0) d*=-1; if(d<=1){ if(n%2==0){ if(a<(n/2) && b<n/2){ if(a>b){ int s1 = 1; int s2 = n; int c = 0; while (s2>=s1) { c+=1; if(a>0 && b>0){ out.print(s1+" "+s2+" "); if(c>1){ a-=1; b-=1; } s1+=1; s2-=1; } else if(a>0){ if(c==1){ out.print(s1+" "+s2+" "); s2-=1; s1+=1; } else{ out.print(s2+" "); s2-=1; } } else{ out.print(s2+" "); s2-=1; } } } else{ int s1 = 1; int s2 = n; int c = 0; while (s2>=s1) { c+=1; if(a==1 && b==1){ out.print(s2+" "); a-=1; b-=1; s2-=1; if(c==1){ out.print(s1+" "); s1+=1; } } else if(a>0 && b>0){ out.print(s2+" "+s1+" "); if(c>1){ a-=1; b-=1; } s1+=1; s2-=1; } else if(b>0){ if(c==1){ out.print(s2+" "+s1+" "); s1+=1; s2-=1; } else{ out.print(s1+" "); s1+=1; } } else{ out.print(s2+" "); s2-=1; } } } } else{ out.print("-1"); } } else{ int mn = Math.min(a,b); int mx = Math.max(a,b); if(mn<(n/2) && mx<=(n/2)){ if(a>b){ int s1 = 1; int s2 = n; int c = 0; while (s2>=s1) { c+=1; if(a>0 && b>0){ out.print(s1+" "+s2+" "); if(c>1){ a-=1; b-=1; } s1+=1; s2-=1; } else if(a>0){ if(c==1){ out.print(s1+" "+s2+" "); s2-=1; s1+=1; } else{ out.print(s2+" "); s2-=1; } } else{ out.print(s2+" "); s2-=1; } } } else{ int s1 = 1; int s2 = n; int c = 0; while (s2>=s1) { c+=1; if(a==1 && b==1){ out.print(s2+" "); a-=1; b-=1; s2-=1; if(c==1){ out.print(s1+" "); s1+=1; } } else if(a>0 && b>0){ out.print(s2+" "+s1+" "); if(c>1){ a-=1; b-=1; } s1+=1; s2-=1; } else if(b>0){ if(c==1){ out.print(s2+" "+s1+" "); s1+=1; s2-=1; } else{ out.print(s1+" "); s1+=1; } } else{ out.print(s2+" "); s2-=1; } } } } else{ out.print("-1"); } } } else out.print("-1"); out.println(); } out.close(); } 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()); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
a3c3a23078d5b5eb1b534bedadc6b4f3
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
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.StringTokenizer; public class Main { BufferedReader in; PrintWriter out; Main() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } void close() throws IOException { in.close(); out.flush(); out.close(); } void solve() throws IOException { int t = Integer.parseInt(in.readLine()); while (t > 0) { StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int sum = n - 2; int h; if (n % 2 == 1) { h = sum / 2 + 1; } else { h = sum / 2; } if (a + b <= sum && a <= h && b <= h && Math.abs(a - b) <= 1) { int c = 0; int d = n - 1; ArrayList<Integer> res = new ArrayList<>(); if (a >= b) { res.add(0); c++; while (a > 0 || b > 0) { if (a > 0) { res.add(d); a--; d--; } if (b > 0) { res.add(c); b--; c++; } } } else { res.add(n - 1); d--; while (a > 0 || b > 0) { if (b > 0) { res.add(c); b--; c++; } if (a > 0) { res.add(d); a--; d--; } } } if (res.get(res.size() - 1) == c - 1) { for (int j = c; j <= d; j++) { res.add(j); } } else { for (int j = d; j >= c; j--) { res.add(j); } } for (int i = 0; i < n; i++) { if (i != 0) { out.append(' '); } out.append(String.format("%d", res.get(i) + 1)); } out.append('\n'); } else { out.append("-1\n"); } t--; } } public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
1e92467c7491f3bcfd64f9fc81e7e2ab
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f; public static int mod = 1000000007; public static int mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = true; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);o.println();} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static void solve(PrintWriter o){ try { int n = fReader.nextInt(), a = fReader.nextInt(), b = fReader.nextInt(); if(n-2 < a+b || Math.abs(a-b) > 1){ o.print(-1); return; } if(a == b){ o.print(1 + " "); for(int i=3;i<=2*a+1;i+=2) o.print(i + " " + (i-1) + " "); for(int i=2*a+2;i<=n;i++) o.print(i + " "); } else if(a > b){ for(int i=1;i<=n-2*a;i++) o.print(i + " "); for(int i=n-2*a+2;i<=n;i+=2) o.print(i + " " + (i-1) + " "); } else{ for(int i=2;i<=2*b;i+=2) o.print(i + " " + (i-1) + " "); for(int i=2*b+1;i<=n;i++) o.print(i + " "); } } catch (Exception e){e.printStackTrace();} } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static void reverse(int[] array){ reverse(array, 0 , array.length-1); } public static void reverse(int[] array, int left, int right) { if (array != null) { int i = left; for(int j = right; j > i; ++i) { int tmp = array[j]; array[j] = array[i]; array[i] = tmp; --j; } } } public static long qpow(long a, long n){ long ret = 1l; while(n > 0){ if((n & 1) == 1) ret = ret * a % mod; n >>= 1; a = a * a % mod; } return ret; } public static class unionFind { int[] parent; int[] size; int n; public unionFind(int n){ this.n = n; parent = new int[n]; size = new int[n]; for(int i=1;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(p != parent[p]){ parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q){ int root_p = find(p); int root_q = find(q); if(root_p == root_q) return; if(size[root_p] >= size[root_q]){ parent[root_q] = root_p; size[root_p] += size[root_q]; size[root_q] = 0; } else{ parent[root_p] = root_q; size[root_q] += size[root_p]; size[root_p] = 0; } n--; } public int getCount(){ return n; } public int[] getSize(){ return size; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
47fd2270c9ce46edc0d27ec159c5239f
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.Buffer; import java.util.Scanner; public class fastTemp { public static void main(String[] args) throws IOException, NumberFormatException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String s[] = br.readLine().split(" "); int n = Integer.parseInt(s[0]); int a = Integer.parseInt(s[1]); int b = Integer.parseInt(s[2]); boolean tt = false; if (n - (a + b) < 2 || Math.abs(a - b) > 1) { System.out.println(-1); } else if (a==b) { int l=1; int r = n-1; System.out.print(n+" "); for(int i=0;i<a;i++){ System.out.print(l+" "+r+" "); l++; r--; } while(r>=l){ System.out.print(r+" "); r--; } System.out.println(); }else if(a>b){ int l=1; int r = n; for(int i=0;i<a;i++){ System.out.print(l+" "+r+" "); l++; r--; } while(r>=l){ System.out.print(r+" "); r--; } System.out.println(); }else{ int l=1; int r = n; for(int i=0;i<b;i++){ System.out.print(r+" "+l+" "); r--; l++; } while(l<=r){ System.out.print(l+" "); l++; } System.out.println(); } } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
fc3aa7ecdb7b52fa89e376280be7a70d
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; public class B_Build_the_Permutation { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader f = new FastReader(); StringBuilder sb = new StringBuilder(); int t = f.nextInt(); while (t-- > 0) { String[] s = f.nextLine().split(" "); int n = Integer.parseInt(s[0]); int a = Integer.parseInt(s[1]); int b = Integer.parseInt(s[2]); if (Math.abs(a - b) > 1 || a + b > (n - 2)) { sb.append(-1 + "\n"); continue; } int[] arr=new int[n]; for(int i=0;i<arr.length;i++){ arr[i]=i+1; } if(a>b){ int v=arr.length-1; while(a>0){ int temp=arr[v]; arr[v]=arr[v-1]; arr[v-1]=temp; v-=2; a--; } }else if(b>=a){ int v=0; int u=b; while(u>0){ int temp=arr[v]; arr[v]=arr[v+1]; arr[v+1]=temp; v+=2; u--; } if(b==a&&b>0){ int m=arr[arr.length-1]; arr[arr.length-1]=arr[arr.length-2]; arr[arr.length-2]=m; } } for(int val:arr){ sb.append(val+" "); } sb.append("\n"); } System.out.println(sb); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
55fa5e65de65b94f523a6f018959b6da
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
// हर हर महादेव import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; import java.text.DecimalFormat; public final class Solution { static int inf = Integer.MAX_VALUE; static long mod = 1000000000 + 7; static void ne(Scanner sc, BufferedWriter op) throws Exception { int n=sc.nextInt(); int a=sc.nextInt(); int b=sc.nextInt(); int[] arr= new int[n]; if(Math.abs(a-b)>1){ op.write("-1\n"); return; } for(int i=0;i<n;i++){ arr[i]=i+1; } int no=(n-1)/2; // print(no); if(Math.max(a,b)>no){ op.write("-1\n"); return; } if((n-1)%2==0){ if(Math.min(a,b)>=no){ op.write("-1\n"); return; } } int aa=a; int bb=b; if(a>=b){ for(int i=n-2;i>=0 && a>0;i-=2){ swp(arr,i+1,i); a--; } }else{ for(int i=1;i<n && b>0;i+=2){ swp(arr,i-1,i); b--; } } if(aa==bb && aa!=0){ swp(arr,0,1); } // get(arr); for(int i=0;i<n;i++){ op.write(arr[i]+" "); } op.write("\n"); } public static void get(int[] arr){ int a=0; int b=0; int n=arr.length; for(int i=0;i<arr.length;i++){ if(i-1>=0 && i+1<n){ if(arr[i]<arr[i-1] && arr[i]<arr[i+1]){ b++; } if(arr[i]>arr[i-1] && arr[i]>arr[i+1]){ a++; } } } print(a+" "+b); } public static void swp(int[] arr, int i,int j){ int t=arr[j]; arr[j]=arr[i]; arr[i]=t; } public static boolean allEqual(int[] arr){ for(int i=1;i<arr.length;i++){ if(arr[i]!=arr[i-1]){ return false; } } return true; } public static void reverse(long[] arr){ int n=arr.length; for(int i=0;i<arr.length/2;i++){ long t=arr[i]; arr[i]= arr[n-i-1]; arr[n-i-1]=t; } } static long gcd(long a, long b){ if(a==0L) return b; return gcd(b%a,a); } public static void main(String[] args) throws Exception { BufferedWriter op = new BufferedWriter(new OutputStreamWriter(System.out)); // Reader sc = new Reader(); Scanner sc= new Scanner(System.in); int t = sc.nextInt(); while (t-->0){ ne(sc, op); } // ne(sc,op); op.flush(); } static void print(Object o) { System.out.println(String.valueOf(o)); } static int[] toIntArr(String s){ int[] val= new int[s.length()]; for(int i=0;i<s.length();i++){ val[i]=s.charAt(i)-'a'; } return val; } static void sort(int[] arr){ ArrayList<Integer> list= new ArrayList<>(); for(int i=0;i<arr.length;i++){ list.add(arr[i]); } Collections.sort(list); for(int i=0;i<arr.length;i++){ arr[i]=list.get(i); } } static void sort(long[] arr){ ArrayList<Long> list= new ArrayList<>(); for(int i=0;i<arr.length;i++){ list.add(arr[i]); } Collections.sort(list); for(int i=0;i<arr.length;i++){ arr[i]=list.get(i); } } } // return -1 to put no ahed in array class pair { long xx; int yy; pair(long xx, int yy ) { this.xx = xx; this.yy = yy; } } class sortY implements Comparator<pair> { public int compare(pair p1, pair p2) { if (p1.yy > p2.yy) { return 1; } else if (p1.yy == p2.yy) { if (p1.xx > p2.xx) { return 1; } else if (p1.xx < p2.xx) { return -1; } return 0; } return -1; } } class sortX implements Comparator<pair> { public int compare(pair p1, pair p2) { if (p1.xx > p2.xx) { return 1; } else if (p1.xx == p2.xx) { if (p1.yy > p2.yy) { return 1; } else if (p1.yy < p2.yy) { return -1; } return 0; } return -1; } } class debug { static void print1d(long[] arr) { System.out.println(); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } static void print1d(int[] arr) { System.out.println(); for (int i = 0; i < arr.length; i++) { System.out.println(i+" = "+arr[i]); } } static void print1d(boolean[] arr) { System.out.println(); for (int i = 0; i < arr.length; i++) { System.out.println(i + "= " + arr[i]); } } static void print2d(int[][] arr) { System.out.println(); int n = arr.length; int n2 = arr[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < n2; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } static void print2d(long[][] arr) { System.out.println(); int n = arr.length; int n2 = arr[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < n2; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } static void printPair(ArrayList<pair> list) { if(list.size()==0){ System.out.println("empty list"); return; } System.out.println(); for(int i=0;i<list.size();i++){ System.out.println(list.get(i).xx+"-"+list.get(i).yy); } } } 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(); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
61803f439dea94568c4f967cf935b770
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t=scanner.nextInt(); while (t--!=0){ int n= scanner.nextInt(); int a=scanner.nextInt(); int b=scanner.nextInt(); int [] nums=new int[n]; for (int i=0;i<n;i++) nums[i]=i+1; if(a==0&&b==0){ for (int i=1;i<=n;i++){ System.out.print(i+" "); } System.out.println(); continue; } if(a+b<=n-2&&b>=a-1&&b<=a+1){ if (a==0){ System.out.print(2+" "+1+" "); for (int i=3;i<=n;i++){ System.out.print(i+" "); } }else if (b==0){ System.out.print(1+" "+n+" "); for (int i=n-1;i>=2;i--){ System.out.print(i+" "); } }else if (a==b){ int cnt=0; for (int i=2;i<=n&&cnt<a;i+=2){ swap(nums,i,i-1); cnt++; } // System.out.println(cnt); for (int i = 0; i < nums.length; i++) { System.out.print(nums[i]+" "); } }else if (a>b){ int cnt=0; for (int i=n-a+1,j=1;i<=n;i++,j++){ System.out.print(j+" "+i+" "); cnt+=2; } for (int i=n-a;i>=b+2;i--){ System.out.print(i+" "); } }else { for (int i=n,j=b;i>n-b&&b>0;i--,j--){ System.out.print(i+" "+j+" "); } for (int i=b+1;i<=n-b;i++){ System.out.print(i+" "); } } System.out.println(); }else { System.out.println(-1); } } } public static void swap(int []a,int i,int j){ int tmp=a[i]; a[i]=a[j]; a[j]=tmp; } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
e613947cdc74725cf907759001846318
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
//package com.example.lib; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; public class Algorithm { public static void main(String[] rgs) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\USER\\AndroidStudioProjects\\MyApplication\\lib\\src\\main\\java\\com\\example\\lib\\inpu")); StringBuilder stringBuilder= new StringBuilder(); int t= Integer.parseInt(bufferedReader.readLine()); for (int i = 0; i < t; i++) { String[] arr= bufferedReader.readLine().split(" "); int number=Integer.parseInt( arr[0]); int inc= Integer.parseInt(arr[1]); int dec= Integer.parseInt(arr[2]); if(inc+dec>number-2 || Math.abs(inc-dec)>1|| inc>= (number+1)/2 || dec>= (number+1)/2){ stringBuilder.append("-1\n"); continue; } StringBuilder ans = new StringBuilder(); if(inc==0 && dec==0){ for (int j = 0; j < number; j++) { ans.append(j+1).append(" "); } stringBuilder.append(ans+"\n"); continue; } int [] ansarr = new int[number+1]; if(inc> dec) { int tempnum = number; for (int j = 2; j < ansarr.length - 1; j += 2) { ansarr[j] = tempnum; tempnum--; if(number-tempnum==inc)break; } for (int j = 1; j < ansarr.length; j++) { if (ansarr[j] == 0) { ansarr[j] = tempnum--; } } }else if(inc==dec){ int tempnum = 1; for (int j = 2; j < ansarr.length; j+=2) { ansarr[j]=tempnum; tempnum++; if(tempnum-1==inc)break; } if(ansarr[ansarr.length-1]==0)ansarr[ansarr.length-1]= tempnum++; for (int j = 1; j < ansarr.length; j++) { if(ansarr[j]==0){ ansarr[j]= tempnum++; } } }else { int tempnum = 1; for (int j = 2; j < ansarr.length-1; j+=2) { ansarr[j]=tempnum; tempnum++; if(tempnum-1==dec)break; } for (int j = 1; j < ansarr.length; j++) { if(ansarr[j]==0){ ansarr[j]= tempnum++; } } } for (int j = 1; j < ansarr.length; j++) { ans.append(ansarr[j]).append(" "); } stringBuilder.append(ans+"\n"); } System.out.println(stringBuilder); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
440ec354118ca7de9f6036bd0aca2cfb
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
/*========================================================================== * AUTHOR: RonWonWon * CREATED: 12.12.2021 23:16:04 /*==========================================================================*/ import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { /* in.ini(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); */ long startTime = System.nanoTime(); int t = in.nextInt(), T = 1; while(t-->0) { int n = in.nextInt(), a = in.nextInt(), b = in.nextInt(); int ar[] = new int[n]; if(a==0&&b==0){ for(int i=1;i<=n;i++) out.print(i+" "); out.println(); } else if(a-b==1){ if(a>(n-1)/2){ out.println(-1); continue; } int p = n, q = 1, ind = 0; for(int i=0;i<a;i++){ ar[ind] = q; ar[ind+1] = p; ind += 2; p--; q++; } while(ind<n){ ar[ind++] = p--; } for(int i : ar) out.print(i+" "); out.println(); } else if(b-a==1){ if(b>(n-1)/2){ out.println(-1); continue; } int p = 1, q = n, ind = 0; for(int i=0;i<b;i++){ ar[ind] = q; ar[ind+1] = p; ind += 2; p++; q--; } while(ind<n){ ar[ind++] = p++; } for(int i : ar) out.print(i+" "); out.println(); } else if(a==b && a<=(n-1)/2){ if(a==(n-1)/2&&n%2==1){ out.println(-1); continue; } int p=2, q=n, ind = 1; ar[0] = 1; for(int i=0;i<a;i++){ ar[ind] = q; ar[ind+1] = p; p++; q--; ind+=2; } while(ind<n) ar[ind++] = p++; for(int i=1;i<n-1;i++){ if(ar[i-1]<ar[i]&&ar[i]>ar[i+1]) a--; else if(ar[i-1]>ar[i]&&ar[i]<ar[i+1]) b--; } if(a!=0||b!=0){ out.println(-1); continue; } for(int i : ar) out.print(i+" "); out.println(); } else{ out.println(-1); } //out.println("Case #"+T+": "+ans); T++; } /* startTime = System.nanoTime() - startTime; System.err.println("Time: "+(startTime/1000000)); */ out.flush(); } static FastScanner in = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static int oo = Integer.MAX_VALUE; static long ooo = Long.MAX_VALUE; static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); void ini() throws FileNotFoundException { br = new BufferedReader(new FileReader("input.txt")); } String next() { while(!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch(IOException e) {} return st.nextToken(); } String nextLine(){ try{ return br.readLine(); } catch(IOException e) { } return ""; } 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()); } long[] readArrayL(int n) { long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nextLong(); return a; } double nextDouble() { return Double.parseDouble(next()); } double[] readArrayD(int n) { double a[] = new double[n]; for(int i=0;i<n;i++) a[i] = nextDouble(); return a; } } static final Random random = new Random(); static void ruffleSort(int[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n), temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } static void ruffleSortL(long[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n); long temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
d9e4ab45d3195b7ae62fe91d72da43c5
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.math.*; import java.util.* ; import java.io.* ; @SuppressWarnings("unused") public class B { static final int mod = (int)1e9+7 ; static final double pi = 3.1415926536 ; static boolean not_prime[] = new boolean[1000001] ; static void sieve() { for(int i=2 ; i*i<1000001 ; i++) { if(not_prime[i]==false) { for(int j=2*i ; j<1000001 ; j+=i) { not_prime[j]=true ; } } }not_prime[0]=true ; not_prime[1]=true ; } public static long bexp(long base , long power) { long res=1L ; base = base%mod ; while(power>0) { if((power&1)==1) { res=(res*base)%mod ; power-- ; } else { base=(base*base)%mod ; power>>=1 ; } } return res ; } static long modInverse(long n, long p){return power(n, p - 2, p); } static long power(long x, long y, long p) { // Initialize result long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long nCrModPFermat(int n, int r, long p){if(n<r) return 0 ;if (r == 0)return 1; long[] fac = new long[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;} static long mod_add(long a, long b){ return ((a % mod) + (b % mod)) % mod; } static long mod_sub(long a, long b){ return ((a % mod) - (b % mod) + mod) % mod; } static long mod_mult(long a, long b){ return ((a % mod) * (b % mod)) % mod; } static long lcm(int a, int b){ return (a / gcd(a, b)) * b; } static long gcd(long a, long b){if (b == 0) {return a;}return gcd(b, a % b);} public static void main(String[] args)throws IOException//throws FileNotFoundException { FastReader in = new FastReader() ; StringBuilder op = new StringBuilder() ; int T = in.nextInt() ; // int T=1 ; for(int tt=0 ; tt<T ; tt++) { int n = in.nextInt() ; int a = in.nextInt() ; int b = in.nextInt() ; int maxfill=n ; int minfill=1 ; if(Math.abs(a-b)>1 || a+b>n-2) { op.append("-1\n") ; continue ; } if(a>b) { for(int i=1 ; i<=2*a ; i++) { if((i&1)==1)op.append(minfill++).append(" ") ; else op.append(maxfill--).append(" ") ; } for(int i=2*a+1 ; i<=n ; i++) { op.append(maxfill--).append(" ") ; } } else if(a<b) { for(int i=1 ; i<=2*b ; i++) { if((i&1)==1)op.append(maxfill--).append(" ") ; else op.append(minfill++).append(" ") ; } for(int i=2*b+1 ; i<=n ; i++) { op.append(minfill++).append(" ") ; } } else if(a!=0){ for(int i=1 ; i<=2*a ; i++) { if((i&1)==1)op.append(minfill++).append(" ") ; else op.append(maxfill--).append(" ") ; } for(int i=2*a+1 ; i<=n ; i++) { op.append(minfill++).append(" ") ; } } else { for(int i=1 ; i<=n ; i++) op.append(maxfill--).append(" ") ; } op.append("\n") ; } System.out.println(op.toString()); } static class pair implements Comparable<pair> { int first , second ; pair(int first , int second){ this.first=first ; this.second=second; } public int compareTo(pair other) { return this.first-other.first ; } } 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 FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); }; String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
492a0df8e7caa6de6a7f164c3589e7fa
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.PI; import static java.lang.System.in; import static java.lang.System.out; import static java.lang.System.err; public class B { static int what(ArrayList<Integer> arr, int min, int max) { int mina = 0, maxa = 0; for(int i = 1; i < arr.size()-1; i++) { int prev = arr.get(i-1); int cur = arr.get(i); int next = arr.get(i+1); if(prev > cur && cur < next) mina++; if(prev < cur && cur > next) maxa++; } // out.println(arr); // out.println(maxa + " " + mina); if(mina==min && maxa==max) return 1; return 0; } public static void main(String[] args) throws Exception { Foster sc = new Foster(); PrintWriter p = new PrintWriter(out); /* * Is that extra condition needed * Check overflow in pow function or in general * Check indices of read array functions * Think of an easier solution because the problems you solve are always easy * Check the iterator of loop */ int t = sc.nextInt(); while(t--!=0) { int n = sc.nextInt(), b = sc.nextInt(), a = sc.nextInt(); int min = a, max = b; // if(a+b+2 > n) { // p.println("-1"); // continue; // } // if(Math.abs(a-b) > 1) { // p.println("-1"); // continue; // } // if(a==b && n%2!=0) { // p.println("-1"); // continue; // } if(a==0 && b==0) { for(int i = 1; i <= n; i++) { p.print(i + " "); } p.println(); continue; } ArrayList<Integer> arr = new ArrayList<>(); int L = 1, H = n; if(a==b) { arr.add(L); L++; while(b > 0) { // p.print(H + " "); arr.add(H); H--; b--; if(a > 0) { // p.print(L + " "); arr.add(L); L++; a--; } } while(H >= L) { // p.print(H + " "); arr.add(L); L++; } } else if(a > b) { // p.print(H + " "); arr.add(H); H--; while(a > 0) { // p.print(L + " "); arr.add(L); L++; a--; if(b > 0) { // p.print(H + " "); arr.add(H); H--; b--; } } while(L <= H) { // p.print(L + " "); arr.add(L); L++; } } else { // p.print(L + " "); arr.add(L); L++; while(b > 0) { // p.print(H + " "); arr.add(H); H--; b--; if(a > 0) { // p.print(L + " "); arr.add(L); L++; a--; } } while(H >= L) { // p.print(H + " "); arr.add(H); H--; } } if(what(arr, min, max)==1) { for(int i : arr) { p.print(i + " "); } p.println(); } else { p.println("-1"); } } p.close(); } static long[] sort(long a[]) { ArrayList<Long> arr = new ArrayList<>(); for(long i : a) { arr.add(i); } Collections.sort(arr); for(int i = 0; i < arr.size(); i++) { a[i] = arr.get(i); } return a; } static int[] sort(int a[]) { ArrayList<Integer> arr = new ArrayList<>(); for(int i : a){ arr.add(i); } Collections.sort(arr); // Collections.reverse(arr); for(int i = 0; i < arr.size(); i++){ a[i] = arr.get(i); } return a; } static class Foster { BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] intArray(int n) { int arr[] = new int[n]; for(int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } long[] longArray(int n) { long arr[] = new long[n]; for(int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } static long pow(long... a) { long mod = Long.MAX_VALUE; if(a.length == 3) mod = a[2]; long res = 1; while(a[1] > 0) { if((a[1] & 1) == 1) res = (res * a[0]) % mod; a[1] /= 2; a[0] = (a[0] * a[0]) % mod; } return res; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
e3af43b336849944e0fc6df9b3544979
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; import java.io.*; public class tr0 { static PrintWriter out; static StringBuilder sb; static long mod = (long) 998244353; static long inf = (long) 1e16; static int n, m; static ArrayList<Integer>[] ad; static int[][] remove, add; static int[][][] memo; static boolean vis[]; static long[] inv, f, ncr[]; static HashMap<Integer, Integer> hm; static int[] pre, suf, Smax[], Smin[]; static int idmax, idmin; static ArrayList<Integer> av; static HashMap<Integer, Integer> mm; static boolean[] msks; static int[] lazy[], lazyCount; static int[] dist; static int[][] P; static long N; static ArrayList<Integer> gl; static int[] a, b; static String s; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int t = sc.nextInt(); all: while (t-- > 0) { int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); if (Math.abs(a - b) >= 2 || a + b > n - 2) { out.println(-1); continue; } if (a == 0 && b == 0) { for (int i = 1; i <= n; i++) out.print(i + " "); out.println(); continue; } TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i < n; i++) ts.add(i + 1); int[] ar = new int[n]; if (a == b) { ar[0] = ts.pollFirst(); int c = 0; for (int i = 1; i < n; i += 2) { c++; if (ts.isEmpty()) { out.println(-1); continue all; } ar[i] = ts.pollLast(); if (ts.isEmpty()) { out.println(-1); continue all; } ar[i + 1] = ts.pollFirst(); if (i + 1 == n - 1) { out.println(-1); continue all; } if (c == a) { i += 2; while (!ts.isEmpty()) { ar[i] = ts.pollFirst(); i++; } break; } } if (c < a) { out.println(-1); continue; } } else if (a > b) { if (a == 1) { ar[0] = ts.pollFirst(); int i = 1; while (i < n) { ar[i] = ts.pollLast(); i++; } } else { ar[0] = ts.pollFirst(); int c = 0; for (int i = 1; i < n; i += 2) { c++; if (ts.isEmpty()) { out.println(-1); continue all; } ar[i] = ts.pollLast(); if (ts.isEmpty()) { out.println(-1); continue all; } ar[i + 1] = ts.pollFirst(); if (i + 1 == n - 1) { out.println(-1); continue all; } if (c == b) { i += 2; while (!ts.isEmpty()) { ar[i] = ts.pollLast(); i++; } break; } } if (c < b) { out.println(-1); continue; } } } else if (b > a) { if (b == 1) { ar[0] = ts.pollLast(); int i = 1; while (i < n) { ar[i] = ts.pollFirst(); i++; } } else { ar[0] = ts.pollLast(); int c = 0; for (int i = 1; i < n; i += 2) { c++; if (ts.isEmpty()) { out.println(-1); continue all; } ar[i] = ts.pollFirst(); if (ts.isEmpty()) { out.println(-1); continue all; } ar[i + 1] = ts.pollLast(); if (i + 1 == n - 1) { out.println(-1); continue all; } if (c == a) { i += 2; while (!ts.isEmpty()) { ar[i] = ts.pollFirst(); i++; } break; } } if (c < a) { out.println(-1); continue; } } } else { throw new Exception(); } for (int i = 0; i < n; i++) out.print(ar[i] + " "); out.println(); } out.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextArrIntSorted(int n) throws IOException { int[] a = new int[n]; Integer[] a1 = new Integer[n]; for (int i = 0; i < n; i++) a1[i] = nextInt(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].intValue(); return a; } public long[] nextArrLongSorted(int n) throws IOException { long[] a = new long[n]; Long[] a1 = new Long[n]; for (int i = 0; i < n; i++) a1[i] = nextLong(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].longValue(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
c3179375142cc7eeec07ad9f66488b5e
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class B{ static final int up = -1, down = 1; public static void main(String[] args) throws IOException{ // br = new BufferedReader(new FileReader(".in")); // out = new PrintWriter(new FileWriter(".out")); // new Thread(null, new (), "fisa balls", 1<<28).start(); int t =readInt(); while(t-->0) { int n =readInt(); int a =readInt(), b=readInt(); a^=b; b^=a; a^=b; if (a+b > n-2 || abs(a-b) > 1) { out.println(-1); continue; } int lp = 1, rp = a+b; // a is min in my code ArrayDeque<Integer> q = new ArrayDeque<Integer>(); if (a == 0 && b == 0) { for (int i = 1; i <= n; i++) out.print(i + " "); out.println(); } else if (a>b) { for (int i = 0; i < a+b; i++) { if (i%2==0)q.add(lp++); else q.add(rp--); } for (int j = a+b+1; j <= n; j++) { if (j%2==0) q.addFirst(j); else q.addLast(j); } for (int x: q) out.print(x + " "); out.println(); } else if (a<b) { for (int i = 0; i < a+b; i++) { if (i%2==1)q.add(lp++); else q.add(rp--); } int min = 0; while(q.size() < n) { if (min%2==0) q.addFirst(min--); else q.addLast(min--); } for (int x: q) out.print(x-min + " "); out.println(); } else { lp = 1; rp = n; for (int i = 0; i < a+b; i++) { if (i%2==0)q.add(lp++); else q.add(rp--); } for (int i = a+b; i < n; i++) { if (i%2==0)q.addFirst(lp++); else q.addLast(rp--); } for (int x: q) out.print(x + " "); out.println(); } } out.close(); } 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{ while (!st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public static int readInt() throws IOException{return Integer.parseInt(read());} public static long readLong() throws IOException{return Long.parseLong(read());} }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
1717e37e9e206e722ef39fa14d5459da
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.*; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; public class pre1{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]){ FastReader obj = new FastReader(); int tc = obj.nextInt(); while(tc--!=0){ int n = obj.nextInt(),a = obj.nextInt(),b = obj.nextInt(); if(abs(a-b)>1 || a+b>n-2) out.println(-1); else{ int arr[] = new int[n]; int h = n,l = 1; if(a>b){ for(int i=1;i<n && a>0;i+=2){ arr[i] = h--; a--; } for(int i=2;i<n && b>0;i+=2){ arr[i] = l++; b--; } for(int i=0;i<n;i++){ if(arr[i]==0) arr[i] = h--; } }else if(a<b){ for(int i=1;i<n && b>0;i+=2){ arr[i] = l++; b--; } for(int i=2;i<n && a>0;i+=2){ arr[i] = h--; a--; } for(int i=0;i<n;i++){ if(arr[i]==0) arr[i] = l++; } }else{ for(int i=1;i<n && a>0;i+=2){ arr[i] = h--; a--; } for(int i=0;i<n && b>0;i+=2){ arr[i] = l++; b--; } for(int i=0;i<n;i++){ if(arr[i]==0) arr[i] = l++; } } for(int i=0;i<n;i++) out.print(arr[i]+" "); out.println(); } } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
415039c37cbf23ccd7f8959bdfc23a68
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static void swap(int[] P, int idx1, int idx2) { int tmp = P[idx1]; P[idx1] = P[idx2]; P[idx2] = tmp; } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int T = Integer.parseInt(in.readLine()); int[] P = new int[100100]; for (int ts=1; ts<=T; ts++) { String[] line = in.readLine().split(" "); int N = Integer.parseInt(line[0]); int A = Integer.parseInt(line[1]); int B = Integer.parseInt(line[2]); if (A + B > N - 2 || Math.abs(A - B) > 1) { out.write("-1\n"); out.flush(); continue; } if (A == 0 || B == 0) { for (int i=1; i<=N; i++) { P[i] = i; } if (A != 0 || B != 0) { if (A == 0) { swap(P, 2, 1); } else { swap(P, N-1, N); } } out.write(P[1] + ""); for (int idx=2; idx<=N; idx++) { out.write(" " + P[idx]); } out.write("\n"); out.flush(); continue; } for (int i=1; i<=N; i++) { P[i] = 0; } int idx = 2; if (A > B) { idx = 3; } int origOrigB = B; int origB = B; while (B > 0) { P[idx] = B; B--; idx += 2; } for (idx=1; idx<=N; idx++) { if (P[idx] != 0) continue; origB++; P[idx] = origB; } if (A >= origOrigB) { for (idx=1; idx<=N; idx++) { if (P[idx] == 1) { break; } } idx++; int great = N; while (idx <= N) { P[idx] = great; great--; idx++; } } out.write(P[1] + ""); for (idx=2; idx<=N; idx++) { out.write(" " + P[idx]); } out.write("\n"); out.flush(); } in.close(); out.close(); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
3c732ee256e352148b4eff1c5a1e58a0
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.lang.*; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.out; import java.util.*; import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { /* 10^(7) = 1s. * ceilVal = (a+b-1) / b */ static final int mod = 1000000007; static final long temp = 998244353; static final long MOD = 1000000007; static final long M = (long)1e9+7; static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair ob) { return (int)(first - ob.first); } } static class Tuple implements Comparable<Tuple> { int first, second,third; public Tuple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public int compareTo(Tuple o) { return (int)(o.third - this.third); } } public static class DSU { int[] parent; int[] rank; //Size of the trees is used as the rank public DSU(int n) { parent = new int[n]; rank = new int[n]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); } public int find(int i) //finding through path compression { return parent[i] < 0 ? i : (parent[i] = find(parent[i])); } public boolean union(int a, int b) //Union Find by Rank { a = find(a); b = find(b); if(a == b) return false; //if they are already connected we exit by returning false. // if a's parent is less than b's parent if(rank[a] < rank[b]) { //then move a under b parent[a] = b; } //else if rank of j's parent is less than i's parent else if(rank[a] > rank[b]) { //then move b under a parent[b] = a; } //if both have the same rank. else { //move a under b (it doesnt matter if its the other way around. parent[b] = a; rank[a] = 1 + rank[a]; } return true; } } static class Reader { 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) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] longReadArray(int n) throws IOException { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long lcm(long a, long b) { return (a / LongGCD(a, b)) * b; } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static long LongLCM(long a, long b) { return (a / LongGCD(a, b)) * b; } //Count the number of coprime's upto N public static long phi(long n) //euler totient/phi function { long ans = n; // for(long i = 2;i*i<=n;i++) // { // if(n%i == 0) // { // while(n%i == 0) n/=i; // ans -= (ans/i); // } // } // // if(n > 1) // { // ans -= (ans/n); // } for(long i = 2;i<=n;i++) { if(isPrime(i)) { ans -= (ans/i); } } return ans; } public static long fastPow(long x, long n) { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long modPow(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return modPow(n, p - 2, p); } // Returns nCr % p using Fermat's little theorem. public static long nCrModP(long n, long r,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)(n)] * modInverse(fac[(int)(r)], p) % p * modInverse(fac[(int)(n - r)], p) % p) % p; } public static long fact(long n) { long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (long i = 1; i <= n; i++) fac[(int)(i)] = fac[(int)(i - 1)] * i; return fac[(int)(n)]; } public static long nCr(long n, long k) { long ans = 1; for(long i = 0;i<k;i++) { ans *= (n-i); ans /= (i+1); } return ans; } //Modular Operations for Addition and Multiplication. public static long perfomMod(long x) { return ((x%M + M)%M); } public static long addMod(long a, long b) { return perfomMod(perfomMod(a)+perfomMod(b)); } public static long subMod(long a, long b) { return perfomMod(perfomMod(a)-perfomMod(b)); } public static long mulMod(long a, long b) { return perfomMod(perfomMod(a)*perfomMod(b)); } public static boolean isPrime(long n) { if(n == 1) { return false; } //check only for sqrt of the number as the divisors //keep repeating so only half of them are required. So,sqrt. for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Integer> SieveList(int n) { boolean prime[] = new boolean[(int)(n+1)]; Arrays.fill(prime, true); List<Integer> l = new ArrayList<>(); 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 p = 2; p<=n; p++) { if (prime[p] == true) { l.add(p); } } return l; } public static int countDivisors(int x) { int c = 0; for(int i = 1;i*i<=x;i++) { if(x%i == 0) { if(x/i != i) { c+=2; } else { c++; } } } return c; } public static long log2(long n) { long ans = (long)(log(n)/log(2)); return ans; } public static boolean isPow2(long n) { return (n != 0 && ((n & (n-1))) == 0); } public static boolean isSq(int x) { long s = (long)Math.round(Math.sqrt(x)); return s*s==x; } /* * * >= <= 0 1 2 3 4 5 6 7 5 5 5 6 6 6 7 7 lower_bound for 6 at index 3 (>=) upper_bound for 6 at index 6(To get six reduce by one) (<=) */ public static int LowerBound(int a[], int x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } public static int UpperBound(long a[], long x) { int l=-1, r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } public static void Sort(int[] a) { List<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void ssort(char[] a) { List<Character> l = new ArrayList<>(); for (char i : a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void main(String[] args) throws Exception { Reader sc = new Reader(); PrintWriter fout = new PrintWriter(System.out); int t = sc.nextInt(); next:while(t-- > 0) { int n = sc.nextInt(), a = sc.nextInt(), b = sc.nextInt(); int x = (int)(n+10); int[] list = new int[x]; if(a + b > n - 2 || abs(a - b) > 1) { fout.println(-1); continue next; } if(a == b && a == 0) { for(int i = 1;i<=n;i++) fout.print(i + " "); continue next; } else if(a > b) { int right = n; for(int i = 1;i<=n;i++) list[i] = right--; for(int i = 2;i<n && a-- > 0; i += 2) { int tx = list[i]; list[i] = list[i-1]; list[i-1] = tx; } } else if(a < b) { for(int i = 1;i<=n;i++) list[i] = i; for(int i = 2;i<n && b-- > 0; i += 2) { int tx = list[i]; list[i] = list[i-1]; list[i-1] = tx; } } else { for(int i = 1;i<=n;i++) list[i] = i; for(int i = 2;i<n && b-- > 0;i+= 2) { int tx = list[i]; list[i] = list[i+1]; list[i+1] = tx; } } for(int i = 1;i<=n;i++) fout.print(list[i] + " "); fout.println(); } fout.close(); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
3139854a26daa06013832916c782b94f
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Pentagram { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int tc = sc.nextInt(); while(tc-->0){ int n = sc.nextInt(), a = sc.nextInt(), b = sc.nextInt(); int[] arr = new int[n]; for(int i = 1; i<=n; i++)arr[i - 1] = i; if((Math.abs(a - b) > 1) || (n == 2 && (a > 0 || b > 0)) || (a + b > n - 2)){ pw.println(-1); }else if(a == b){ ArrayList<Integer> ans = new ArrayList<>(); ans.add(1); int i = 2, j = n; int idx = 1; int temp = 0; while(temp < a){ ans.add(j); j--; ans.add(i); i++; temp++; } //System.out.println(Arrays.toString(ans)); for(int k = i; k<=j;k++){ ans.add(k); } for(int x: ans)pw.print(x + " "); pw.println(); }else if(a > b){ int cnta = 0; ArrayList<Integer> ans = new ArrayList<>(); ans.add(1); int i = 2, j = n; int idx = 1; while(cnta < a - 1){ ans.add(j); j--; ans.add(i); i++; cnta++; } for(int k = j; k>=i; k--)ans.add(k); for(int x: ans)pw.print(x + " "); pw.println(); }else{ ArrayList<Integer> ans = new ArrayList<>(); ans.add(n); int i = 1, j = n - 1; int cntb = 0; while(cntb < b - 1){ ans.add(i); i++; ans.add(j); j--; cntb++; } for(int k = i; k<=j; k++)ans.add(k); for(int x: ans)pw.print(x + " "); pw.println(); } } pw.flush(); /* if(a >= b){ for(int i = 1; i<n; i+=2){ int temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } boolean f = true; int cnta = 0, cntb = 0; for(int i = 1; i<n-1; i++){ if(arr[i] > arr[i - 1] && arr[i] > arr[i + 1])cnta++; else if(arr[i] < arr[i - 1] && arr[i] < arr[i + 1])cntb++; } if(a == cnta && b == cntb){ for(int x: arr)pw.print(x + " "); pw.println(); }else pw.println(-1); } */ } static class Pair implements Comparable<Pair>{ long x; long y; public Pair(long x, long y){ this.x = x; this.y = y; } public int compareTo(Pair p){ if(x > p.x)return 1; if(x < p.x)return -1; if(y > p.y) return -1; if(y < p.y) return 1; return 0; } public String toString(){ return "(" + x + "," + y + ")"; } } 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(); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
9e7e07ddd582f46905531286b519fe1f
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; public class A { static boolean[] isPrime; public static void main(String[] args) { FastScanner sc=new FastScanner(); PrintWriter pw=new PrintWriter(System.out); int ts=sc.nextInt(); while(ts-- > 0){ int n=sc.nextInt(); int a=sc.nextInt(); int b=sc.nextInt(); ArrayList<Integer> li=new ArrayList<>(); if(a+b>n-2 || Math.abs(a-b) > 1){ pw.print(-1); } else{ int l=1,r=n; if(a==b){ int h=0; li.add(l); l++; while(h<a){ li.add(r); r--; li.add(l); l++; h++; } for(int i=l;i<=r;i++){ li.add(i); } } else if(a>b){ int h=0; li.add(l); l++; while(h<a-1){ li.add(r); r--; li.add(l); l++; h++; } for(int i=r;i>=l;i--){ li.add(i); } } else{ int v=0; li.add(r); r--; while(v<b-1){ li.add(l); l++; li.add(r); r--; v++; } for(int i=l;i<=r;i++){ li.add(i); } } } n=li.size(); for(int i=0;i<n;i++){ if(i==0){ pw.print(li.get(i)); } else{ pw.print(" "+li.get(i)); } } pw.println(); } pw.flush(); } public static long npr(int n, int r) { long ans = 1; for(int i= 0 ;i<r; i++) { ans*= (n-i); } return ans; } public static double ncr(int n, int r) { double ans = 1; for(int i= 0 ;i<r; i++) { ans*= (n-i); } for(int i= 0 ;i<r; i++) { ans/=(i+1); } return ans; } public static void fillPrime() { int n = 1000007; Arrays.fill(isPrime, true); isPrime[0] = isPrime[1] = false; for (int i = 2; i * i < n; i++) { if (isPrime[i]) { for (int j = i * i; j < n; j += i) { isPrime[j] = false; } } } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (st == null || !st.hasMoreTokens()) { try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } 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
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
d1c9daa6838acc26547dd20340e99bad
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i=1;i<=t;i++) { int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int l = 1; int r=n; int[] ans=new int[n]; if(a+b > n-2 || Math.abs(a-b)>1) System.out.println(-1); else { if(a==b) { int q=0; int w =0; int k=1; ans[0] =l; l++; while(q<a) { ans[k]=r; k++; r--; ans[k] =l; k++; l++; q++; } for(int j=l;j<=r;j++) { ans[k] =j; k++; } } else if(a>b) { int q=0; int w =0; int k=1; ans[0] =l; l++; while(q<a-1) { ans[k]=r; k++; r--; ans[k] =l; k++; l++; q++; } for(int j=r;j>=l;j--) { ans[k]=j; k++; } } else { int q=0; int w =0; int k=1; ans[0] =r; r--; while(w<b-1) { ans[k]=l; k++; l++; ans[k] =r; k++; r--; w++; } for(int j=l;j<=r;j++) { ans[k] =j; k++; } } for(int j=0;j<n;j++) { System.out.print(ans[j]+" "); } } System.out.println(" "); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
46f17a290d2cce9cf8d8eefc8bf053cb
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); int a = sc.nextInt(); // maxima int b = sc.nextInt(); // minima if(a + b > n - 2 || Math.abs(a-b) > 1){ System.out.println(-1); continue; } if(a + b == 0){ for(int i = 1; i <= n; i++) System.out.print(i + " "); System.out.println(); continue; } int[] ans = new int[n]; int l = 1; int r = n; int flag = 0; int ptr = 1; int origA = a; int origB = b; if(a >= b){ while(a > 0 || b > 0){ if(flag == 0){ ans[ptr] = r; r--; a--; } else { ans[ptr] = l; l++; b--; } ptr++; flag ^= 1; } if(origA > origB){ while(ptr < n){ ans[ptr++] = r; r--; } ans[0] = r; } else { while(ptr < n){ ans[ptr++] = l; l++; } ans[0] = l; } } else { while(a > 0 || b > 0){ if(flag == 0){ ans[ptr] = l; l++; b--; } else { ans[ptr] = r; r--; a--; } ptr++; flag ^= 1; } while(ptr < n){ ans[ptr++] = l; l++; } ans[0] = l; } for(int i : ans){ System.out.print(i + " "); } System.out.println(); } } 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; } static boolean isPS(long x){ long sr = (long) Math.sqrt(x); return ((sr * sr) == x); } static long getNextPS(long x){ if(isPS(x)) return x; long sq = (long) Math.sqrt(x); sq++; return sq * sq; } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
ba647cae8df1be37822dc5e2d10b41db
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; import java.io.*; public class practice { public static void solve() { Reader sc = new Reader(); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); if(a + b > n - 2 || Math.abs(a - b) > 1) out.println(-1); else { if(a == 0 && b == 0) { for(int i = 1;i <= n;i++) out.print(i + " "); out.println(); } else if(a == 1 && b == 0) { for(int i = 1;i <= n - 2;i++) out.print(i + " "); out.println(n + " " + (n - 1)); } else if(a == 0 && b == 1) { out.print("2 1" + " "); for(int i = 3;i <= n;i++) out.print(i + " "); out.println(); } else { int x; if(a > b) { x = a + b + 1; for(int i = 1;i <= n - x;i++) out.print(i + " "); for(int i = n - x + 1;i <= n;i += 2) out.print((i + 1) + " " + i + " "); out.println(); } else if(b > a) { x = a + b + 1; for(int i = 1;i <= x;i += 2) out.print((i + 1) + " " + i + " "); for(int i = x + 1;i <= n;i++) out.print(i + " "); out.println(); } else { x = a + b; for(int i = 1;i <= x;i += 2) out.print((i + 1) + " " + i + " "); for(int i = x + 1;i <= n - 2;i++) out.print(i + " "); out.println(n + " " + (n - 1)); } } } } out.flush(); } public static void main(String[] args) throws IOException { solve(); } static int[] sort(int[] arr,int n) { 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); return arr; } 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 { if(st.hasMoreTokens()) str = st.nextToken("\n"); else str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
565817f7011ca2298d9a1247789c32f6
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; public class CSESProblemSets { public static void main (String[] args) { int T = in.nextInt(); for(int testCase = 0; testCase < T; testCase ++){ solve(); out.flush(); } out.close(); } static void solve(){ int N = in.nextInt(), a = in.nextInt(), b = in.nextInt(); if(Math.abs(a - b) > 1 || (a + b) > N - 2) { out.println(-1); return; } int left = 1, right = N, back = 0; StringBuilder x = new StringBuilder(); if(a==b){ int h = 0 ; x.append(left++ + " "); while (h<a){ x.append(right-- + " "); x.append(left++ + " "); h++; } for(int i=left; i <= right ;i++) x.append(i + " "); } else if(a>b){ int h = 0 ; x.append(left++ + " "); while (h<a-1){ x.append(right-- + " "); x.append(left++ + " "); h++; } for(int i=right; i >= left ;i--) x.append(i + " "); } else{ int h = 0 ; x.append(right + " "); right--; while (h<b-1){ x.append(left + " "); left++; x.append(right + " "); right--; h++; } for(int i=left; i <=right ;i++) x.append(i).append(" "); } out.println(x); } 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(new FileWriter(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()); } public String readLine() throws Exception { return r.readLine(); } public long[] readArrayLong(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public Integer[] readArrayI(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public int[] readArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public int[]prefixSum(int N, int[]a){ int[]nw = new int[N + 1]; nw[0] = 0; for (int i = 0; i < N; i ++) { nw[i + 1] = nw[i] + a[i]; } return nw; } public int[][] prefixSum(int N, int[][]grid){ int[][]pfx = new int[grid.length][grid.length]; for (int i = 1; i < N + 1; i++) { for (int j = 1; j < N + 1; j++) { pfx[i][j] = grid[i][j] + pfx[i-1][j] + pfx[i][j-1] - pfx[i-1][j-1]; } } return pfx; } public int prefixSum2D(int x1, int y1, int x2, int y2, int[][]pfx) { return pfx[x2][y2] - pfx[x1-1][y2] - pfx[x2][y1-1] + pfx[x1-1][y1-1]; } } static final Kattio in = new Kattio(); static final PrintWriter out = new PrintWriter(System.out); static class Pair implements Comparable<Pair> { int x, y; Pair (int x, int y) { this.x = x; this.y = y; } @Override public int compareTo (Pair other) { return Integer.compare(this.x, other.x); } public String toString() { return x + " " + y;} } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
56f8637b2731922c3d33ab1059904ba4
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; public class BuildThePermutation { static void display(Vector<Integer> x){ PrintWriter pw = new PrintWriter(System.out); for (int i=0; i<x.size() ;i++) pw.print(x.elementAt(i)+" "); pw.println(); pw.flush(); } 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() , a = sc.nextInt() , b = sc.nextInt(); int left = 1, right = n , back = 0; Vector<Integer> x = new Vector<>(n); if(a+b > n-2 || Math.abs(a-b)>1) System.out.println(-1); else{ if(a==b){ int h = 0 ; x.add(left++); while (h<a){ x.add(right--); x.add(left++); h++; } for(int i=left; i <= right ;i++) x.add(i); } else if(a>b){ int h = 0 ; x.add(left++); while (h<a-1){ x.add(right--); x.add(left++ ); h++; } for(int i=right; i >= left ;i--) x.add(i); } else{ int h = 0 ; x.add(right); right--; while (h<b-1){ x.add(left); left++; x.add(right); right--; h++; } for(int i=left; i <=right ;i++) x.add(i); } display(x); } } } 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() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] nextIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
4384126297a1dd2d38ee7bc2b2080e74
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; public class BuildThePermutation { static void display(Vector<Integer> x){ for (int i=0; i<x.size() ;i++) System.out.print(x.elementAt(i)+" "); System.out.println(); } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt() , a = sc.nextInt() , b = sc.nextInt(); int left = 1, right = n , back = 0; Vector<Integer> x = new Vector<>(n); if(a+b > n-2 || Math.abs(a-b)>1) System.out.println(-1); else{ if(a==b){ int h = 0 ; x.add(left++); while (h<a){ x.add(right--); x.add(left++); h++; } for(int i=left; i <= right ;i++) x.add(i); } else if(a>b){ int h = 0 ; x.add(left++); while (h<a-1){ x.add(right--); x.add(left++ ); h++; } for(int i=right; i >= left ;i--) x.add(i); } else{ int h = 0 ; x.add(right); right--; while (h<b-1){ x.add(left); left++; x.add(right); right--; h++; } for(int i=left; i <=right ;i++) x.add(i); } display(x); } } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
99a5d7c716a7f6a062ef58cbdc54bc30
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); if(Math.abs(a-b)>1){ pw.println(-1); continue; } if(n-2<a+b){ pw.println(-1); continue; } StringBuilder sb= new StringBuilder(); int start=1; int end =n; if(a==b&&b==0){ for(int i =0;i<n;i++){ sb.append((i+1)+" "); } } else if(a==b){ while(a>0){ sb.append(start+" "); // 1 6 2 5 3 4 // 1 6 2 5 4 3 start++; sb.append(end+" "); end--; a--; } while(start<=end){ sb.append(start+" "); start++; } // while(start<end){ // sb.append(start+" "); // sb.append(end+" "); // start++; // end--; // } // if(start==end){ // sb.append(start); // } } else if(a>b){ // we want tha maxima to be greater while(a>0){ sb.append(start+" "); // 1 6 2 5 3 4 // 1 6 2 5 4 3 start++; sb.append(end+" "); end--; a--; } while(end>=start){ sb.append(end+" "); end--; } // while(start<Math.ceil((n*1.0)/(2*1.0))){ // sb.append(start+" "); // start++; // } }else{ while(b>0){ sb.append(end+" "); // 1 6 2 5 end--; sb.append(start+" "); start++; b--; } while(start<=end){ sb.append(start+" "); start++; } // while(end>Math.ceil((n*1.0)/(2*1.0))){ // sb.append(end+" "); // end--; // } } pw.println(sb.toString()); } pw.close(); } 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(); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
357ac588cbd480f74a3c5a8cecfc10b2
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; import java.util.concurrent.LinkedTransferQueue; //import javax.swing.plaf.basic.BasicInternalFrameTitlePane.SystemMenuBar; import java.lang.*; import java.io.*; public class Main { 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; } } /*static int LEN = 10000000; int lp[]=new int[LEN+1]; List<Inter> public void sieve() { for (int i=2; i <= N; ++i) { if (lp[i] == 0) { lp[i] = i; pr.push_back(i); } for (int j=0; j < (int)pr.size() && pr[j] <= lp[i] && i*pr[j] <= N; ++j) { lp[i * pr[j]] = pr[j]; } } }*/ public static long gcd(long a,long b) {if(a==0)return b; return gcd(b%a,a);} public static int gcd(int a,int b) {if(a==0)return b; return gcd(b%a,a);}; static int power(int x, int y){ if (y == 0) return 1; else if (y % 2 == 0) return power(x, y / 2) * power(x, y / 2); else return x * power(x, y / 2) * power(x, y / 2); } static long power(long x , long y) { if (y == 0) return 1; else if (y % 2 == 0) return power(x, y / 2) * power(x, y / 2); else return x * power(x, y / 2) * power(x, y / 2); } static int rank[]; static int parent[]; static int findpar(int x) { if(x==parent[x]) return x; return parent[x]=findpar(parent[x]); } static void union(int u,int v) { int x=findpar(u); int y=findpar(v); if(x==y) return; if(rank[x]>rank[y]) { parent[y]=x; } else if(rank[y]>rank[x]) { parent[x]=y; } else { parent[y]=x; rank[x]++; } } static boolean dfs(int i,boolean visited[],List<List<Integer>>adj) { visited[i]=true; if(adj.get(i).size()!=2) return false; for(int it:adj.get(i)) { if(!visited[it]) { if(!dfs(it,visited,adj)) return false; } } return true; } public static void main (String[] args) throws java.lang.Exception { long mod=1000000007; FastReader in=new FastReader(); if(in.hasNext()){ if(in.hasNext()){ BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); int test=in.nextInt(); while(test-->0) { int n=in.nextInt(); int a=in.nextInt(); int b=in.nextInt(); int arr[]=new int[n]; int t=n; if((a+b+2)>n||Math.abs(a-b)>1) System.out.println(-1); else { if(a==0&&b==0) { for(int i=1;i<=n;i++) System.out.print(i+" "); System.out.println(); } else if(a>b) { int j=1; while(j<n-1&&a>0) { arr[j]=t--; j+=2; a--; } for(int i=0;i<n;i++) { if(arr[i]==0) arr[i]=t--; } for(int i=0;i<n;i++) System.out.print(arr[i]+" "); System.out.println(); } else if(b>a) { int c=1; int j=1; while(j<n-1&&b>0) { arr[j]=c++; j+=2; b--; } for(int i=0;i<n;i++) { if(arr[i]==0) arr[i]=c++; } for(int i=0;i<n;i++) System.out.print(arr[i]+" "); System.out.println(); } else { arr[n-1]=n; t=n-1; int j=1; while(j<n-1&&a>0) { arr[j]=t--; j+=2; a--; } for(int i=0;i<n;i++) { if(arr[i]==0) arr[i]=t--; } for(int i=0;i<n;i++) System.out.print(arr[i]+" "); System.out.println(); } } } } } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
c296b0c05495b85126c389af48a0de93
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) throws IOException { int n, counter, a,b, m, sum, p1, p2, t, k; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writerObj = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine(), " "); t = Integer.parseInt(st.nextToken()); for (int i = 0; i < t; i++) { st = new StringTokenizer(br.readLine(), " "); n = Integer.parseInt(st.nextToken()); a = Integer.parseInt(st.nextToken()); b = Integer.parseInt(st.nextToken()); int[] numbers = new int[n]; for (int j = 0; j < n; j++) { numbers[j] = j + 1; } if (Math.abs(a - b) > 1 || a + b > n - 2 ) { System.out.println(-1); continue; } if (a == 0 && b == 0) { } else if (a < b) { for (int j = 0; j < b; j++) { numbers[1 + j * 2] = j + 1; } int max = n - a; for (int j = 0; j < a; j++) { numbers[2 + j * 2 ] = max + 1; max++; } numbers[0] = n - a; for (int j = b; j < n - a; j++) { numbers[a + j] = j; } } else if (a == b) { for (int j = 0; j < b - 1; j++) { numbers[2 + j * 2] = j + 1; } int max = n - a + 1; for (int j = 0; j < a; j++) { numbers[1 + j * 2] = max; max++; } numbers[0] = n - a; int lim = b; for (int j = a + b; j < n; j++) { numbers[j] = lim++; } } else { for (int j = 0; j < b; j++) { numbers[2 + j * 2] = j + 1; } int max = n - a + 1; for (int j = 0; j < a; j++) { numbers[1 + j * 2] = max; max++; } numbers[0] = n - a; int lim = n - a - 1; for (int j = a + b + 1; j < n; j++) { numbers[j] = lim--; } } for (int j = 0; j < n; j++) { System.out.print(numbers[j] + " "); } System.out.println(); } writerObj.flush(); writerObj.close(); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
dced57c5b11f609ddf0503a5e3ec0282
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int test = Integer.parseInt(br.readLine()); String[] input = new String[test]; int m = 0; while(test-- > 0){ input[m++] = br.readLine(); } for(String str: input){ solution(str); } } private static void solution(String inputStr){ String line = inputStr; String[] input = line.split(" "); int n = Integer.parseInt(input[0]); int a = Integer.parseInt(input[1]); int b = Integer.parseInt(input[2]); if(Math.abs(a-b)>1){ System.out.println(-1); return; } StringBuilder sb = new StringBuilder(); int left = 1, right = n; if(a==b){ sb.append(right--).append(" "); while(b>0 && left<=right){ sb.append(left++).append(" ").append(right--).append(" "); a--;b--; } if(left > right) { System.out.println(-1);return; } for(int i=right;i>=left;i--){ sb.append(i).append(" "); } System.out.println(sb.toString().trim()); }else if(a > b) { if(n < 2*a+1){ System.out.println(-1);return; } sb.append(1).append(" "); int first = n; int second = n-a; for(int i=1;i<=a;i++){ sb.append(first--).append(" ").append(second--).append(" "); } for(int i=second;i>1;i--){ sb.append(i).append(" "); } System.out.println(sb.toString().trim()); }else { if(n < 2*b+1){ System.out.println(-1);return; } sb.append(n).append(" "); int first = 1; int second = b+1; for(int i=1;i<=b;i++){ sb.append(first++).append(" ").append(second++).append(" "); } for(int i=second;i<n;i++){ sb.append(i).append(" "); } System.out.println(sb.toString().trim()); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
16bb253051bff9176b4d5acee0817248
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; public class cp { static PrintWriter w = new PrintWriter(System.out); static FastScanner s = new FastScanner(); static int mod = 1000000007; static class Edge { int src; int wt; int nbr; Edge(int src, int nbr, int et) { this.src = src; this.wt = et; this.nbr = nbr; } } class EdgeComparator implements Comparator<Edge> { @Override //return samllest elemnt on polling public int compare(Edge s1, Edge s2) { if (s1.wt < s2.wt) { return -1; } else if (s1.wt > s2.wt) { return 1; } return 0; } } static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } static void prime_till_n(boolean[] prime) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. for (int p = 2; p * p < prime.length; 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 < prime.length; i += p) { prime[i] = false; } } } // int l = 1; // for (int i = 2; i <= n; i++) { // if (prime[i]) { // w.print(i+","); // arr[i] = l; // l++; // } // } //Time complexit Nlog(log(N)) } static int noofdivisors(int n) { //it counts no of divisors of every number upto number n int arr[] = new int[n + 1]; for (int i = 1; i <= (n); i++) { for (int j = i; j <= (n); j = j + i) { arr[j]++; } } return arr[0]; } static char[] reverse(char arr[]) { char[] b = new char[arr.length]; int j = arr.length; for (int i = 0; i < arr.length; i++) { b[j - 1] = arr[i]; j = j - 1; } return b; } static long factorial(int n) { if (n == 0) { return 1; } long su = 1; for (int i = 1; i <= n; i++) { su *= (long) i; } return su; } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } long[] readArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } static class Vertex { int x; int y; int wt; public Vertex(int x, int y) { this.x = x; this.y = y; } public Vertex(int x, int y, int wt) { this.x = x; this.y = y; this.wt = wt; } } public static long power(long x, int n) { if (n == 0) { return 1l; } long pow = power(x, n / 2) % mod; if ((n & 1) == 1) // if `y` is odd { return ((((x % mod) * (pow % mod)) % mod) * (pow % mod)) % mod; } // otherwise, `y` is even return ((pow % mod) * (pow % mod)) % mod; } public static void main(String[] args) { { int t = s.nextInt(); // int t = 1; while (t-- > 0) { solve(); } w.close(); } } public static void solve() { int n = s.nextInt(); int x = s.nextInt(); int y = s.nextInt();int arr[]= new int[n]; TreeSet<Integer> set = new TreeSet<>(); if(x==0 && y==0) { for(int i=1;i<=n;i++)w.print(i+" "); w.println();return; } if(Math.abs(x-y)>1 || n==2 || x+y>n-2) { w.println(-1);return; } for(int i=1;i<=n;i++) set.add(i); if(x>y) { int k=n; for(int i=1;i<n-1&& x-->0;i+=2){ arr[i]=k;set.remove(k);k--; } for(int i=0;i<n;i++) { if(arr[i]==0) { int p = set.last();set.remove(p); arr[i]=p; } } } else if(x<y) { int k=1; for(int i=1;i<n-1&& y-->0;i+=2){ arr[i]=k;set.remove(k);k++; } for(int i=0;i<n;i++) { if(arr[i]==0) { int p = set.first();set.remove(p); arr[i]=p; } } } else { int k=1; for(int i=1;i<n-1&& y-->0;i+=2){ arr[i]=k;set.remove(k);k++; } for(int i=0;i<n;i++) { if(arr[i]==0) { int p = set.first();set.remove(p); arr[i]=p; } } int temp = arr[n-1]; arr[n-1]=arr[n-2]; arr[n-2]=temp; } for(int i:arr) w.print(i+" "); w.println(); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
3021bc4691e421e575e9b33c541600c4
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
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 x1608B { public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); if(abs(A-B) >= 2 || A+B > N-2 || max(A, B) > (N-1)/2) { sb.append("-1\n"); continue; } int[] arr = new int[N]; if(A < B) { //min first arr[0] = N; int val = 1; for(int i=1; i < N; i+=2) { if(B == 0) break; arr[i] = val++; B--; } val = N-1; for(int i=2; i < N; i+=2) { if(A == 0) break; arr[i] = val--; A--; } TreeSet<Integer> active = trim(N, arr); maxLast(N, arr, active); } else { boolean equal = A == B; //max first arr[0] = 1; int val = N; for(int i=1; i < N; i+=2) { if(A == 0) break; arr[i] = val--; A--; } val = 2; for(int i=2; i < N; i+=2) { if(B == 0) break; arr[i] = val++; B--; } TreeSet<Integer> active = trim(N, arr); //maxLast(N, arr, active); if(equal) maxLast(N, arr, active); else minLast(N, arr, active); } for(int x: arr) sb.append(x+" "); sb.append("\n"); } System.out.print(sb); } public static TreeSet<Integer> trim(int N, int[] arr) { TreeSet<Integer> set = new TreeSet<Integer>(); for(int i=1; i <= N; i++) set.add(i); for(int x: arr) if(x > 0) set.remove(x); return set; } public static void minLast(int N, int[] arr, TreeSet<Integer> set) { for(int i=0; i < N; i++) if(arr[i] == 0) { arr[i] = set.last(); set.remove(arr[i]); } } public static void maxLast(int N, int[] arr, TreeSet<Integer> set) { for(int i=0; i < N; i++) if(arr[i] == 0) { arr[i] = set.first(); set.remove(arr[i]); } } } /* abs(A-B) <= 1 max = mx min = mn .mx(mn)mx(mn) .mn(mx)mn(mx)mn. .mn.mn.mn. .m.m.. */
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
2118ff6c5728f388704e1bc1c922bbee
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
//package CodeForces.RoadMap.diff1200; import java.util.*; /** * @author SyedAli * @createdAt 12-03-2022, Saturday, 17:50 */ public class BuildPermutation { private static Scanner s = new Scanner(System.in); private static void solve() { int n = s.nextInt(); int a = s.nextInt(); int b = s.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = (i + 1); } if (Math.abs(a - b) > 1 || (a + b) > n - 2) System.out.println("-1"); else { if (a == b) { for (int i = 1; a > 0; i = i + 2) { int temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; a--; } } else if (a > b) { for (int i = n - 1; a > 0; i = i - 2) { int temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; a--; } } else { for (int i = 0; b > 0; i = i + 2) { int temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; b--; } } for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println(); } } public static void main(String[] args) { int t = s.nextInt(); while (t-- > 0) { solve(); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
537346c5cd56247fc886c471ebd603fb
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; public class BuildPermutation { public static void main(String[] args) throws IOException { FastIO fr = new FastIO(); PrintWriter pr = new PrintWriter(new OutputStreamWriter(System.out)); int t = fr.nextInt(); while (t-- > 0) { int n = fr.nextInt(), a = fr.nextInt(), b = fr.nextInt(); if (a + b > n - 2 ) { pr.println(-1); continue; } if (Math.abs(a - b) > 1) { pr.println(-1); continue; } // casework for each kind of sequence int[] out = new int[n]; int s, e; if (a == b) { s = 1; e = n - 1; out[0] = n; int cur = 1; for (int i = 0; i < a; i++) { out[cur] = s; out[cur + 1] = e; s++; e--; cur += 2; } while (e >= s) { out[cur] = e; e--; cur++; } } else if (a > b) { s = 1; e = n; int cur = 0; for (int i = 0; i < a; i++) { out[cur] = s; out[cur + 1] = e; s++; e--; cur += 2; } while (e >= s && cur < n) { out[cur] = e; e--; cur++; } } else { s = 1; e = n; int cur = 0; for (int i = 0; i < b; i++) { out[cur] = e; out[cur + 1] = s; s++; e--; cur += 2; } while (s <= e && cur < n) { out[cur] = s; s++; cur++; } } String ans = Arrays.toString(out).replaceAll(",", ""); pr.println(ans.substring(1, ans.length()-1)); } pr.close(); } static class Pair { int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static int toInt(String s) { return Integer.parseInt(s); } // MERGE SORT IMPLEMENTATION void sort(int[] arr, int l, int r) { if (l < r) { int m = l + (r - l) / 2; sort(arr, l, m); sort(arr, m + 1, r); // call merge merge(arr, l, m, r); } } void merge(int[] arr, int l, int m, int r) { // find sizes int len1 = m - l + 1; int len2 = r - m; int[] L = new int[len1]; int[] R = new int[len2]; // push to copies for (int i = 0; i < L.length; i++) L[i] = arr[l + i]; for (int i = 0; i < R.length; i++) { R[i] = arr[m + 1 + i]; } // fill in new array int i = 0, j = 0; int k = l; while (i < len1 && j < len2) { if (L[i] < R[i]) { arr[k] = L[i]; i++; } else { arr[k] = R[i]; j++; } k++; } // add remaining elements while (i < len1) { arr[k] = L[i]; i++; k++; } while (j < len2) { arr[k] = R[j]; j++; k++; } } static class FastIO extends PrintWriter { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar, numChars; // standard input public FastIO() { this(System.in, System.out); } public FastIO(InputStream i, OutputStream o) { super(o); stream = i; } // file input public FastIO(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } // to read in entire lines, replace c <= ' ' // with a function that checks whether c is a line break public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public int nextInt() { // nextLong() would be implemented similarly int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
c18211a8ab67cd80532284a8717e392d
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import static java.lang.Math.*; // Sachin_2961 submission // public class CodeforcesA { public void solve() { int n = fs.nInt(), a = fs.nInt(), b = fs.nInt(); if( a+b+2 > n || abs(a-b)>1){ out.println("-1"); return; } int l = 1,r = n; if( a > b ){ for(int i=1;i<=a;i++){ out.print(l+" "+r+" "); l++; r--; } for(int i=r;i>=l;i--){ out.print(i+" "); } }else if(a < b ){ for(int i=1;i<=b;i++){ out.print(r+" "+l+" "); r--;l++; } for(int i=l;i<=r;i++){ out.print(i+" "); } }else{ for(int i=1;i<=a;i++){ out.print(r+" "+l+" "); r--;l++; } for(int i=r;i>=l;i--){ out.print(i+" "); } } out.println(); } static boolean multipleTestCase = true; static FastScanner fs; static PrintWriter out; public void run(){ fs = new FastScanner(); out = new PrintWriter(System.out); int tc = (multipleTestCase)?fs.nInt():1; while (tc-->0)solve(); out.flush(); out.close(); } public static void main(String[]args){ try{ new CodeforcesA().run(); }catch (Exception e){ e.printStackTrace(); } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String n() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String Line() { String str = ""; try { str = br.readLine(); }catch (IOException e) { e.printStackTrace(); } return str; } int nInt() {return Integer.parseInt(n()); } long nLong() {return Long.parseLong(n());} double nDouble(){return Double.parseDouble(n());} int[]aI(int n){ int[]ar = new int[n]; for(int i=0;i<n;i++) ar[i] = nInt(); return ar; } } public static void sort(int[] arr){ ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } public static void sort(long[] arr){ ArrayList<Long> ls = new ArrayList<>(); for(long x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
f389b88896e974211e2cdd57edd6c332
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.math.*; import java.net.Inet4Address; import java.util.*; public class sampleEditor_codeforces { static int mod=1000000007; static int mod2=1000003; static Scanner sc = new Scanner(System.in); static class Pair implements Comparable<Pair>{ int x; int y; public Pair(int px , int py){ x = px; y = py; } @Override public int compareTo(Pair pair){ if (x > pair.x) return 1; else if (x == pair.x) return 0; else return -1; } } public static void loop(int [] a,int l,int r){ for(int i=l;i<r;i++){ a[i]=sc.nextInt(); } } public static long binaryToDecimal(String binary){ int n=binary.length(); int i=n-1; long sum=0; long two=1; while(i>=0){ sum+=two*(binary.charAt(i)-'0')%mod2; two*=2; i--; } return sum; } public static boolean isSorted(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { if (arr[i] > arr[i + 1]) { return false; } } return true; } public static void reverse(int[] arr) { int l = 0; int r = arr.length - 1; while (l < r) { int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; l++; r--; } } public static void reverse(int[] arr,int l,int r) { while (l < r) { int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; l++; r--; } } public static boolean isPalindrome(int n,int [] a,int x1){ int [] b=new int[n]; int m=0; for(int i=0;i<n;i++){ if(a[i]!=x1){ b[m++]=a[i]; } } for(int i=0;i<m;i++){ if(b[i]!=b[m-1-i]){ return false; } } return true; } public static void solve(int n,int a,int b) { StringBuilder sb=new StringBuilder(""); int l=1; int r=n; if(Math.abs(a-b)>1 || (a+b)>n-2) System.out.println(-1); else{ if(a>b){ for(int i=0;i<a;i++){ sb.append(l++).append(" ").append(r--).append(" "); } for(int i=r;i>=l;i--){ sb.append(i).append(" "); } sb.append("\n"); System.out.print(sb); } else if(a<b){ for(int i=0;i<b;i++){ sb.append(r--).append(" ").append(l++).append(" "); } for(int i=l;i<=r;i++){ sb.append(i).append(" "); } sb.append("\n"); System.out.print(sb); } else{ for(int i=0;i<a;i++){ sb.append(r--).append(" ").append(l++).append(" "); } for(int i=r;i>=l;i--){ sb.append(i).append(" "); } sb.append("\n"); System.out.print(sb); } } } public static void main(String args[]) { // Scanner sc = new Scanner(System.in); int smallestNum=10000; int t = sc.nextInt(); while (t-- > 0) { int n=sc.nextInt(); int a=sc.nextInt(); int b=sc.nextInt(); solve(n,a,b); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
e8f2ebd575f00fd13ac852856ff77593
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.Scanner; import java.lang.Math; public class BuildthePermutation { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int j = 0; j<t; j++) { int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int k = 0; int result[] = new int[n]; result[0] = 2; result[1] = 1; int m = 1; int temp = 0; if((a!=0 || b!=0)&&n>2) { if(Math.abs(a-b)<=1) { if(a>b) for(int i = 3; i<n+1; i++) { if(a!=0 && k == 0) { temp = result[m]; result[m] = i; result[++m] = temp; a--; k = 1; } else if(b!=0 && k == 1) { result[++m] = i; b--; k = 0; } else while(i<n+1) { temp = result[m]; result[m] = i++; result[++m] = temp; } } else if(a==b) for(int i = 3; i<n+1; i++) { if(a!=0 && k == 0) { temp = result[m]; result[m] = i; result[++m] = temp; a--; k = 1; } else if(b!=0 && k == 1) { result[++m] = i; b--; k = 0; } else { while(++m<n) result[m] = m+1; break; } } else for(int i = 3; i<n+1; i++) { if(b!=0 && k == 0) { result[++m] = i; b--; k = 1; } else if(a!=0 && k == 1) { temp = result[m]; result[m] = i; result[++m] = temp; a--; k = 0; } else { while(++m<n) result[m] = m+1; break; } } if(a==0 && b==0) { for(int i = 0; i<n; i++) System.out.print(result[i]+ " "); System.out.println(); } else System.out.println(-1); } else System.out.println(-1); } else if(a==0 && b==0 && n>2) { for(int i = 1; i<n+1; i++) System.out.print(i+ " "); System.out.println(); } else { if(a == 0 && b==0 && n==2) System.out.println("1 2"); else System.out.println(-1); } } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
877f84891ca79bacf28a884981a6f06f
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; import java.util.stream.Stream; public class Program { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws NumberFormatException, IOException { int cases = Integer.parseInt(reader.readLine()); int mod = 998244353; while(cases-- > 0) { String[] firstLine = reader.readLine().split(" "); int n = Integer.parseInt(firstLine[0]); int a = Integer.parseInt(firstLine[1]); int b = Integer.parseInt(firstLine[2]); if(Math.abs(a-b) > 1 || a+b > n-2 ) { printNumber(-1); continue; } List<Integer> list = new ArrayList<>(); if(a==b) { int k = a; list.add(1); int ele = 3; while(k-->0) { list.add(ele); list.add(ele-1); ele+=2; } int end = 2; if(list.size() >= 2) { end = list.get(list.size()-2); end++; } while(end<=n) { list.add(end); end++; } }else if(a>b) { int k = a-1; int ele = 3; list.add(1); while(k-->0) { list.add(ele); list.add(ele-1); ele+=2; } int start = n; int end = 1; if(list.size() >= 2) { end = list.get(list.size()-2); } while(start>end) { list.add(start); start--; } }else { int k = b; int ele = 2; while(k-->0) { list.add(ele); list.add(ele-1); ele+=2; } int end = list.get(list.size()-2); end++; while(end<=n) { list.add(end); end++; } } for(int i: list) { out.append(i + " "); } out.append("\n"); } out.flush(); } public static int[] convertToIntPrimitiveArray(String[] str) { return Stream.of(str).mapToInt(Integer::parseInt).toArray(); } public static Integer[] convertToIntArray(String[] str) { Integer[] arr = new Integer[str.length]; for(int i=0;i<str.length;i++) { arr[i] = Integer.parseInt(str[i]); } return arr; } public static Long[] convertToLongArray(String[] str) { Long[] arr = new Long[str.length]; for(int i=0;i<str.length;i++) { arr[i] = Long.parseLong(str[i]); } return arr; } public static long[] convertToLongPrimitiveArray(String[] str) { return Stream.of(str).mapToLong(Long::parseLong).toArray(); } public static void printYes() throws IOException { out.append("YES" + "\n"); } public static void printNo() throws IOException { out.append("NO" + "\n"); } public static void printNumber(long num) throws IOException { out.append(num + "\n"); } public static long hcf(long a, long b) { if(b==0) return a; return hcf(b, a%b); } public static int findSet(int[] parent, int[] rank, int v) { if(v==parent[v]) { return v; } parent[v] = findSet(parent, rank, parent[v]); return parent[v]; } public static void unionSet(int[] parent, int[] rank, int a, int b) { a = findSet(parent, rank, a); b = findSet(parent, rank, b); if(a == b) { return; } if(rank[a] < rank[b]) { int temp = a; a = b; b = temp; } parent[b] = a; if(rank[a] == rank[b]) { rank[a]++; } } public static void makeSet(int[] parent, int[] rank, int v) { parent[v] = v; rank[v] = 0; } public static long modularDivision(long a, long b, int mod) { if(a==0) return 1; a %= mod; long res = 1L; while(b > 0) { if((b&1)==1) { res = (res * a)%mod; } a = (a*a)%mod; b >>= 1; } return res; } public static void customSort(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); return; } public static long[] factorial(int n, int mod) { long[] fact = new long[n+1]; fact[0] = 1; for(int i=1;i<fact.length;i++) { fact[i] = (i*fact[i-1] + mod)%mod; } return fact; } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
9bec6224298e89583026891a29551b90
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /** * @author Naitik * */ public class Main { static FastReader sc=new FastReader(); static long dp[]; //static int v[][]; // static int mod=998244353;; static int mod=1000000007; static int max; static int bit[]; //static long fact[]; // static long A[]; // static TreeMap<Integer,Integer> map; //static StringBuffer sb=new StringBuffer(""); static HashMap<Integer,Integer> map; static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) { // StringBuffer sb=new StringBuffer(""); int ttt=1; ttt =i(); outer :while (ttt-- > 0) { int n=i(); int y=(n-1)/2; int a=i(),b=i(); if(a>y || b>y) { out.println("-1"); continue outer; } if(n%2!=0) { int p=max(a,b); int q=min(a,b); if(p==q && p==y) { out.println("-1"); continue outer; } } if(Math.abs(a-b)>1) { out.println("-1"); continue outer; } if(a==b && a==y) { int c=1; int d=n; for(int i=0;i<n;i++) { if(i%2==0) { out.print(c+" "); c++; } else { out.print(d+" "); d--; } } out.println(); } else if(a==b) { int c=1; int d=n; int f=0; while(b>=0) { if(b==0) { out.print(d+" "); d--; for(;d>=c;d--) { out.print(d+" "); } // for(;c<=d;c++) { // out.print(c+" "); // } out.println(); break; } else { if(f==0) { out.print(d+" "+c+" "); } d--; c++; b--; } } } else { int c=1; int d=n; int f=0; if(a>b) { while(a>=0) { if(a==0) { // for(;c<=d;c++) { // out.print(c+" "); // } for(;d>=c;d--) { out.print(d+" "); } out.println(); break; } else { if(f==0) { out.print(c+" "+d+" "); } d--; c++; a--; } } } else { while(b>=0) { if(b==0) { // out.print(c+" "); // c++; // for(;d>=c;d--) { // out.print(d+" "); // } for(;c<=d;c++) { out.print(c+" "); } out.println(); break; } else { if(f==0) { out.print(d+" "+c+" "); } d--; c++; b--; } } } } } //System.out.println(sb.toString()); out.close(); //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 } static class Pair implements Comparable<Pair> { int x; int y; int z; Pair(int x,int y,int z){ this.x=x; this.y=y; this.z=z; } @Override public int compareTo(Pair o) { if(this.x>o.x) return 1; else if(this.x<o.x) return -1; else { if(this.y>o.y) return 1; else if(this.y<o.y) return -1; else return 0; } } // public int hashCode() // { // final int temp = 14; // int ans = 1; // ans =x*31+y*13; // return ans; // } // @Override // public boolean equals(Object o) // { // if (this == o) { // return true; // } // if (o == null) { // return false; // } // if (this.getClass() != o.getClass()) { // return false; // } // Pair other = (Pair)o; // if (this.x != other.x || this.y!=other.y) { // return false; // } // return true; // } // /* FOR TREE MAP PAIR USE */ // public int compareTo(Pair o) { // if (x > o.x) { // return 1; // } // if (x < o.x) { // return -1; // } // if (y > o.y) { // return 1; // } // if (y < o.y) { // return -1; // } // return 0; // } } static int find(int A[],int a) { if(A[a]==a) return a; return A[a]=find(A, A[a]); } //static int find(int A[],int a) { // if(A[a]==a) // return a; // return find(A, A[a]); //} //FENWICK TREE static void update(int i, int x){ for(; i < bit.length; i += (i&-i)) bit[i] += x; } static int sum(int i){ int ans = 0; for(; i > 0; i -= (i&-i)) ans += bit[i]; return ans; } //END static void add(int v) { if(!map.containsKey(v)) { map.put(v, 1); } else { map.put(v, map.get(v)+1); } } static void remove(int v) { if(map.containsKey(v)) { map.put(v, map.get(v)-1); if(map.get(v)==0) map.remove(v); } } public static int upper(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { ans=mid; l=mid+1; } else { u=mid-1; } } return ans; } public static int lower(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { l=mid+1; } else { ans=mid; u=mid-1; } } return ans; } static int[] copy(int A[]) { int B[]=new int[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static long[] copy(long A[]) { long B[]=new long[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void reverse(long A[]) { int n=A.length; long B[]=new long[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void reverse(int A[]) { int n=A.length; int B[]=new int[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static int[][] input(int n,int m){ int A[][]=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { A[i][j]=i(); } } return A; } static char[][] charinput(int n,int m){ char A[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=s(); for(int j=0;j<m;j++) { A[i][j]=s.charAt(j); } } return A; } static int nextPowerOf2(int n) { n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n; } static int highestPowerof2(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static long highestPowerof2(long x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long [] prefix(long A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] prefix(int A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] suffix(long A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static long [] suffix(int A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static void fill(int dp[]) { Arrays.fill(dp, -1); } static void fill(int dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(int dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(int dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static void fill(long dp[]) { Arrays.fill(dp, -1); } static void fill(long dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(long dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(long dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long power(long x, long y, long p) { if(y==0) return 1; if(x==0) return 0; long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long power(long x, long y) { if(y==0) return 1; if(x==0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void print(int A[]) { for(int i : A) { System.out.print(i+" "); } System.out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { return ((x%mod + mod)%mod); } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static String sort(String s) { Character ch[]=new Character[s.length()]; for(int i=0;i<s.length();i++) { ch[i]=s.charAt(i); } Arrays.sort(ch); StringBuffer st=new StringBuffer(""); for(int i=0;i<s.length();i++) { st.append(ch[i]); } return st.toString(); } static HashMap<Integer,Integer> hash(int A[]){ HashMap<Integer,Integer> map=new HashMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static HashMap<Long,Integer> hash(long A[]){ HashMap<Long,Integer> map=new HashMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Integer,Integer> tree(int A[]){ TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Long,Integer> tree(long A[]){ TreeMap<Long,Integer> map=new TreeMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
4e610024dabcf5d47c0c596f477a6dc3
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; import java.io.*; public class Omar { static PrintWriter pw = new PrintWriter(System.out); static Scanner sc = new Scanner(System.in); public static void main(String[] args) throws IOException { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(),a=sc.nextInt(),b=sc.nextInt(); int max=n-2; if(a+b>max)pw.println(-1); else { if(a>=b) { if(b<a-1) pw.println(-1); else { int c=1; for(int i=0;i<n-a-b-1;i++) { pw.print(c+++" "); } c--; int x=c; c+=2; int c2=c-1; for(int i=0;i<n-x;i++) { if(i%2==0 && c<=n) { pw.print(c+" "); c+=2; } else { pw.print(c2+" "); c2+=2; } } pw.println(); } } else { if(a<b-1) pw.println(-1); else { int c=n; for(int i=0;i<n-a-b-1;i++) { pw.print(c--+" "); } c++; int x=c; c-=2; int c2=c+1; for(int i=0;i<x-1;i++) { if(i%2==0 && c>=1) { pw.print(c+" "); c-=2; } else { pw.print(c2+" "); c2-=2; } } pw.println(); } } } } pw.flush(); } 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 class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws IOException { br = new BufferedReader(new FileReader(file)); } 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 String readAllLines(BufferedReader reader) throws IOException { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line); content.append(System.lineSeparator()); } return content.toString(); } 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(); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
05a7aed4db154219f832e7f6472a5c02
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { static FastReader fr; static int arrForIndexSort[]; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair{ int first; int second; Pair(int first, int second){ this.first = first; this.second = second; } @Override public boolean equals(Object b) { Pair a = (Pair)b; if(this.first == a.first && this.second==a.second) { return true; } return false; } } class PairSorter implements Comparator<Main.Pair>{ public int compare(Pair a, Pair b) { if(a.first!=b.first) { return a.first-b.first; } return a.second-b.second; } } static class DoublePair{ double first; double second; DoublePair(double first, double second){ this.first = first; this.second = second; } @Override public boolean equals(Object b) { Pair a = (Pair)b; if(this.first == a.first && this.second==a.second) { return true; } return false; } } class DoublePairSorter implements Comparator<Main.DoublePair>{ public int compare(DoublePair a, DoublePair b) { if(a.second>b.second) { return 1; } else if(a.second<b.second) { return -1; } return 0; } } class IndexSorter implements Comparator<Integer>{ public int compare(Integer a, Integer b) { //desc if(arrForIndexSort[b]==arrForIndexSort[a]) { return b-a; } return arrForIndexSort[b]-arrForIndexSort[a]; } } class ListSorter implements Comparator<List>{ public int compare(List a, List b) { return b.size()-a.size(); } } static class DisjointSet{ int[] dsu; public DisjointSet(int n) { makeSet(n); } public void makeSet(int n) { dsu = new int[n+1]; //*** 1 Based indexing *** for(int i=1;i<=n;i++) { dsu[i] = -1; } } public int find(int i) { while(dsu[i] > 0) { i = dsu[i]; } return i; } public void union(int i, int j) { int iRep = find(i); int jRep = find(j); if(iRep == jRep) { return; } if(dsu[iRep]>dsu[jRep]) { dsu[jRep] += dsu[iRep]; dsu[iRep] = jRep; } else { dsu[iRep] += dsu[jRep]; dsu[jRep] = iRep; } } } public static void main(String[] args) { fr = new FastReader(); int T = 1; T = fr.nextInt(); int t1 = T; while (T-- > 0) { solve(); } } public static void solve() { int n = fr.nextInt(); int a = fr.nextInt(); int b = fr.nextInt(); int min = 1; int max = n; int total = n; int count = Math.max(a, b)*2+1; if(a==b) { count++; } if(Math.abs(a-b)>1 || count>n) { System.out.println(-1); }else { StringBuilder sb = new StringBuilder(); int lastappended = 0; if(a==0 && b==0) { for(int i=1;i<=n;i++) { sb.append(i).append(" "); } } else if(a>=b) { int temp = a; boolean isMax = true; int starter = min = 1; int ender = max = count; if(a>b) { starter = min = n-count+1; max = n; } sb.append(min++).append(" "); lastappended = min-1; while(temp>0) { if(isMax) { lastappended = max--; temp--; } else { lastappended = min++; } isMax = !isMax; sb.append(lastappended).append(" "); } lastappended = min++; sb.append(lastappended).append(" "); if(a==b) { sb.append(max--).append(" "); lastappended = max+1; } int tempcount = n-count; while(tempcount-->0) { if(a==b) { sb.append(++ender).append(" "); } else { sb.append(--starter).append(" "); } } } else { boolean isMax = false; min = 1; int starter = max = count; sb.append(max--).append(" "); lastappended = max+1; int temp = b; while(temp>0) { if(isMax) { lastappended = max--; } else { lastappended = min++; temp--; } isMax = !isMax; sb.append(lastappended).append(" "); } lastappended = max--; sb.append(lastappended).append(" "); int tempcount = n-count; while(tempcount-->0) { sb.append(++starter).append(" "); } } System.out.println(sb.toString()); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
d2051601728682044e8b5062f2923361
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; public class A { //--------------------------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 long ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static long mod = 1000000007; //-----------------------------------------------------------------------// //--------------------------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(), a = sc.ni(), b = sc.ni(); if(Math.abs(a-b)>1) { w.p(-1); return; } ArrayDeque<Integer> q = new ArrayDeque<>(); if(a > b) { if(a > Math.ceil((n-2)/2.0) || b > (n-2)/2) { w.p(-1); return; } else { int ct = 0; int ct2 = 0; boolean f = false; for(int i = n; i > 0; i--) { if(ct >= a && ct2 > b) { q.addFirst(i); continue; } if(!f) { q.addFirst(i-1); ct++; } else { q.addFirst(i+1); ct2++; } f = !f; } } } else if(b > a) { if(b > Math.ceil((n-2)/2.0) || a > (n-2)/2) { w.p(-1); return; } else { int ct = 0; int ct2 = 0; boolean f = false; for(int i = 1; i <= n; i++) { if(ct >= b && ct2 > a) { q.addLast(i); continue; } if(!f) { q.addLast(i+1); ct++; } else { q.addLast(i-1); ct2++; } f = !f; } } } else { if(a > (n-2)/2 || b > (n-2)/2) { w.p(-1); return; } int ct = 0; int ct2 = 0; boolean f = false; q.add(1); for(int i = 2; i <= n; i++) { if(ct >= a && ct2 >= b) { q.addLast(i); continue; } if(!f) { q.addLast(i+1); ct++; } else { q.addLast(i-1); ct2++; } f = !f; } } for(int i: q) { w.pr(i+" "); } w.pl(); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
94b1d65a96a805b4c0d0485786c994a4
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
//package codeforce.div2.r758; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.HashSet; import static java.lang.System.out; import static java.util.stream.Collectors.joining; /** * @author pribic (Priyank Doshi) * @see <a href="https://codeforces.com/contest/1608/problem/B" target="_top">https://codeforces.com/contest/1608/problem/B</a> * @since 11/12/21 3:45 PM */ public class B { static FastScanner sc = new FastScanner(System.in); public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { int T = sc.nextInt(); for (int tt = 1; tt <= T; tt++) { int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); if (Math.abs(a - b) > 1 || (n - a - b) < 2) System.out.println(-1); else if (a == 0 && b == 0) { for (int i = 1; i <= n; i++) System.out.print(i + " "); System.out.println(); } else if (a == 0 && b == 1) { System.out.print(n + " "); for (int i = 1; i <= n - 1; i++) System.out.print(i + " "); System.out.println(); } else if (a == 1 && b == 0) { System.out.print("1 "); for (int i = n; i > 1; i--) System.out.print(i + " "); System.out.println(); } else { int[] ans = new int[n]; int idx = 1; int first = 0; int second = 0; int diff1 = 0; int diff2 = 0; int diff3 = 0; int st = 0; if (a > b) { first = n; second = 1; diff1 = -1; diff2 = 1; st = n - a; diff3 = -1; } else { first = 1; second = n; diff1 = 1; diff2 = -1; st = b + 1; diff3 = 1; } if (a == b) { diff3 = -1; st = n - a; } for (int i = 0; i < Math.max(a, b); i++, idx += 2, first += diff1) ans[idx] = first; idx = 2; for (int i = 0; i < Math.min(a, b); i++, idx += 2, second += diff2) ans[idx] = second; idx = a + b + 1; while (idx < n) { ans[idx++] = st; st += diff3; } idx = 0; while (ans[idx] == 0) { ans[idx++] = st; st += diff3; } StringBuilder sb = new StringBuilder(); for (int num : ans) sb.append(num).append(" "); System.out.println(sb); } } } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f), 32768); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
d0bf12da6cf8329b88128413ea11a496
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
/* Challenge 1: Newbie to CM in 1year (Dec 2021 - Nov 2022) 🔥 5* Codechef Challenge 2: CM to IM in 1 year (Dec 2022 - Nov 2023) 🔥🔥 6* Codechef Challenge 3: IM to GM in 1 year (Dec 2023 - Nov 2024) 🔥🔥🔥 7* Codechef Goal: Become better in CP! Key: Consistency! */ // New Concept: Derangements => D(n)=(n-1)*[D(n-1)+D(n-2)] import java.util.*; import java.io.*; import java.math.*; public class Coder { static StringBuffer str=new StringBuffer(); static int n, a, b; static void solve(){ if(Math.abs(a-b)>1){ str.append("-1\n"); return; } if(n%2==1){ if((a>=n/2 && b>=n/2) || a>n/2 || b>n/2){ str.append("-1\n"); return; } }else{ if(a>=n/2 || b>=n/2 || a>n/2 || b>n/2){ str.append("-1\n"); return; } } // if((n%2==1 && a==n/2 && b==n/2) || a>n/2 || b>n/2 || Math.abs(a-b) > 1){ // str.append("-1\n"); // return; // } if(a==b){ int l=1, r=n; for(int i=0;i<a;i++){ str.append(l++).append(" ").append(r--).append(" "); } for(int i=l;i<=r;i++) str.append(i).append(" "); str.append("\n"); } if(a<b){ int l=1, r=n; for(int i=0;i<b;i++){ str.append(r--).append(" ").append(l++).append(" "); } for(int i=l;i<=r;i++) str.append(i).append(" "); str.append("\n"); } if(a>b){ int l=1, r=n; for(int i=0;i<a;i++){ str.append(l++).append(" ").append(r--).append(" "); } for(int i=r;i>=l;i--) str.append(i).append(" "); str.append("\n"); } } public static void main(String[] args) throws java.lang.Exception { BufferedReader bf; PrintWriter pw; boolean lenv=false; if(lenv){ bf = new BufferedReader( new FileReader("input.txt")); pw=new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); }else{ bf = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); } int t = Integer.parseInt(bf.readLine().trim()); while (t-- > 0) { String []st=bf.readLine().trim().split("\\s+"); n=Integer.parseInt(st[0]); a=Integer.parseInt(st[1]); b=Integer.parseInt(st[2]); solve(); } pw.print(str); pw.flush(); // System.outin.print(str); } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
9086f37a3728bf707ce3ef762ac8d856
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; public class maxima { public static void main(String[] args){ Scanner sc=new Scanner(System.in); int t,j,i,n,a,b,p,q; t=sc.nextInt(); for(j=1;j<=t;j++){ n=sc.nextInt(); a=sc.nextInt(); b= sc.nextInt(); p=1;q=n; if(a==b&&a<=(n-2)/2){ System.out.print((p++)+" "); for(i=1;i<=a;i++) System.out.print((q--)+" "+(p++)+" "); for(i=p;i<=q;i++) System.out.print(i+" "); } else if((a-b)==1&&a<=(int)Math.ceil((n-2)/2.0)){ for(i=1;i<=a;i++) System.out.print((p++)+" "+(q--)+" "); for(i=q;i>=p;i--) System.out.print(i+" "); } else if((b-a)==1&&b<=(int)Math.ceil((n-2)/2.0)){ for(i=1;i<=b;i++) System.out.print((q--)+" "+(p++)+" "); for(i=p;i<=q;i++) System.out.print(i+" "); } else System.out.print(-1); System.out.println(); } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
e683d892f736073ecc2b3e44c4f17d11
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; public class Main { public static void main(String []args) { int t; Scanner in=new Scanner(System.in); t=in.nextInt(); while((t--)!=0) { int n; n=in.nextInt(); int a,b; a=in.nextInt(); b=in.nextInt(); if(Math.abs(a-b)>1 || (a+b+2)>n) { System.out.println(-1); continue; } if(a>b) { int l=1; int r=n; int i; for(i=1;i<=a;i++) { System.out.print(l++ +" "); System.out.print(r-- +" "); } for(i=r;i>=l;i--) System.out.print(i+" "); System.out.println(); } else if(a<b) { int l=1; int r=n; int i; for(i=1;i<=b;i++) { System.out.print(r-- +" "); System.out.print(l++ +" "); } for(i=l;i<=r;i++) System.out.print(i+" "); System.out.println(); } else { int l=1; int r=n; int i; for(i=1;i<=b;i++) { System.out.print(r-- +" "); System.out.print(l++ +" "); } for(i=r;i>=l;i--) System.out.print(i+" "); System.out.println(); } } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
3af4dc7e30db98e7eedcf3482339c839
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.Scanner; public class _08_Build_The_Permutation { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int test=Integer.parseInt(sc.next());sc.nextLine(); for(int i=0;i<test;i++) { String inputSplit[]=sc.nextLine().split(" "); int n=Integer.parseInt(inputSplit[0]); int a=Integer.parseInt(inputSplit[1]); int b=Integer.parseInt(inputSplit[2]); int flag=0; if(a+b>n-2){ System.out.println("-1");} else if(Math.abs(a-b)>1){ System.out.println("-1");} else{ if(a==0&&b==0) { for(int j=0;j<n;j++) { System.out.print((j+1)+" "); } System.out.println(); } else if(a==1&&b==0) { for(int j=1;j<=n-2;j++) { System.out.print(j+" "); } System.out.println(n+" "+(n-1)); } else if(a==0&&b==1) { System.out.println("2 1 "); for(int j=3;j<=n;j++) {System.out.print(j+" "); } System.out.println(); } else { int x; if(a>b) { x=a+b+1; for(int j=1;j<=n-x;j++){System.out.print(j+" ");} for(int j=n-x+1;j<=n;j+=2) { System.out.print((j+1)+" "+(j)+" "); }System.out.println(); } else if(b>a) { x=a+b+1; for(int j=1;j<=x;j+=2) { System.out.print((j+1)+" "+j+" "); } for(int j=x+1;j<=n;j++) { System.out.print(j+" "); } System.out.println(); } else { x=a+b; for(int j=1;j<=x;j+=2) { System.out.print((j+1)+" "+j+" "); } for(int j=x+1;j<=n-2;j++) { System.out.print(j+" "); } System.out.println(n+" "+(n-1)); } } } /*if(a+b>n-2 || Math.abs(a-b)>1) { System.out.println("-1"); } else if(a==0 && b==0) { for(int j=0;j<n;j++) { System.out.print((j+1)+" "); } System.out.println(); } else { int res[]=new int[n]; if(a<b) { for(int j=0;j<a+b;j=j+2) { res[j]=j+2; res[j+1]=j+1; } for(int j=a+b+1;j<n;j++) { res[j]=j+1; } } else if(a>b) { int x=a+b+1; for(int j=n-x+1;j<=n;j=j+2) { res[j]=j+1; res[j+1]=j; } for(int j=1;j<=n-x;j++) { res[j]=j; } } else { for(int j=0;j<a+b-1;j=j+2) { res[j]=j+2; res[j+1]=j+1; } for(int j=a+b;j<n;j++) { res[j]=j+1; } int temp=res[n-2]; res[n-2]=res[n-1]; res[n-1]=temp; } for(int j=0;j<n;j++) { System.out.print(res[j]+" "); } System.out.println(); } }*/ } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
3e1c842913992a93e76cfaf5698c9791
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.io.*; import java.util.*; //import javafx.util.*; public class Main { static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<Integer> g[]; //static ArrayList<ArrayList<TASK>> t; static long mod=(long)(1e9+7); static boolean set[],post[][]; static int prime[],c[]; static int par[]; // static int dp[][]; static HashMap<String,Long> mp; static long max=1; static boolean temp[][]; static int K=0; static int size[],dp[][],iv_A[],iv_B[]; static long modulo = 998244353; public static void main(String args[])throws IOException { /* * star,rope,TPST * BS,LST,MS,MQ */ int t = i(); while(t-- > 0){ int n = i(); int a = i(); int b = i(); int[] arr = new int[n]; for(int i = 0;i < n;i++){ arr[i] = i+1; } if(Math.abs(a-b) > 1 || a + b + 2 > n){ System.out.println(-1); continue; } if(a == b){ for(int i = 1; a > 0;i += 2){ int temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; a--; } }else if(a > b){ for(int i = n-1;a > 0;i -= 2){ int temp = arr[i-1]; arr[i-1] = arr[i]; arr[i] = temp; a--; } }else{ for(int i = 0;b > 0;i += 2){ int temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; b--; } } for(int i = 0;i < n;i++){ System.out.print(arr[i] + " "); } System.out.println(); } } public static void helper(ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> curr, int[] arr,int target,int index){ if(target == 0){ ans.add(new ArrayList<Integer>(curr)); return; } if(index == arr.length){ return; } if(arr[index] <= target){ curr.add(arr[index]); helper(ans,curr,arr,target - arr[index],index); curr.remove(curr.size() - 1); } helper(ans,curr,arr,target,index+1); } static int getmax(ArrayList<Integer> arr){ int n = arr.size(); int max = Integer.MIN_VALUE; for(int i = 0;i < n;i++){ max = Math.max(max,arr.get(i)); } return max; } static boolean check(ArrayList<Integer> arr){ int n = arr.size(); boolean flag = true; for(int i = 0;i < n-1;i++){ if(arr.get(i) != arr.get(i+1)){ flag = false; break; } } return flag; } static int MinimumFlips(String s, int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = (s.charAt(i) == '1' ? 1 : 0); } // Initialize prefix arrays to store // number of changes required to put // 1s at either even or odd position int[] oddone = new int[n + 1]; int[] evenone = new int[n + 1]; oddone[0] = 0; evenone[0] = 0; for (int i = 0; i < n; i++) { // If i is odd if (i % 2 != 0) { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 1 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 0 ? 1 : 0); } // Else i is even else { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 0 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 1 ? 1 : 0); } } // Initialize minimum flips return Math.min(evenone[n],oddone[n]); } static int nextPowerOf2(int n) { int count = 0; // First n in the below // condition is for the // case where n is 0 if (n > 0 && (n & (n - 1)) == 0){ while(n != 1) { n >>= 1; count += 1; } return count; }else{ while(n != 0) { n >>= 1; count += 1; } return count; } } static int length(int n){ int count = 0; while(n > 0){ n = n/10; count++; } return count; } static boolean isPrimeInt(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 int lcs(int[] nums) { int[] tails = new int[nums.length]; int size = 0; for (int x : nums) { int i = 0, j = size; while (i != j) { int m = (i + j) / 2; if (tails[m] <= x) i = m + 1; else j = m; } tails[i] = x; if (i == size) ++size; } return size; } static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } static int f(int A[], int size) { // Add boundary case, when array size is one int[] tailTable = new int[size]; int len; // always points empty slot tailTable[0] = A[0]; len = 1; for (int i = 1; i < size; i++) { if (A[i] < tailTable[0]) // new smallest value tailTable[0] = A[i]; else if (A[i] > tailTable[len - 1]) // A[i] wants to extend largest subsequence tailTable[len++] = A[i]; else // A[i] wants to be current end candidate of an existing // subsequence. It will replace ceil value in tailTable tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; } return len; } static int containsBoth(char X[],int N) { for(int i=1; i<N; i++)if(X[i]!=X[i-1])return i-1; return -1; } static void f(char X[],int N,int A[]) { int c=0; for(int i=N-1; i>=0; i--) { if(X[i]=='1') { A[i]=c; } else c++; A[i]+=A[i+1]; } } static int f(int i,int j,char X[],char Y[],int zero) { if(i==X.length && j==Y.length)return 0; if(i==X.length)return iv_B[j]; //return inversion count here if(j==Y.length)return iv_A[i]; if(dp[i][j]==-1) { int cost_x=0,cost_y=0; if(X[i]=='1') { cost_x=zero+f(i+1,j,X,Y,zero); } else cost_x=f(i+1,j,X,Y,zero-1); if(Y[j]=='1') { cost_y=zero+f(i,j+1,X,Y,zero); } else cost_y=f(i,j+1,X,Y,zero-1); dp[i][j]=Math.min(cost_x, cost_y); } return dp[i][j]; } static boolean f(long last,long next,long l,long r,long A,long B) { while(l<=r) { long m=(l+r)/2; long s=((m)*(m-1))/2; long l1=(A*m)+s,r1=(m*B)-s; if(Math.min(next, r1)<Math.max(last, l1)) { if(l1>last)r=m-1; else l=m+1; } else return true; } return false; } static boolean isVowel(char x) { if(x=='a' || x=='e' || x=='i' ||x=='u' || x=='o')return true; return false; } static boolean f(int i,int j) { //i is no of one //j is no of ai>1 if(i==0 && j==0)return true; //this player has no pile to pick --> last move iska rha hoga if(dp[i][j]==-1) { boolean f=false; if(i>0) { if(!f(i-1,j))f=true; } if(j>0) { if(!f(i,j-1) && !f(i+1,j-1))f=true; } if(f)dp[i][j]=1; else dp[i][j]=0; } return dp[i][j]==1; } static int last=-1; static void dfs(int n,int p) { last=n; System.out.println("n--> "+n+" p--> "+p); for(int c:g[n]) { if(c!=p)dfs(c,n); } } static long abs(long a,long b) { return Math.abs(a-b); } static int lower(long A[],long x) { int l=0,r=A.length; while(r-l>1) { int m=(l+r)/2; if(A[m]<=x)l=m; else r=m; } return l; } static int f(int i,int s,int j,int N,int A[],HashMap<Integer,Integer> mp) { if(i==N) { return s; } if(dp[i][j]==-1) { if(mp.containsKey(A[i])) { int f=mp.get(A[i]); int c=0; if(f==1)c++; mp.put(A[i], f+1); HashMap<Integer,Integer> temp=new HashMap<>(); temp.put(A[i],1); return dp[i][j]=Math.min(f(i+1,s+1+c,j,N,A,mp), s+K+f(i+1,0,i,N,A,temp)); } else { mp.put(A[i],1); return dp[i][j]=f(i+1,s,j,N,A,mp); } } return dp[i][j]; } static boolean inRange(int a,int l,int r) { if(l<=a && r>=a)return true; return false; } static long f(long a,long b) { if(a%b==0)return a/b; else return (a/b)+f(b,a%b); } static void f(int index,long A[],int i,long xor) { if(index+1==A.length) { if(valid(xor^A[index],i)) { xor=xor^A[index]; max=Math.max(max, i); } return; } if(dp[index][i]==0) { dp[index][i]=1; if(valid(xor^A[index],i)) { f(index+1,A,i+1,0); f(index+1,A,i,xor^A[index]); } else { f(index+1,A,i,xor^A[index]); } } } static boolean valid(long xor,int i) { if(xor==0)return true; while(xor%2==0 ) { xor/=2; i--; } return i<=0; } static int next(int i,long pre[],long S) { int l=i,r=pre.length; while(r-l>1) { int m=(l+r)/2; if(pre[m]-pre[i-1]>S)r=m; else l=m; } return r; } static boolean lexo(long A[],long B[]) { for(int i=0; i<A.length; i++) { if(B[i]>A[i])return true; if(A[i]>B[i])return false; } return false; } static long [] f(long A[],long B[],int j) { int N=A.length; long X[]=new long[N]; for(int i=0; i<N; i++) { X[i]=(B[j]+A[i])%N; j++; j%=N; } return X; } static int find(int a) { if(par[a]<0)return a; return par[a]=find(par[a]); } static void union(int a,int b) { b=find(b); a=find(a); if(a!=b) { par[b]=a; } } static void print(char A[]) { for(char c:A)System.out.print(c+" "); System.out.println(); } static void print(boolean A[]) { for(boolean c:A)System.out.print(c+" "); System.out.println(); } static void print(int A[]) { for(int a:A)System.out.print(a+" "); System.out.println(); } static void print(long A[]) { for(long i:A)System.out.print(i+ " "); System.out.println(); } static void print(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } static long lower_Bound(long A[],int low,int high, long x) { if (low > high) if (x >= A[high]) return A[high]; int mid = (low + high) / 2; if (A[mid] == x) return A[mid]; if (mid > 0 && A[mid - 1] <= x && x < A[mid]) return A[mid - 1]; if (x < A[mid]) return lower_Bound( A, low, mid - 1, x); return lower_Bound(A, mid + 1, high, x); } static void sort(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void setGraph(int N) { size=new int[N+1]; // D=new int[N+1]; g=new ArrayList[N+1]; for(int i=0; i<=N; i++) { g[i]=new ArrayList<>(); } } static long pow(long a,long b) { long pow=1L; long x=a; while(b!=0) { if((b&1)!=0)pow=(pow*x)%mod; x=(x*x)%mod; b/=2; } return pow; } static long toggleBits(int x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static boolean isPrime(long N) { if (N<=1) return false; if (N<=3) return true; if (N%2 == 0 || N%3 == 0) return false; for (int i=5; i*i<=N; i=i+6) if (N%i == 0 || N%(i+2) == 0) return false; return true; } static long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b ); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N) { long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } } //Code For FastReader //Code For FastReader //Code For FastReader //Code For FastReader class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st==null || !st.hasMoreElements()) { try { st=new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output
PASSED
a2c310556e0cca602d06029ea780ea52
train_109.jsonl
1639217100
You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &lt; p_i &gt; p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} &gt; p_i &lt; p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.
256 megabytes
import java.util.*; import java.io.*; public class MySolution { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int test=sc.nextInt(); while(test>0) { int n=sc.nextInt(); int a=sc.nextInt(); int b=sc.nextInt(); int arr[]=new int[n]; for(int i=0; i<n; i++) { arr[i]=(i+1); } if(Math.abs(a-b)>1 || (a+b)>n-2) System.out.println("-1"); else { if(a==b) { for(int i=1; a>0; i=i+2) { int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; a--; } } else if(a>b) { for(int i=n-1; a>0; i=i-2) { int temp=arr[i]; arr[i]=arr[i-1]; arr[i-1]=temp; a--; } } else { for(int i=0; b>0; i=i+2) { int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; b--; } } for(int i=0; i<n; i++) { System.out.print(arr[i]+" "); } System.out.println(); } test--; } } }
Java
["3\n4 1 1\n6 1 2\n6 4 0"]
1 second
["1 3 2 4\n4 2 3 1 5 6\n-1"]
NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 &lt; p_2 &gt; p_3$$$, and $$$2$$$ is the only such index, and $$$p_2&gt; p_3 &lt; p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
2fdbf033e83d7c17841f640fe1fc0e55
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,200
For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
standard output